如何修复我的 "java.util.InputMismatchException" 错误?

How do I fix my "java.util.InputMismatchException" error?

我需要它做的就是再次循环,这样用户就可以继续使用该程序。让我知道是否有任何我可以阅读的参考资料,以帮助我更多地了解这个问题。提前致谢。

import java.util.Scanner;

public class Module3Assignment1 {

    // public variables
    public static String letterChosen;
    public static int loop = 0;
    public static double radius, area;
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {

        // tells user what the program is about
        System.out.println("Welcome to the Round Object Calculator");
        System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
        System.out.println("The calculations will be based on the user input radius.");
        System.out.println("");

            // loops while the user wants to calculate information
            while (loop == 0){

                Input();
                System.out.print(Answer());

                System.out.println("Do you want to calculate another round object (Y/N)? ");
                String input = scanner.next().toUpperCase();
                    if (input == "N"){
                        loop = 1;
                        }
            }

        // ending message/goodbye
        Goodbye();
        scanner.close();

    }

    private static void Input(){

        // prompts user for input
        System.out.print("Enter C for circle or S for sphere: ");
        letterChosen = scanner.nextLine().toUpperCase();
        System.out.print("Thank you. What is the radius of the circle (in inches): ");
        radius = scanner.nextDouble();

    }

    private static double AreaCircle(){

        // calculates the area of a circle
        area = Math.PI * Math.pow(radius, 2);
        return area;

    }

    private static double AreaSphere(){

        // calculates the area of a sphere
        area = (4/3) * (Math.PI * Math.pow(radius, 3));
        return area;

    }

    private static String Answer(){

        //local variables
        String answer;

        if(letterChosen == "C"){
            // builds a string with the circle answer and sends it back
            answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", AreaCircle(), "inches");
            return answer;
        }else{
            // builds a string with the sphere answer and sends it back
            answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", AreaSphere(), "cubic inches");
            return answer;
        }
    }

    private static String Goodbye(){

        // local variables
        String goodbye;

        // says and returns the goodbye message
        goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
        return goodbye;
    }

}

下面是控制台输出和执行后出现的错误

Welcome to the Round Object Calculator
This program will calculate the area of a circle of the colume of a sphere.
The calculations will be based on the user input radius.

Enter C for circle or S for sphere: C
Thank you. What is the radius of the circle (in inches): 12
The volume of a sphere with a radius of 12.000000 inches is: 5428.672 cubic inches 
Do you want to calculate another round object (Y/N)? 
Y
Enter C for circle or S for sphere: Thank you. What is the radius of the circle (in inches): C
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextDouble(Scanner.java:2387)
    at Module3Assignment1.Input(Module3Assignment1.java:48)
    at Module3Assignment1.main(Module3Assignment1.java:24)

Concept One

在 Java

中比较字符串时始终使用 .equals Method

所以

if(letterChosen == "C")

应该是if(letterChosen.equals("C")),所以其他

Concept Two.

这可能是您的代码出现问题的原因之一。 您已经从扫描仪的键盘对象中获取了 UserInput class 这就是它给出 else 响应的原因。当您从该对象

获取字符串以外的输入时,尤其会发生这种情况

那是因为 Scanner#nextDouble 方法不会读取您输入的最后一个换行符,因此在下一次调用 Scanner#nextLine 时会消耗该换行符。

WorkAround Fire a blank Scanner#nextLine call after Scanner#nextDouble to consume newline.

Or Use Two Scanner Object.

演示 nextLine() 和 nextInt() 的相同扫描器对象会发生什么

public class 测试 {

    public static void main(String[] args) {
        Scanner keyboard= new Scanner(System.in);
        int n=keyboard.nextInt();

        String userResponse;
        while(true) {
            userResponse = keyboard.nextLine();
            if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
                System.out.println("Great! Let's get started.");
                break;
            }
            else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
                System.out.println("Come back next time " + "" + ".");
                System.exit(0);
            }
            else {
                System.out.println("Invalid response.");
            }
        }
    }

} 

输出

5
Invalid response.

现在更改代码结构以从该扫描器对象获取字符串输入,而不是获取代码工作的另一种数据类型。

将字符串作为先前的输入

public class Test {

    public static void main(String[] args) {
        Scanner keyboard= new Scanner(System.in);
        String n=keyboard.nextLine();
        String userResponse;
        while(true) {
            userResponse = keyboard.nextLine();
            if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
                System.out.println("Great! Let's get started.");
                break;
            }
            else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
                System.out.println("Come back next time " + "" + ".");
                System.exit(0);
            }
            else {
                System.out.println("Invalid response.");
            }
        }
    }

}

输出

j
y
Great! Let's get started.

如果之前没有对该对象的任何响应,您的代码将起作用。

public class Test {

    public static void main(String[] args) {
        Scanner keyboard= new Scanner(System.in);

        String userResponse;
        while(true) {
            userResponse = keyboard.nextLine();
            if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
                System.out.println("Great! Let's get started.");
                break;
            }
            else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
                System.out.println("Come back next time " + "" + ".");
                System.exit(0);
            }
            else {
                System.out.println("Invalid response.");
            }
        }
    }

}

并给我所需的输出

y
Great! Let's get started.

我通常一直在这样做,创建两个扫描仪对象 Class 一个用于获取字符串输入,另一个用于获取其他数据类型的输入 (坦率地说,即使我一直无法弄清楚为什么我需要创建两个对象来接收 java 中的字符串和其他数据类型而没有任何错误。如果有人知道请告诉我)

import java.util.Scanner;

public class Module3Assignment1 {
// public static variables are discouraged... 
private static char letterChosen; //char takes less memory 
private static char useAgain = 'Y'; //just use the answer to loop... 
private static double radius, area;
private static String answer;
private  static Scanner scanner = new Scanner(System.in);


//you might want to clear the screen after the user gave an answer to another round object
private static void clearScreen(){
    for(int i =0;i<50;i++){System.out.print("\n");}
}

public void input(){

    // prompts user for input
    System.out.print("Enter C for circle or S for sphere: ");
    letterChosen = scanner.next().charAt(0);
    System.out.print("Thank you. What is the radius of the circle (in inches): ");
    radius = scanner.nextDouble();
    this.answer= answer(letterChosen);

}

public double areaCircle(double radius){

    // calculates the area of a circle
    area = Math.PI * Math.pow(radius, 2);
    return area;

}

public double areaSphere(double radius){

    // calculates the area of a sphere
    area = (4/3) * (Math.PI * Math.pow(radius, 3));
    return area;

}

public String answer(char letterChosen){

    //local variables
    String answer = "";
    if(letterChosen=='c'||letterChosen=='C'){
        answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", areaCircle(radius), "inches");
    }else{
        answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", areaSphere(radius), "cubic inches");
    }
    return answer;
}

private static String goodbye(){

    // local variables
    String goodbye;

    // says and returns the goodbye message
    goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
    return goodbye;
}

public static void main(String[] args) {

    // tells user what the program is about
    System.out.println("Welcome to the Round Object Calculator");
    System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
    System.out.println("The calculations will be based on the user input radius.");
    System.out.println("");
    Module3Assignment1 ass1 = new Module3Assignment1();

        // loops while the user wants to calculate a round object
        while (useAgain == 'Y'||useAgain=='y'){

            ass1.input();
            System.out.print(answer);
            System.out.println("Do you want to calculate another round object (Y/N)? ");
            useAgain = scanner.next().charAt(0);
            System.out.println(useAgain);
            clearScreen();
        }

    // ending message/goodbye
    System.out.println(goodbye());
    scanner.close();

}

}

我更改的一些内容:

  • 我使用 char 而不是 StringStringchar 占用更多内存
  • 添加了 clearScreen() 方法,当您使用控制台时,该方法 "clears" 屏幕。
  • 我在 areaSphere 和 areaCircle 方法中添加了一个参数 radius 。这使得方法可重用。

  • 我把所有的public静态变量都改成了private static。使用 public 静态变量 非常不鼓励 。您可以阅读 this 找出原因。

  • 并且为了防止 public 静态变量,我创建了一个 Module3Assignment1 实例,而不是让所有内容都处于静态状态。

  • 更改了方法名称的大小写。请遵循驼峰式,这意味着方法的第一个字母是小写的,其他单词的第一个字母是大写的(例如 input(), areaSphere() )

关于比较字符串的评论:

== compares REFERENCES TO THE OBJECT , NOT VALUES

如果要比较两个字符串的值,请使用 .equals().equalsIgnoreCase()。这是一个示例语法:

if(string1.equals(string2)){
//do something
}