【问题标题】:Error when trying to convert string to integer using Integer.parseInt()尝试使用 Integer.parseInt() 将字符串转换为整数时出错
【发布时间】:2019-10-20 02:29:34
【问题描述】:

***更新我的帖子以显示我的所有代码,希望这能提供更多上下文。

当我运行程序时,它会跳过我的第一个“if”语句并引发错误。***

我收到错误Exception in thread "main" java.lang.NumberFormatException: For input string: ""

我正在尝试在 while 循环的第一个 else 语句中将字符串变量转换为 int...错误发生在 int examScore = Integer.parseInt(userInput).

   import java.util.Scanner;//imports scanner

   public class ExamScoresCalculator{

   public static void main(String[] args){



   Scanner scan = new Scanner(System.in);//creates new scanner object 

   //prompts user for lowest possible exam score
   System.out.println("Enter the lowest possible value for the exam: ");
   int lowRange = scan.nextInt();

   //prompts user for highest possible exam score
   System.out.println("Enter the highest possible value for the exam: ");
   int highRange = scan.nextInt();

   boolean flag = true; //while loop flag
   double lowestExamScore = highRange; // holds lowest score
   double highestExamScore = lowRange; //holds highest score
   double totalPoints = 0; //holds sum of all scores entered
   int totalExams = 0; //holds the total number of exams entered by the user

   while (flag == true){
      System.out.println("Enter an exam score between " + lowRange + " and " + highRange + " or type exit. "); //asks user for an exam score within correct range     
      String userInput = scan.nextLine();

      if ((userInput.equals("exit")) || (userInput.equals("Exit")) || (userInput.equals("EXIT"))){ //checks if user enters "exit"
         flag = false; //ends while loop

      }else{      
         int examScore = Integer.parseInt(userInput); //converts user input into integer 

         if (examScore >= lowRange && examScore <= highRange){ //checks if user entered a correct test score
            totalExams += 1; //increments totalExams by 1
            totalPoints += examScore; //adds examScore total to totalPoints

            if (examScore < lowestExamScore){ //checks if the exam score entered is the lowest 
               lowestExamScore = examScore; //updates lowestExamScore variable 
            }

            else if (examScore > highestExamScore){ //checks if exam score entered is the highest 
               highestExamScore = examScore; //updates highestExamScore variable 
            }

         }else{
            System.out.println("Please enter a correct score."); //asks user to enter a correct score 
         }

      }


   }//closing while loop 

   //prints the total number of exams, lowest score, highest score, and average score to screen 
   System.out.println("Total number of exams: " + totalExams);
   System.out.println("Lowest exam score: " + lowestExamScore);
   System.out.println("Highest exam score: " + highestExamScore);
   System.out.println("Average exam score: " + (totalPoints / totalExams)); 

   }//closing main 
   }//closing class


【问题讨论】:

  • 如果您给出除数字以外的任何其他值,那么您将收到此错误,因为您正在转换为整数,对吧?
  • 不相关,但 while (flag = true) 没有做你想做的事。
  • 同样不相关,您不处理“eXit”、“eXIt”、“eXIT”或“ExIT”(以及更多排列!)if (userInput.equalsIgnoreCase("exit"))
  • 您必须在命令行上提供输入。如果你只是按下回车,它将是""(空字符串),你会得到错误(异常)。 Integer.parseInt 需要以字符串的形式给出一个整数,例如“42”。
  • 我知道我需要在命令行上提供输入,但是当我运行程序时它会立即抛出错误。似乎它跳过了“if”并直接进入“else”语句......

标签: java if-statement boolean java.util.scanner parseint


【解决方案1】:

在您按下 ENTER 输入最高分数后,扫描仪会读取整数(nextInt)但也会读取行尾(nextLine)。由于在该行中没有提供文本,因此将其读取为空字符串“”。

您应该在代码中将scanner.nextInt 替换为scanner.nextLine。它应该可以在以下更改中正常工作。

//prompts user for lowest possible exam score
  System.out.println("Enter the lowest possible value for the exam: ");
   int lowRange = Integer.parseInt(scan.nextLine());

   //prompts user for highest possible exam score
System.out.println("Enter the highest possible value for the exam: ");
   int highRange = Integer.parseInt(scan.nextLine());

【讨论】:

  • 感谢您的解释。这对我来说更有意义。
【解决方案2】:

请为userInputexamScore 使用两个输入,这将解决您的问题,因为您不能对StringInteger 数据类型都使用一个值。

(但是当您的输入值为“123”(仅限数字)时,即使这也不适用于您的程序)

【讨论】:

  • 这个答案不正确。可以对 String 和 Integer 数据类型使用单个值
  • @CocoNess,我的回答似乎更新了问题描述。无论如何,您能否解释一下我们如何将单个输入值同时用作字符串和整数。 (也请考虑我部分中引用的段落)
【解决方案3】:

添加 scan.nextLine() 以移动扫描仪以读取下一行(新行)。

System.out.println("Enter the highest possible value for the exam: ");
int highRange = scan.nextInt();
scan.nextLine();   // Add this line 

【讨论】:

  • 前两个 scan.nextLine() 输入以获取最高和最低可能的分数工作正常。当我尝试使用 int ExamScore = Integer.parseInt(userInput) 将 String userInput = nextLine() 转换为 int 时,String userInput = nextLine() 引发错误
  • 我将代码复制到我的 IDE 中,当在 scan.nextLine() 输入后添加 scan.nextLine() 时,它可以正常工作。
  • nextInt 不会将扫描仪推进到下一行。首先 Scanner 必须前进到下一行,然后你可以使用 nextLine
猜你喜欢
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2013-02-28
  • 2017-02-25
相关资源
最近更新 更多