Java扫描程序需要多个输入

时间:2015-01-22 09:16:52

标签: java java.util.scanner

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

我为它的低效率和混乱而道歉,我仍在努力学习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。但是你可以从第二个看到if if语句是3号需要两个输入,我必须在下一行出现之前输入两次。第三个else if语句是数字4,在下一行显示之前需要3个输入,依此类推,每个连续的else if语句。对不起,如果我没有正确解释,有人知道为什么会这样吗?

2 个答案:

答案 0 :(得分:3)

将您的代码更改为:

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

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

nextInt将消耗您的输入。因此,如果您来到第二个if,则第一个if会消耗输入。

nextLine在int值之后消耗<ENTER>是必要的。

答案 1 :(得分:0)

         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();
                }
     }