这个java代码中的错误是什么?

时间:2014-06-22 06:18:09

标签: java netbeans

import java.util.Scanner;

public class Hello{
    public static void main(String[]args){

        Scanner input=new Scanner(System.in);

        System.out.println("Enter ur name");
        String name=input.nextLine();

        System.out.println("enter ur gpa");
        double gpa=input.nextDouble();

        System.out.println("Hi"+name+",ur gpa is "+ gpa);
       }
   }

我收到以下异常:

Exception in thread "main" java.util.InputMismatchException at    
java.util.Scanner.throwFor(Scanner.java:909) at 
java.util.Scanner.next(Scanner.java:1530) at 
java.util.Scanner.nextDouble(Scanner.java:2456) at Hello.main(Hello.java:12) 

3 个答案:

答案 0 :(得分:0)

如果输入除double之外的其他内容,则会发生这种情况。它预计会翻倍;也许你输入了一个字符串或类似的东西。

(整数会上调)

答案 1 :(得分:0)

代码可以很好地工作正常的值按程序的预期传递,即字符串然后加倍。您可能希望为其添加异常处理

    Scanner input=new Scanner(System.in);

    String name = "";
    double gpa = 0;
    boolean correctNameEnetered = false;
    boolean correctGPAEneterd  = false;

    while(true){
         try {
             if(!correctNameEnetered){
                 System.out.println("Enter ur name");
                 name=input.nextLine();
                 correctNameEnetered = true;
             }
         }catch(InputMismatchException ex) {
            System.out.println("Please provide String value for name");
            continue;
         }
         try {
             if(!correctGPAEneterd) {
                System.out.println("enter ur gpa");
                gpa = Double.parseDouble(input.next()); 
                correctGPAEneterd = true;
             }
         }catch(NumberFormatException  ex) {
            System.out.println("Please provide an integer or decimal value for gpa");
            continue;
         }
         break;

    }

    System.out.println("Hi"+name+",ur gpa is "+ gpa);

答案 2 :(得分:0)

你的代码看起来很好,当你在double中输入例如字符串时会发生异常,所以要解决这个问题,你需要捕获这个异常:

 try {
        Scanner input=new Scanner(System.in);

        System.out.println("Enter ur name");
        String name=input.nextLine();

        System.out.println("enter ur gpa");
        double gpa=input.nextDouble();

        System.out.println("Hi"+name+",ur gpa is "+ gpa);
    }catch (Exception e){
            System.out.println(e);
        }