简体   繁体   English

在Java中使用扫描仪时出错

[英]Error using Scanner in java

What's the problem with the object scanner in this code ? 这段代码中的对象扫描器有什么问题?

void exp03(){
    System.out.println("---CREATION DES POINTS---");
    char res = 'O';
    Scanner sc = new Scanner(System.in);
       do{
        Point a = new Point();
        try{
        System.out.println("Entrez la valeur du coordonnée du point suivant X");
        double resx = sc.nextDouble();
        a.setX(resx);
        System.out.println("Entrez la valeur du coordonnée du point suivant Y");
        double resy = sc.nextDouble();
        a.setY(resy);
        }
        catch(CoorExp e){
        System.out.println("ERREUR:coordonnée négative!");  //exit  
        }
        System.out.println("1- Afficher le point creer");
        System.out.println("2- Deplacer le point creer");
        int i = sc.nextInt();
        switch (i){

        case 1 : 
            break;

        case 2 :
            System.out.println("entrer la valeur de deplacement suivant X");
            double depx =sc.nextDouble();
            a.setDx(depx);
            System.out.println("entrer la valeur de deplacement suivant Y");
            double depy =sc.nextDouble();
            a.setDy(depy);
            a.deplace(depx, depy);
            System.out.println("Nouvelles coordonnées du point");
            a.affiche();
            break;
        default:
            System.out.println("Choix Incorrect ! ");


        }
        System.out.println("Voulez vous creez un autre point ? O/N");//exception
        res = sc.next().charAt(0);
        }
        while(res == 'O');  

}

When I chose case 2 , I get this error: 当选择情况2时,出现此错误:

 > Exception in thread "main" java.util.InputMismatchException 
 > java.util.Scanner.throwFor(Scanner.java:864) 
 > java.util.Scanner.next(Scanner.java:1485) 
 > java.util.Scanner.nextDouble(Scanner.java:2413) 
 > com.mbisc.java.Test.exp03(Test.java:115) 
 > com.mbisc.java.Test.<init>(Test.java:9) 
 > com.mbisc.java.Test.main(Test.java:137)

i thing it that scanner is first declare as an int and now after the switch i collect answer with a type double. 我认为扫描仪首先声明为int,现在在切换后我用double类型收集答案。 I'm not pretty sure and i need to understand more how the scanner class works. 我不太确定,我需要更多地了解扫描仪类的工作方式。

Firstly you have to check whether a double had been read: 首先,您必须检查是否已读取double精度型:

if (sc.hasNextDouble())
     double depx = sc.nextDouble();

It may be that a double is not there. 可能是没有double


Or you should state a Locale for your Scanner . 或者,您应该为Scanner声明一个Locale

Scanner sc = new Scanner(System.in).useLocale(Locale.US);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM