我正在尝试收集用户输入并在给出输入“再见”后对它们进行排序。但是我不明白如何完成“再见”部分。 这是我到目前为止所拥有的。有人可以解释为什么我不能添加 nextLine() 而不是 nextInt() 并将其更改为字符串。然后我可以用字符串“bye”打破 while 语句,但到目前为止,这些都对我不起作用。
import java.util.*;
public class Work {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] values = new int[1];
int currentSize = 0;
System.out.print("Type a number ");
while( s.hasNextInt())
{
if(currentSize >= values.length)
{
values = Arrays.copyOf(values, values.length + 1);
}
System.out.print("Type: ");
values[currentSize] = s.nextInt();
currentSize++;
Arrays.sort(values);
System.out.print(Arrays.toString( values ) );
}
}
}
最佳答案
Can someone explain why I can't add nextLine() instead of nextInt() and change things to Strings.
可以,您只需处理转换即可。
String input = null;
while(!"bye".equalsIgnoreCase(input))
{
value = Integer.parseInt(input.trim());
//..do stuff with the int value
input = s.nextLine();
}
如果您不想相信用户会输入数字,则可能需要处理 NumberFormatException
。
关于java - 在 Java 中收集数组中的用户输入并打印排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32723506/