我有一个整数数组列表,它将由用户填充,我想接受输入直到用户想要。我该怎么办?
我已经尝试过了,但是不满意我。 s是用户的最终令牌。
for(int i=0;input.nextInt()!='s';i++)
{ int a=input.nextInt();
number.add(a);
}
答案 0 :(得分:0)
使用nextInt()
不会解决您的问题,因为一旦用户输入非整数,它将生成一个异常,因此将永远不会执行您的循环条件。另外,由于您的迭代次数未知,因此您应该只使用while
循环而不是使用for
循环。我已经修改了您的代码。请参阅下面的代码和代码注释。
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<>();
String endToken = "s"; // this will be the holder of your end token
while (true) { // iterate while user doesn't input the end token
try {
System.out.println("Enter an integer or enter 's' to exit!"); // ask the user for input
String userInput = input.nextLine(); // get the user input
if (userInput.equals(endToken)) { // check if user input is end token
break; // exit the loop
}
int a = Integer.parseInt(userInput); // convert the input into an int
number.add(a); // add the input to the list
// if an error inputs a String but not the end token then an exception will occur
} catch (Exception e) {
System.out.println("Invalid Input!"); // tell the user that the input is invalid and ask the input again
}
}
input.close(); // don't forget to close the scanner
// loop below is just used to print the user inputs
System.out.println("Your inputs are: ");
for (int i = 0; i < number.size(); i++) {
System.out.println(i);
}
}
}
答案 1 :(得分:0)
您可以使用Regex解析传递的输入,解决方案将排除浮点数和字符串
showModalBottomSheet(
context: context,
builder: (builder){
return Container();
}
);
输入
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
ArrayList<Integer> userNumber = new ArrayList<>();
Pattern p = Pattern.compile("\\d+\\d");
Matcher m = null ;
System.out.println("Enter your number list use chanracter 'NO' or 'no' as the terminator: ");
String input = s.nextLine();
String[] data = input.split(",");
for(String word : data) {
if(word.equals("NO") || word.equals("no")) {
break;
}
//m = p.matcher(word).matches();
if(p.matcher(word).matches()) {
m = p.matcher(word);
m.find();
int n = Integer.valueOf((m.group()));
userNumber.add(n);
}else {
System.out.println("Data entered " + word + " is not a number : ");
}
}
System.out.println("Numbers entered are : " + userNumber);
}
输出
12,12.1,123,"asd",123,"NO","NO"