如何修复“java.util.InputMismatchException”错误?

时间:2015-07-08 10:13:57

标签: java compiler-errors mismatch

我需要做的就是再次循环,以便用户可以继续使用该程序。如果有任何我可以阅读的参考资料,请告诉我,以帮助我更多地了解这个问题。提前谢谢。

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)

2 个答案:

答案 0 :(得分:0)

  

概念一

在比较Java中的字符串

时始终使用.equals Method

所以

if(letterChosen == "C")

应该是if(letterChosen.equals("C")),而其他人

  

概念二。

这可能是您的代码发生的原因之一。 您已经从扫描仪类的键盘对象获取了一个UserInput,这就是为什么它会给出else响应。当您从该对象输入非String输入时,尤其会发生这种情况

这是因为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 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.

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

使用String作为上一个输入

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.

我通常一直在创建两个OBJECT of Scanner Class 1来获取String Input而其他来获取其他数据类型输入 (太坦率了,即使我一直无法弄清楚为什么我需要在java中创建两个用于接收String和其他数据类型的Object而没有任何错误。如果有人知道请告诉我)

答案 1 :(得分:0)

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 而不是字符串字符串字符占用更多内存
  • 添加了clearScreen()方法&#34;清除&#34;您使用控制台时的屏幕。
  • 我在areaSphere和areaCircle方法中添加了参数radius。这使得这些方法可以重用。

  • 我将所有公共静态变量更改为private static。使用公共静态变量高度重新。您可以阅读this以找出原因。

  • 为了防止公共静态变量,我创建了一个Module3Assignment1的实例,而不是让所有东西都是静态的。

  • 更改了方法名称的大小写。请遵循camel-casing,这意味着该方法的第一个字母是小写的,其他单词将以大写形式显示第一个字母(例如input(),areaSphere())

关于比较字符串的评论:

  

== 比较参考对象 NOT VALUES

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

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