ParseInt在一个数组中

时间:2012-12-03 02:17:30

标签: java parseint

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?

3 个答案:

答案 0 :(得分: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
        //}
    }
  }
}

答案 1 :(得分: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();

更新:固定代码格式化

答案 2 :(得分:0)

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