简体   繁体   中英

Program compiles but does not run

This is an assignment i have to complete.

Can someone lead me in the right direction?

The program compiles but wont run correctly.

The error is InputMissmatch exception.

The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.

When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.

In order to do so, you need to use the has methods.

Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();

You should do something like this:

if (hope.hasNextFloat())
{
    // Code to execute when you have a proper float, 
    // which you can retrieve with hope.nextFloat()
}
else
{ 
    // Code to execute when the user input is not a float
    // Here you should treat it properly, maybe asking for new input
}

That should be enough to point you in the right direction.

Also, check the Scanner api documentation for further details.

EDIT

Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:

if (hope.hasNextString())
{
   if (hope.nextString().equals("A"))
   {
       // Code for option "A"
   }
   else if (hope.nextString().equals("B"))
   {
       // Code for option "B"
   }
   else ...
}

You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.

Your problem is that you are entering a letter into a float field. In your program you're asking the user to enter a float:

A = hope.nextFloat();

But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.

A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:

String choice = hope.next();

Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example

if (choice.equals("A")) {
        number4 = (number1 + number2 + number3);
        System.out.printf("Your results are:" + (number4));
    } 

And you can do the same thing for the other choices you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM