Java 在线读数字
我从stdin获取了一个输入。此输入将是由多个数字组成的一行。例如,变量行的有效值为:Java 在线读数字,java,Java,我从stdin获取了一个输入。此输入将是由多个数字组成的一行。例如,变量行的有效值为: 1 2 3 4 5 6 7 8 9 10 我知道会有多少个数字,我已经将其存储在变量N中。我试图将这些数字存储在大小为N的数组中 String a=""; for(int i=0; i<line.length(); i++){ if(line.charAt(i)!=' ') a = a+ line.charAt(i); else{ numbers[x+
1 2 3 4 5 6 7 8 9 10
我知道会有多少个数字,我已经将其存储在变量N中。我试图将这些数字存储在大小为N的数组中
String a="";
for(int i=0; i<line.length(); i++){
if(line.charAt(i)!=' ')
a = a+ line.charAt(i);
else{
numbers[x++]=Integer.parseInt(a);
a="";
}
}
numbers[x]=Integer.parseInt(a); //to store the last number in the array
字符串a=”“;
对于(int i=0;i您可以使用String.split()
来分离输入
您可以使用String.split()
来分离输入
您可以使用String#split
:
String[] numbersAsString = line.split(" "); // one space, right?
Listy<Integer> numbers = new ArrayList<String>(); // lists are better here
for (String numberAsString:numbersAsString) {
try {
numbers.add(Integer.parseInt(numberAsString));
} catch (NumberFormatException nfe) {
// input was not a number is not added to the list
}
}
String[]numbersAsString=line.split(“”;//一个空格,对吗?
Listy numbers=new ArrayList();//这里的列表更好
for(字符串numbersastring:numbersastring){
试一试{
add(Integer.parseInt(numberAsString));
}捕获(NumberFormatException nfe){
//输入不是一个没有添加到列表中的数字
}
}
您可以使用String#split
:
String[] numbersAsString = line.split(" "); // one space, right?
Listy<Integer> numbers = new ArrayList<String>(); // lists are better here
for (String numberAsString:numbersAsString) {
try {
numbers.add(Integer.parseInt(numberAsString));
} catch (NumberFormatException nfe) {
// input was not a number is not added to the list
}
}
String[]numbersAsString=line.split(“”;//一个空格,对吗?
Listy numbers=new ArrayList();//这里的列表更好
for(字符串numbersastring:numbersastring){
试一试{
add(Integer.parseInt(numberAsString));
}捕获(NumberFormatException nfe){
//输入不是一个没有添加到列表中的数字
}
}
在任何情况下,使用StringBuilder#append()
连接字符都比反复调用a=a+
更有效。在任何情况下,使用StringBuilder#append()
连接字符都比反复调用a=a+
更有效
String[] numbersAsString = line.split(" "); // one space, right?
Listy<Integer> numbers = new ArrayList<String>(); // lists are better here
for (String numberAsString:numbersAsString) {
try {
numbers.add(Integer.parseInt(numberAsString));
} catch (NumberFormatException nfe) {
// input was not a number is not added to the list
}
}