0

我试图提示用户输入 x 坐标,但是当我写一个十进制数(例如 2.1)作为输入时,这会导致问题。我该如何解决这个问题?

     import java.util.Scanner;

     public class TwoRetangles{

     public static void main(String[]args){

     Scanner input=new Scanner(System.in);

      System.out.print("Enter the center x coordinate of retangle = ");

      double x1=input.nextDouble();

      }
}

- - - - - - - - - - 配置: - - - - - - - - - -

      Enter the center x coordinate of retangle = 2.1

     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 TwoRetangles.main(TwoRetangles.java:6)

     Process completed.
4

2 回答 2

4

Your code works for me.. Scanner is tied to your system settings I believe, so if its not for US you couldn't use a decimal like 2.1.

If that is the case, do

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

You would need to import java.util.*;

于 2013-10-25T10:20:10.410 回答
0

没有错误。它在我的系统中工作正常。确保你编译它正确。它正在接受值。我试过这段代码,它正在打印 2.1:

import java.util.Scanner;

public class TwoRetangles{

   public static void main(String[]args){

   Scanner input=new Scanner(System.in);

   System.out.print("Enter the center x coordinate of retangle = ");

   double x1=input.nextDouble();

   System.out.print(x1);

      }
}
于 2013-10-25T10:17:48.880 回答