Java 需要多个输入的扫描仪

Java scanner requiring multiple inputs

我想问一个关于我的代码的问题。

对于效率低下和混乱,我深表歉意,我仍在努力学习java。

    System.out.println("Please choose the number corresponding to the operation: ");
    System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: ");

    if (sc.nextInt() == 5) {
        System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1 / denom1));
        System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2 / denom2));
    } else if (sc.nextInt() == 3) {
        System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2));

    } else if (sc.nextInt() == 4) {
        System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1));

    } else if (sc.nextInt() == 1) {
        int d = denom1 * denom2;
        int n1 = num1 * denom2;
        int n2 = num2 * denom1;
        System.out.println("Addition: " + (n1 + n2) + "/" + d);


    } else if (sc.nextInt() == 2) {
        int d = denom1 * denom2;
        int n1 = num1 * denom2;
        int n2 = num2 * denom1;
        System.out.println("Subtract: " + (n1 - n2) + "/" + d);
    }
    else if (sc.nextInt() == 6 ) {
        System.exit(0);
    }
}
}

当我 运行 程序时,第一个 if 语句运行良好,因为我只需要输入一次数字 5。但是,正如您从第二个 else if 语句(即数字 3)中看到的那样需要两次输入,我必须在下一行出现之前输入两次。第三个 else if 语句是数字 4,在下一行出现之前需要 3 个输入,依此类推每个连续的 else if 语句。很抱歉,如果我没有正确解释这一点,有人知道为什么会这样吗?

将您的代码更改为:

int input = sc.nextInt();
sc.nextLine();
if (input == 5) {

和所有其他if (sc.nextInt()...)也。

nextInt 将消耗您的输入。所以如果你来到第二个 if 输入已经被第一个 if 消耗了。

nextLine 必须在 int 值后使用 <ENTER>

         Try to use switch statement.
    package practice;
    import java.util.Scanner;
    public class Stack{
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);  
    System.out.println("ENTER THE 2 NUMBERS");
    int num1=sc.nextInt();
    int num2=sc.nextInt();
    System.out.println("ENTER THE CHOICE");
    int choice='0';
    while(choice!=6)
    {
         choice=sc.nextInt();
        System.out.println(choice);
    switch(choice)
    {
    case 1:
         int add=num1+num2;
        System.out.println("Addition:"+add);
        break;
    case 2:
          System.out.println("Subtract:");
        break;
    case 3:
          System.out.println("Multiply:");
        break;
    case 4:
        System.out.println("Divide:");
        break;
    case 5:
         System.out.println("Your first fraction is:");
         System.out.println("Your second fraction is:");
        break;
    case 6:
        System.exit(0);
        break;
    default:
        System.out.println("LOSER");
        break;
           }
                            }       
    sc.close();
                }
     }