pls help me to solve my problem.
here's my code

import java.io.*;
public class ifelse {

    public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));



     int a;
     System.out.println("Enter your Level");
     a = Integer.parseInt(in.readLine());



     if (a == 1)
       System.out.println("\nYou are Freshman");
     else if (a == 2)
       System.out.println("\nYou are Sophomore");
     else if (a == 3)
       System.out.println("\nYou are Junior");
     else if (a == 4)
       System.out.println("\nYou are Senior");
 	 else if (a == a)
       System.out.println("\nYou are Senior");


     else
       System.out.println("\nInvalid input\nEnter Valid Year Level");

    }
  }

how to prevent this error

Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at ifelse.main(ifelse.java:19)

this code will come out when i enter any letter
thanks for the answer god bless

Recommended Answers

All 28 Replies

It looks like you're entering a non-integer value when you run the program. Does it do this when you enter a 1?

why dont you just use any other integer value instead of string "a" ? and the statement if (a==a) is not a good way to go .but if you have to have "a" , then my suggestion is that you first convert the string read from console into a char[] and then use statements like if (char[0]=='a')System.out.println("you are a seniour");

Member Avatar for coil

First of all, you should probably check for non-numeric values before you parse the input at line 11.

Another problem is this, at line 23:

else if (a == a)

I assume you want to check if the input was "a". In that case, it should be a.equals("a"). Right now, you're simply checking if the variable a is the same as itself, which will always return true.

If you really want to use "a" as an input value, there are two easy ways to do this. One is to catch that "a" first, and then do the parseint. The better way might be to put the parseint into a try block, and put the check for "a" into the catch block. Put a default case, in case they enter something that isn't an int and isn't "a".

sorry i forgot to remove that line...

this code

else if (a == a)
System.out.println("\nYou are Senior");

is deleted on my jcreator

the main prob is how to terminate the exception error or put output message if you enter a letter

i'm sorry i did'nt notice that line, but if you remove that error its process complete without error

Okay, so you don't want "a" as a value? Better still. Put a try block around the parseint, and use the catch block to alert the user ("Please enter a number from 1 to 4") and set a "redo" flag. A do ... while loop is the appropriate control structure here, where the condition would be ... while (redo);

Sound good?

yah... but how to do it??? sorry again i'm new in java

There are plenty of tutorials out there - try searching for "java try catch" or "java exception handling" and sort through what you find.

Briefly, try-catch-finally is a way of identifying a potential source of an exception (the code in the try block) and proivding instructions for dealing with the exception if it arises (the catch block). The "finally" block is code executed regardless of whether an exception arises.

The format is like this:

try {
  // potentially exceptional code
}
catch (NumberFormatException nfe)
{
  // what to do if there's a NumberFormatException
}
catch (SomeOtherException soe)
{
  // maybe you think there'll be another exception (SomeOtherException doesn't 
  // actually exist, don't try to catch it)
}
finally {
  // don't worry about the finally block just now
}

Go do some research, and come back if you have a specific question that reading half a dozen tutorials and articles doesn't clear up.

try this one

import java.io.*;

      class ifelse {



      public static void main(String[] args) throws IOException{

      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));







      int a;

      System.out.println("Enter your Level");

      a = Integer.parseInt(in.readLine());







      if (a == 1)

      System.out.println("\nYou are Freshman");

      else if (a == 2)

      System.out.println("\nYou are Sophomore");

      else if (a == 3)

      System.out.println("\nYou are Junior");

      else if (a == 4)

      System.out.println("\nYou are Senior");

      else if (a == a)

      System.out.println("\nYou are Senior");





      else

     System.out.println("\nInvalid input\nEnter Valid Year Level");



      }

      }

Check this code. Hope this will solve your problem..

import java.io.*;
      public class ifelse {
      public static void main(String[] args) throws IOException{
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String  a;
      System.out.println("Enter your Level");
      a = in.readLine();
      if (a.equals("1"))
      System.out.println("\nYou are Freshman");
     else if (a.equals("2"))
      System.out.println("\nYou are Sophomore");
      else if (a.equals("3"))
      System.out.println("\nYou are Junior");
      else if (a.equals("4"))
      System.out.println("\nYou are Senior");
      else if (a.equals("a"))
      System.out.println("\nYou are Senior");
      else
      System.out.println("\nInvalid input\nEnter Valid Year Level");
      }
  
      }

HERE A SHORTER WAY FOR YOU.INSTEAD OF USING CASCADING IF ELSE STATEMENT WHICH IS VERY HARD TO READ YOU CAN USE SWITCH STATEMENT WHICH IS A SHORTER WAY.

import javax.swing.*;

 class test{

public static void main(String[] args){

	 	  int a;
          String D_Play =" Invalid Input";

          String enter=JOptionPane.showInputDialog("enter num");
                 a=Integer.parseInt(enter);

          switch(a)
{
          case 1:
          System.out.print("You are Freshman");
 	      break;

          case 2:
          System.out.print("You are Sophomore");
          break;

          case 3:
   	      System.out.print("You are Junior");
   	      break;

   	      case 4:
   	      System.out.println("You are Senior");
   	      break;

   	      default:

          JOptionPane.showMessageDialog(null,D_Play," Alert ", JOptionPane.ERROR_MESSAGE);
}}}

Better still:

String[] gradeLevel = {"Freshman", "Sophomore", "Junior", "Senior");

System.out.println("You are "+gradeLevel[a]);

but that doesn't really solve the problem, does it? Your suggestion still crashes in exactly the same way that the original does...

your way of attempting the question is wrong first of all you are entering integer and then you use an if condition to compare int and string that a==a thats wrong.
this is the way study it first...

import javax.swing.*;

    class IfElse
{
    public static void main(String[] args){

    String Dplay= "\nInvalid input\nEnter Valid Year Level";
    char i=0;
    char[] a= new char[5];

    String menu=JOptionPane.showInputDialog("enter num");
    char c = menu.charAt(0);
    a[i]=c;


    if (a[0] == '1')

    JOptionPane.showMessageDialog(null,"You are Freshman");

    else if (a[0] == '2')

    JOptionPane.showMessageDialog(null,"You are Sophomore");

    else if (a[0] == '3')

    JOptionPane.showMessageDialog(null,"You are Junior");

    else if (a[0] == '4')

    JOptionPane.showMessageDialog(null,"You are Senior");

    else if (a[0] == 'a')

    JOptionPane.showMessageDialog(null,"You are Senior");

    else

    JOptionPane.showMessageDialog(null,Dplay,"Alert",JOptionPane.ERROR_MESSAGE);

}}

Um, why is a[] an array?

Because at the same time it compare char value if you enter 'a' and also compare int value if you enter 1,2,3,or 4.

Really? How do you figure that? You never see an int value in that code, and you never use anything beyond a[0].

This isn't a bad way to get around the original problem, the crash when entering a non-numeric value - but it seems like you need to look at the array part again.
What you're doing is getting the input as a String and converting the first character you see to a char, and using that as a switch character. That's a tolerable way to do it (though if you're only getting or setting data, and not branching your code, you should use a lookup rather than a branch) but your explanation of the array suggests that you haven't thought it through very much.

if you have a way do it and show...arguing is easily then to work on

Well, as I said, your way is a plausible solution for the input problem, since you're not trying to do a forced conversion to a possibly unsuitable value. The obvious improvement would be to replace

char [] a;

with

char a;

And, as I said, using a lookup is generally a better procedure than a branch if your decision is simply about which data to use. It allows you to declare literal data in one spot in the code rather than losing it throughout the code, it's more compact, meaning you can have the whole logic of the expression on screen, but there is no sacrifice of readability: an array lookup is easy to understand, and if you know the contents of the array, you know exactly what it'll do. Furthermore, it reduces the chance for error, since you have fewer lines on which to make errors. Repeated case statements give you the opportunity to make mistakes in writing and then again in rewriting - you have to write the same thing over and over, and get it right each time, and then when you read it, you have to distinguish one minor variation - the error - in a field of similar lines. An array lookup is one line, and you have to get it right exactly once.

So, all things considered, I think that the alternative I posted above - putting the alternative strings into an array and then looking them up when needed - is the one I would prefer to write or to maintain. The value of a in that, of course, would come from a parseInt, using a try block as discussed above to handle and report erroneous input.

Does that answer your question?

there are 100 of ways attempting a question

import java.io.*;
public class ifelse {
public class InputStreamReader reader=new InputStreamReader (System.in);
public class BufferedReader input=new InputStreamReader (reader);
public static void main(String[] args) throws Exception{
int a;
System.out.println("Enter your Level");
a = Integer.parseInt(input.readLine());
if (a == 1)
System.out.println("\nYou are Freshman");
else if (a == 2)
System.out.println("\nYou are Sophomore");
else if (a == 3)
System.out.println("\nYou are Junior");
else if (a == 4)
System.out.println("\nYou are Senior");
else if (a == a)
System.out.println("\nYou are Senior");
else
System.out.println("\nInvalid input\nEnter Valid Year Level");
}
}
just try this code...

Member Avatar for coil

there are 100 of ways attempting a question

Yes there are, but there are also better ways.

For example, consider sorting an array. There exists tons of different sorting algorithms, but using mergesort or quicksort is significantly faster than bubble sort.

import java.io.*;
public class ifelse {
...
int a;
System.out.println("Enter your Level");
a = Integer.parseInt(input.readLine());
....
}
just try this code...

... and watch it fail in precisely the same manner described in the very first post in this thread. I don't think that's what's usually meant by "reproducing a bug"...

no it works check my code on page 2

Yeah, I know he posted pretty much what you posted. Remember, you were wrong, too. What was the problem? Something about a NumberFormatException, when the user entered a non-numeric value at the keyboard? That problem is still live in both of your "solutions", despite the fact that the answer was given to you about a week ago.

i think u havnt run it.i checked it,it working properly and by the way the problem was that if you enters the alpha a then it was given that error NumberFormatException string a

Yes, that's the problem, as I just said. Now, what happens when your user mistakenly enters an alphabetical value? Oops, you've just crashed the program - with a NumberFormatException.

A program that dies when the user enters a non-numeric value cannot be considered a working program, and certainly not a solution to a problem of a program dying when a user enters a non-numeric value. Is that so hard to grasp?

Yes, that's the problem, as I just said. Now, what happens when your user mistakenly enters an alphabetical value? Oops, you've just crashed the program - with a NumberFormatException.

A program that dies when the user enters a non-numeric value cannot be considered a working program, and certainly not a solution to a problem of a program dying when a user enters a non-numeric value. Is that so hard to grasp?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.