数组无法识别

时间:2014-08-22 21:10:05

标签: java arrays exception try-catch

我的程序是输入10个数字并将它们加在一起然后显示结果。然后我将较小的数字除以较大的数字并显示结果。用户无法输入字符或零。

我是新人,并且一直为DAYS工作。我没有看到我的错误。

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

我介绍了一个Exception(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);
    }
    }
 }

}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您需要围绕for循环内容的大括号。

答案 2 :(得分:0)

我试图修改附加的代码段。希望这对你有帮助。

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();
    }