【发布时间】:2013-10-22 02:39:20
【问题描述】:
这就是我想要做的。让用户输入数字,将它们存储在一个数组中,然后在一行上打印所有这些数字。我也必须使用方法/函数。我认为到目前为止我做得很好,它在 Eclipse 中没有显示错误。我坚持的是将他们的输入存储到一个数组中。我希望他们继续一次输入一个数字,直到他们满意并输入“退出”。尽管环顾四周,但我还没有阅读有关如何将事物存储在数组中的信息,尤其是逐步存储多个事物。到目前为止,这是我的代码,提前感谢您的帮助!
import java.util.Scanner;
public class intarray {
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
String x;
Scanner input = new Scanner(System.in);
while (true) {
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
isNum(x);
int goingintoarray = Integer.parseInt(x);
int array[];
}
}
public static String isNum(String t) {
int user=Integer.parseInt(t);
String convertback = Integer.toString(user);
return convertback;
}
}
【问题讨论】:
-
数组不知道输入的确切数量?
-
“我认为到目前为止我做得很好”我真的很想为此 +1 你。
-
数组是一个固定大小的数据结构。因此,如果退出前的输入数量大于数组的大小,则会出现问题。所以你可以使用 arrayList 来存储数据。而isNum方法不好用检查输入的是Number还是未完成,使用try catch