简体   繁体   中英

Why does my Java calculator pause at loop?

After calculator() has ran, my program pauses...unless I enter an input to unpause the program. Then it continues to run and it prints out. However the input that I entered earlier to unpause the program is stored into answer . Please read my comments in the code to have a better understanding. If you still don't understand then feel free to copy the code to see what I am talking about.

public static void main(String[] args) {
    boolean repeat = true;
        while (repeat){
            calculator(); //-Program pauses after this has ran.
            System.out.println("Do you wish to repeat(y/n)?"); // This does not appear unless I enter an input.
            String answer = userInput.next(); //The input that I entered earlier to unpause the program gets stored into answer.

                if (answer.equalsIgnoreCase("y")){ 
                    repeat = true;
                } else { repeat = false;}}} //Program terminates here because the input that I used to unpause the program isn't "y".

Full code below:

package calculatorAttempt;
import java.util.Scanner;

class CalculatorV2 {
    static Scanner userInput = new Scanner(System.in);

public static void calculator(){

    System.out.print(":");

    if (userInput.hasNextInt()){
        int num1 = userInput.nextInt();
        System.out.print(":");
        String inString = userInput.next();
        System.out.print(":");
        int num2 = userInput.nextInt();
        System.out.print("=");

            if (inString.equals("+")){
                System.out.print(num1+num2);}

            if (inString.equals("-")){
                System.out.print(num1-num2);}

            if (inString.equals("*")||(inString.equalsIgnoreCase("x"))){
                System.out.print(num1+num2);}

            if (inString.equals("/")){
                float intTofloat = (float)num1/num2;
                System.out.println(intTofloat);}    }//If Integer


    if (userInput.hasNextFloat()){
        float num1 = userInput.nextFloat();
        System.out.print(":");
        String inString = userInput.next();
        System.out.print(":");
        float num2 = userInput.nextFloat();
        System.out.print("=");

            if (inString.equals("+")){
                System.out.print(num1+num2);}

            if (inString.equals("-")){
                System.out.print(num1-num2);}

            if (inString.equals("*")||(inString.equalsIgnoreCase("x"))){
                System.out.print(num1*num2);}

            if (inString.equals("/")){
                System.out.print(num1/num2);}   }//If Float
}//Public Void Calculator

public static void main(String[] args) {
    boolean repeat = true;
        while (repeat){
            calculator();   
            System.out.println("Do you wish to repeat(y/n)?");
            String answer = userInput.next();


                if (answer.equalsIgnoreCase("y")){
                    repeat = true;
                } else { repeat = false;}}
     }//Main
}//Class

I am beginner so please bear with me :^) . Thanks.

This happens because of this line:

if (userInput.hasNextFloat()){

The hasNext...() methods in Scanner are blocking methods. They block if there is no input other than white space in the scanner, waiting for something to be entered. As soon as something real (not spaces or newlines) is entered, then they check whether it is a float, an int or whatever, and return a true/false reply to you.

After you finish an integer calculation, your program calls hasNextFloat() , and therefore, it blocks, waiting until you enter something. If that something is not a float, it will return false, and the if will not work.

You can experiment a little and see:

  • If you run your program and start with a float (say, 17.2 ), the program will show you the Do you wish to repeat? question after it calculates the result.
  • If you run your program and start with an int, and then, after you get the result, enter a float, it will print the : that is asking you for the float operator.

So basically, that should not be an if . It should be an else if structure.

Just use else if instead of if to check userInput.hasNextFloat().

Your code sample will look like.

if (userInput.hasNextInt()){
        int num1 = userInput.nextInt();
        ....
        ....
        ....

    } else if (userInput.hasNextFloat()){
        float num1 = userInput.nextFloat();
        ....
        ....
        ...
    }

You must use hasNext() instead of hasNextInt() and remove the if(hasNextFloat()) part. And use the Number class because it accepts both ints and floats:

if (userInput.hasNext()) {
    Number num1 = userInput.nextByte();
    System.out.print(":");
    String inString = userInput.next();
    System.out.print(":");
    Number num2 = userInput.nextByte();
    System.out.print("=");

    switch (inString) {
        case "+":
            System.out.print(num1.doubleValue() + num2.doubleValue());
            break;

        case "-":
            System.out.print(num1.doubleValue() - num2.doubleValue());
            break;

        case "*":
        case "x":
        case "X":
            System.out.print(num1.doubleValue() * num2.doubleValue());
            break;

        case "/":
            double intTofloat = num1.doubleValue() / num2.doubleValue();
            System.out.println(intTofloat);
            break;

        default:
            System.out.println(INVALID OPERATOR!);
            break;
    }
}

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