【问题标题】:if else condition is not executed properlyif else 条件未正确执行
【发布时间】:2021-12-21 21:42:16
【问题描述】:

我有一个条件,如果用户输入一个负数或大于 100 的数字,或一个字符串,应该打印一条错误消息“这不是一个有效的百分比,我需要一个 0-100 之间的数字。再试一次。”并要求用户重新输入一个有效号码。如果用户决定直接输入,则应计算所有输入并打印平均数量。


   public static void main(String[ ] args) {
   
      int count = 0; //count to stop loop
       
      double[ ] aGrade = new double[SIZE]; 
      String input = new String("");
      Scanner scan = new Scanner(System.in);
      double total = 0; 
      int gTotal = aGrade.length; 
      boolean exit = false; 
      while ((count < SIZE) && (!exit)) {
      
         System.out.print("Enter number " + (count + 1) + ": " + "\n");
         try {
            input = scan.nextLine();
         
            if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
               aGrade[count] = Double.parseDouble(input); //put into the array
               count++; //only increment count if success

            } else 
               System.out.println("That wasn't a valid percentage,"
                  + " I need a number between 0-100. Try again.");
         
         } catch (NumberFormatException nfe) {
            exit = true; //exit loop
         }
      }

      System.out.println("number of grades entered: " + count + "\n");
      for (int i = 0; i < count; i++) { 
      
      
      // print entered grade
         System.out.println("grade " + (i + 1) + ": " + aGrade[i]);   
      }
      for (int i = 0; i < count; i++) {
         total += aGrade[i]; 
      }
   // calculate and print the average
      System.out.println("\n" + "Average grade: " + total /count);  
   

但是当我运行我的代码时,如果我输入字母,它将不允许用户重新输入值,而是打印计算出的任何内容。我认为它在我的 if-else 语句中,但我不确定如何

【问题讨论】:

  • 我修复了你的降价。请修正缩进。
  • @Yunnosch 非常感谢。我是新来的,所以我还不知道要编辑我的帖子。
  • @LMF:点击帖子下方的“编辑”进行编辑。请参阅stackoverflow.com/editing-help 获取编辑帮助。
  • 提示:当你输入字母时,你认为Double.parseDouble 会做什么?那时您的代码会做什么?您是否在调试器中单步执行过代码?
  • @JonSkeet 谢谢。此外,“Double.parseDouble”表示将字符串转换为双精度

标签: java arrays if-statement


【解决方案1】:

当我们尝试将 String 转换为 Double 时,它​​会抛出 java.lang.NumberFormatException。因此,每当您当时输入 String 或 char 而不是 else 时,它​​都会去 catch 块。根据您的代码 else 块仅在用户输入负数或大于 100 数字时执行。

我更新了你的代码。请检查它。

    import java.util.Scanner;

public class Average {

    public static void main(String[] args) {

        int count = 0; // count to stop loop

        double[] aGrade = new double[3];
        String input = new String("");
        Scanner scan = new Scanner(System.in);
        double total = 0;
        int gTotal = aGrade.length;
        boolean exit = false;
        while ((count < 3) && (!exit)) {

            System.out.print("Enter number " + (count + 1) + ": " + "\n");
            try {
                input = scan.nextLine();

                if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
                    aGrade[count] = Double.parseDouble(input); // put into the array
                    count++; // only increment count if success

                } else
                    System.out
                            .println("That wasn't a valid percentage," + " I need a number between 0-100. Try again.");

            } catch (NumberFormatException nfe) {
                nfe.printStackTrace();
                exit = true; // exit loop
            }
        }

        if (!exit) {
            System.out.println("number of grades entered: " + count + "\n");
            for (int i = 0; i < count; i++) {

                // print entered grade
                System.out.println("grade " + (i + 1) + ": " + aGrade[i]);
            }
            for (int i = 0; i < count; i++) {
                total += aGrade[i];
            }
            // calculate and print the average
            System.out.println("\n" + "Average grade: " + total / count);

        }else {
            System.out
            .println("That wasn't a valid percentage," + " I need a number between 0-100. Try again.");
        }
    }
}

【讨论】:

    【解决方案2】:

    如果您输入 letter 作为输入,您将永远不会出现在 if 语句的 else 部分,因为 if 中的代码会引发异常,然后您会在 catch 部分中。另外,您在catch 部分中写了,当NumberFormatException 发生时(当您输入字母而不是数字时),将exit 设置为true,这就是程序不允许您在输入后再次输入的原因信件。修复这些东西,它就会起作用。另外,看看如何调试你的程序,学习这个技巧,它将帮助你在未来解决这类问题。

    【讨论】:

      【解决方案3】:

      试试这样的:

           boolean ok = false;
           try {
              input = scan.nextLine();
              if ("".equals(input)) {
                  ok = true;
                  exit = true;
              } else if (Double.parseDouble(input) >= 0 && Double.parseDouble(input) <= 100) {
                 aGrade[count] = Double.parseDouble(input); //put into the array
                 count++; //only increment count if success
                 ok = true;
              }
           } catch (NumberFormatException nfe) {
              // nothing
           }
           if (!ok) {
              System.out.println("That wasn't a valid percentage,"
                    + " I need a number between 0-100. Try again.");
           }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 2019-05-26
        • 2012-05-19
        • 2012-06-08
        • 1970-01-01
        相关资源
        最近更新 更多