0
import java.util.Scanner;

public class NumAverage {

    public static void main (String [] args)
    {
        //int a,b;
        int[] numbers = new int [10];

        Scanner numreader = new Scanner(System.in);

        try
        {
            System.out.println("Enter 10 num");
            for (int i = 0; i < numbers.length; i++)
                numbers[i] = numreader.nextInt();
                //numbers[i] = Integer.parseInt(s)
            //for (int i = 0; i < numbers.length; i++)
            //{
                //sum += numbers[i];
            //}
        }
        catch(NumberFormatException numfo)
        {
            System.out.println(numfo.getMessage() + "cannot be converted to integer");
        }
  }
}

如果用户尝试输入字符串而不是整数,我如何才能将我从键盘输入到数组中的数字变为 parseInt

4

3 回答 3

1

尝试:

import java.util.Scanner;

public class NumAverage {

public static void main (String [] args)
{
    //int a,b;
    int[] numbers = new int [10];

    Scanner numreader = new Scanner(System.in);
    System.out.println("Enter 10 num");
    for (int i = 0; i < numbers.length; i++) {
        // Without the try and catch you get the appropriate exception,
        // NumberFormatException in this case
        String str = numreader.next();
        numbers[i] = Integer.parseInt(str);

        //try {
        //    numbers[i] = Integer.parseInt(numreader.next());
        //} catch(NumberFormatException e) {
        //    number[i] = 0; // or whatever you want
        //}
    }
  }
}
于 2012-12-03T02:25:10.683 回答
1

这就是我会为你的情况做的事情。

int[] numbers = new int[10];

Scanner numreader = new Scanner(System.in);

System.out.println("Enter 10 numbers");

// Get User Input
for (int i = 0; i < numbers.length; i++) {
    try {
        numbers[i] = Integer.parseInt((String) numreader.nextLine());
    } catch (NumberFormatException numFormatE) {
        System.out.println(numFormatE.getMessage() + "cannot be converted to integer");
        i = i - 1; // Restart current iteration.
    }
}
numreader.close();

// Loop through the number to get sum of the number.
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}
System.out.println(sum);

但是,如果您想在主循环中组合sum,这也应该有效:

int[] numbers = new int[10];
int sum = 0;

Scanner numreader = new Scanner(System.in);

System.out.println("Enter 10 numbers");

// Get User Input
for (int i = 0; i < numbers.length; i++) {
    try {
        numbers[i] = Integer.parseInt((String) numreader.nextLine());
    } catch (NumberFormatException numFormatE) {
        System.out.println(numFormatE.getMessage() + "cannot be converted to integer");
        i = i - 1; // Restart current iteration.
    }
    sum += numbers[i]; // Add the number in loop
}
System.out.println(sum);
numreader.close();

更新:固定代码格式

于 2018-02-06T02:52:30.463 回答
0

如果 s 不是整数,则 Integer.parse(String s) 会抛出 NumberFormatException。所以用 try-catch 子句包围字符串到 int 的转换

于 2012-12-03T02:21:37.197 回答