当用户可以输入 int 和 double 时添加两个数字

Adding two numbers when the user can enter an int and double

提问人:Corey Aoi Senkō Ausby 提问时间:9/14/2015 更新时间:9/14/2015 访问量:176

问:

我需要当用户输入例如 4 和 6.5 时运行程序,反之亦然。 我只有在它或它尝试同时为两者运行它时才运行if else,我得到这样的错误代码:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at class2.AddTwoNumbers.main(AddTwoNumbers.java:28)

如能提供任何协助,将不胜感激

    public class AddTwoNumbers {

        public static void main(String[] args) {
    Scanner inputSource = new Scanner(System.in);
    Scanner runAgain = new Scanner(System.in);
    int input1, input2, result;
    double input3, input4, result2;

    String answer = null;

    do {

         System.out.println("Please enter two numbers: ");
    if(inputSource.hasNextInt()) {

      input1 = inputSource.nextInt();
      input2 = inputSource.nextInt();


      result = input1 + input2;
      System.out.println("The sum of " + input1 + " and " + input2 + " is " + result);

       } else if (!inputSource.hasNextInt()){

              input3 = inputSource.nextDouble();
              input4 = inputSource.nextDouble();

              result2 = input3 + input4;
              System.out.println("The sum of " + input3 + " and " + input4 + " is " + result2);

              } else if (inputSource.hasNextInt() ||   inputSource.hasNextDouble()){
                  input1 = inputSource.nextInt();
                  input3 = inputSource.nextDouble();

                  result2 = input1 + input3;
                  System.out.println("The sum of " + input1 + " and " + input3 + " is " + result2);
    }           
    System.out.println("Do you want to run this again? Enter Y for Yes or N for No: ");
             answer = runAgain.next();


           } while (answer != "N");

           inputSource.close();     
     }

}
java.util.scanner

评论


答:

0赞 Eran 9/14/2015 #1

在这种情况下,使用 读取输入更有意义。这适用于输入和输入。double number = Double.parseDouble(inputSource.nextLine());intdouble

您的代码变得如此简单:

double input1 = Double.parseDouble(inputSource.nextLine());
double input2 = Double.parseDouble(inputSource.nextLine());
double result = input1 + input2;

除此之外,更改为 .while (answer != "N");while (!answer.equals("N"));

-1赞 Rustam 9/14/2015 #2

use 方法而不是并将其解析为 double,这将适用于 and 类型nextLine()nextInt()intdouble

double result;
double input1=Double.parseDouble(inputSource.nextLine());
double input2=Double.parseDouble(inputSource.nextLine());
result=input1+input2;

并且还随while (answer != "N");while (!answer.equals("N"));// since your are comparing string not character