gpt4 book ai didi

java - 数组中的 ParseInt

转载 作者:行者123 更新时间:2023-12-02 07:25:04 25 4
gpt4 key购买 nike

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

最佳答案

尝试:

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
//}
}
}
}

关于java - 数组中的 ParseInt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com