簡體   English   中英

當用戶可以輸入int和double時添加兩個數字

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

我需要程序在用戶輸入例如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();     
     }

}

在這種情況下,使用double number = Double.parseDouble(inputSource.nextLine());讀取輸入更有意義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"); to while (!answer.equals("N"));

使用nextLine()方法而不是nextInt()並將其解析為double,這將適用於intdouble類型

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

並且同時改變while (answer != "N"); with while (!answer.equals("N"));// since your are comparing string not character

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM