计算器 Java 输入

Calculator Java Input

我正在尝试在 java 中制作一个计算器,它可以进行乘法减法和加法运算,具体取决于用户是否希望他们可以选择他们想要的内容。出于某种原因,它给了我一个奇怪的输出 代码

import java.util.Scanner;  // Import the Scanner class

public class calculator {
    public static void main(String args[]){
        Scanner sc= new Scanner(System.in);
            //System.in is a standard input stream  
        System.out.print("Enter first number- ");  
        int a = sc.nextInt();  
        System.out.print("Enter second number- ");  
        int b = sc.nextInt();  
        System.out.print("Do you want to multiply, add, divide, or subtract? ");  
        String c = sc.nextLine();  
        switch(c) {
            case "multiply":
              System.out.print(a * b);
              break;
            case "add":
              System.out.print(a * b);
              break;
            default:
              System.out.print("Invalid input!");
        }


    }
    
}

输出

Enter first number- 2
Enter second number- 2
Do you want to multiply, add, divide, or subtract? Invalid input!

就像我什至没有输入无效输入一样,它只是出于某种原因自行输入

sc.nextInt() 不会读取您输入的 enter 键,因此 sc.nextLine() 将读取该新行并 return 它。使用 sc.next() 而不是 sc.nextLine() 来避免这个问题。当用户输入 add 时,您的代码也会乘以数字,所以我也更改了它。

import java.util.Scanner;  // Import the Scanner class

public class calculator {
    public static void main(String args[]){
        Scanner sc= new Scanner(System.in);
        //System.in is a standard input stream  
        System.out.print("Enter first number- ");  
        int a = sc.nextInt();  
        System.out.print("Enter second number- ");  
        int b = sc.nextInt();  
        System.out.print("Do you want to multiply, add, divide, or subtract? ");  
        String c = sc.next();  
        switch(c) {
            case "multiply":
                System.out.print(a * b);
                break;
            case "add":
                System.out.print(a + b);
                break;
            default:
                System.out.print("Invalid input!");
        }
    }
}

在您请求值之前,扫描仪中可能会留下一些输入。在这种情况下,换行符标记整数的结尾,但不会作为整数的一部分使用。对 nextLine() 的调用发现缓冲区末尾已经有一个未使用的换行符,结果是 returns。在这种情况下,返回一个空字符串。解决此问题的一种方法是先使用未使用的换行符,然后再请求下一行或请求整行,然后从中解析一个整数。

Scanner scan  = new Scanner(System.in);

// Always request a full line
int firstInt = Integer.parse(scan.nextLine());
int secondInt = Integer.parse(scan.nextLine());
String option = scan.nextLine();

// Use an extra call to nextLine() to remove the line break causing the issues
int firstInt = scan.nextInt();
int secondInt = scan.nextInt();
scan.nextLine(); // Consume the unused line break
String option = scan.nextLine();