【问题标题】:Array not Recognized数组无法识别
【发布时间】:2014-08-22 21:10:04
【问题描述】:

我的程序是输入 10 个数字并将它们相加,然后显示结果。然后我将较小的数字除以较大的数字并显示结果。用户不能输入字符或零。

我是新手,已经为此工作了 DAYS。我没有看到我的错误。

现在我的问题是变量 i 未被识别。

我引入了一个异常 (try..catch),但它无法读取。我试着把东西搬过来(我是新来的,我在猜测,看看有什么作用..)我做错了什么,可能是一些愚蠢的小事。我需要一些帮助和新鲜的眼睛。

当用户输入 9999 时,我还需要结束程序。知道那会去哪里吗?因为我快要泪流满面了。

public static void main(String[] args) throws NumberFormatException {
    Scanner in = new Scanner(System.in);
    Scanner input = new Scanner(System.in);

    double[ ] digit = new double[11];
    int sum = 0;
    //Declare an array


    System.out.print("Please Enter Ten Numbers:");
    System.out.println();

    try{
    for (int i = 1; i < digit.length; i++) 
        System.out.print("Numbers " + i + ": ");
        digit[i] = (double)in.nextInt(); //Array Not recognized here
        sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.

     if(digit[i]==0.0)//None of these are recognized either, what did I do? 
        {
            System.out.println("You can't enter zero. Try again");
            --i; //nope
            in.nextLine();//dispose of wrong number
        }
        }catch (NumberFormatException e){

        System.out.println("You Can Only Enter Numbers!");
            --i; //nope, not recognizing here either
            in.nextLine();//dispose of wrong input
        }

    System.out.println("Total Values in Array:"+ sum);
     // Calculate the sum and print the total


    System.out.println();
    System.out.println("Would you like to divide the values?");
    System.out.println("Yes or No to Exit the Program");
    String a = input.next();

     if(a.equalsIgnoreCase("yes")){   
            double [] divisionResult = new double[digit.length / 2];
//Division array declared

            for (int i = 1; i < digit.length; i += 2)
 //These are all good and recognized. No problem with the division part
            {
            double result = digit[i];
            if (result > digit[i + 1]) 
            result = result / digit[i + 1]; 
    else {
            result = digit[i + 1] / result;
        }
            divisionResult [i / 2] = result;
                System.out.println(result);
            }
        }
    else if(a.equalsIgnoreCase("no")){
       System.exit(0);
    }
    }
 }

}

【问题讨论】:

  • 我们需要一个比“变量 i 未被识别”更好的描述。您需要复制/粘贴您收到的确切错误消息。
  • (请注意您在for 语句之后缺少{。(如果您对缩进更加小心,可能会更容易找到其他一些类似的错误。) )
  • 这是我的问题。我将括号放在 for 循环周围,然后我的 try..catch 无法识别对方
  • 仔细匹配您的 {} 字符。使用缩进来帮助你。您应该为您传递的每个 { 缩进 4 个额外的空格,并在传递匹配的 } 时少缩进 4 个空格。

标签: java arrays exception try-catch


【解决方案1】:

你的 for 循环没有大括号。只有它下面的第一行是循环的一部分。

【讨论】:

    【解决方案2】:

    for 循环的内容需要用大括号括起来。

    【讨论】:

      【解决方案3】:

      我已尝试修改附加代码sn-p。希望这对您有所帮助。

      package com.so.general;
      
      import java.util.Scanner;
      
      public class AddNumbers
      {
        private static final int SIZE_OF_ARRAY = 10;
        public static void main(String[] args)
        {
          int counter = 0;
          double sumOfTenDigits = 0.0;
          double[] digit = new double[SIZE_OF_ARRAY];
          int listOfElements = digit.length;
          System.out.print("Please Enter Ten Numbers:"+"\n");
          Scanner readInputFromUser = new Scanner(System.in);
      
          try
          {
              for (counter=0; counter<listOfElements; counter++)
              {
                  System.out.print("Numbers " + (counter+1) + ": ");
                  digit[counter] = Double.parseDouble(readInputFromUser.next());
                  if(digit[counter] == 0.0)
                  {
                      System.out.println("Zero is not allowed. Please try again.");
                      System.out.print("Numbers " + (counter+1) + ": ");
                      digit[counter] = Double.parseDouble(readInputFromUser.next());
                  }
                  sumOfTenDigits += digit[counter];
              }
          }
          catch(NumberFormatException numberFormatExcep)
          {
              System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
              numberFormatExcep.printStackTrace();
              System.exit(0);
          }
      
          System.out.println("Addition is: "+ sumOfTenDigits);
          System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
      
          Scanner continueWithDivide = new Scanner(System.in);
          String userInput = continueWithDivide.nextLine();
      
          closeScanner(readInputFromUser);
          closeScanner(continueWithDivide);
      
          if(readInputFromUser != null)
          {
              readInputFromUser.close();
          }
      
          // Always use static string literals on the left hand side. 
          // This prevents Null pointer exception.
          if("Y".equalsIgnoreCase(userInput))
          {   
              double[] divisionResult = new double[listOfElements/2];
              for(int i=0; i<listOfElements; i+=2)
              {
                 double result = digit[i];
                 if (result > digit[i+1])
                 {
                     result = result/digit[i+1];
                 }
                 else 
                 {
                     result = digit[i+1]/result;
                 }
                 divisionResult[i/2] = result;
                 System.out.println(result);
              }
          }
          else
          {
             System.out.println("You have entered "+userInput+". Terminating the program.");
             System.exit(0);
          }
      }
      
      /**
       * Closed the scanner
       * @param scanner
       */
      public static void closeScanner(Scanner scanner)
      {
          if(scanner != null)
          {   try
              {
                  scanner.close();
              }
              catch(IllegalStateException illegatStateExcep)
              {
                  System.err.println("Scanner is already closed.");
                  illegatStateExcep.printStackTrace();
              }
          }
      }
      

      请注意以下几点:

      • 始终使用正确的缩进。
      • 始终匹配 { }
      • 即使您的iffor 只有一个语句,也请使用{ }

        For example: 
        
        for (int counter=1; i<digit.length; i++) 
        {
           System.out.print("Numbers " + i + ": ");
        }
        

        如果您的程序出现问题,上述三点将为您节省大量时间。

      • 为变量和方法使用正确的名称。
      • 在使用完之后总是关闭 IO 资源。

        For example:
        
        if(scanner != null)
        {
           scanner.close();
        }
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 2016-06-02
        • 1970-01-01
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多