尝试使用 Integer.parseInt() 将字符串转换为整数时出错

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


当我运行该程序时,它会跳过我的第一个“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


      }

幕布斯7119047
浏览 178回答 3
3回答

慕婉清6462132

一旦您按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 scoreSystem.out.println("Enter the highest possible value for the exam: ");   int highRange = Integer.parseInt(scan.nextLine());

慕慕森

请使用userInput和 的两个输入examScore,这将解决您的问题,因为您不能对String和Integer数据类型使用单个值。(但当您的输入值为“123”(仅限数字)时,这是可能的,即使这也不适用于您的程序)

忽然笑

添加 scan.nextLine() 来移动扫描仪以读取下一行(新行)。System.out.println("Enter the highest possible value for the exam: ");int highRange = scan.nextInt();scan.nextLine();   // Add this line 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java