英文:
Exiting a loop when there are no more inputs
问题
我正在编写一些非常基础的 Java 代码。思路是使用循环将最多 20 个数字写入一个数组。我希望在没有剩余值时退出循环。当前,我的代码会写入数组,但我无法使其在不输入非整数值的情况下退出循环。我已阅读了一些其他帖子,但它们往往使用字符串方法,这会使我的代码显得有些臃肿。我觉得应该有一个简单的解决方案,但我似乎想不出来....
import java.util.Scanner;
public class getArray {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize += 1;
continue;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("第 " + i + " 个输入是 " + newArray[i]);
}
}
}
英文:
I am writing some pretty basic java code. The idea is to use a loop to write up to 20 numbers into an array. I want to exit the loop when there are no values left. Right now, my code will write to the array, but I cannot get it to exit the loop without entering a non-integer value. I have read some other posts, but they tend to use string methods, which would make my code kind of bulky. I feel like there is a simple solution to this, but I can't seem to figure it out....
import java.util.Scanner;
public class getArray{
public static void main (String[] args){
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt()){
newArray[newArraySize] = scnr.nextInt();
newArraySize += 1;
continue;
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
答案1
得分: 2
如果我理解正确的话,您希望限制输入的数字数量与数组大小相匹配?
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length && scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("第 " + i + " 个输入为 " + newArray[i]);
}
}
英文:
If I understand correctly, then you want the input of numbers to be limited to the size of the array?
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length && scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
答案2
得分: 2
以下是翻译好的内容:
另一种选择是:允许输入单个数字或以空格分隔的多个数字,例如:
// --> 1
// --> 2
// --> 10 11 12 13 14 15 16
// --> 20
// --> 21
输入空内容以结束数据输入并查看数组内容:
Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
System.out.println("请输入您想要存储在 int[] 数组中的所有整数值:");
System.out.println("您可以逐个输入,也可以在一行上输入多个值,以单个空格分隔。");
System.out.println("输入空内容以结束数字输入并查看数组内容。");
System.out.println("============================================");
System.out.println();
String inputLine = "";
while (inputLine.isEmpty()) {
System.out.print("输入一个数字:--> ");
inputLine = scnr.nextLine().trim();
// 如果未提供任何内容,则结束“数据输入”循环。
if (inputLine.isEmpty()) {
break;
}
// 是否为包含多个数字值的字符串行?
if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
String[] values = inputLine.split("\\s+");
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
// 是否为包含单个数字值的字符串行?
else if (inputLine.matches("\\d+")) {
valuesList.add(Integer.valueOf(inputLine));
}
// 如果输入不属于上述任何一种情况...
else {
System.err.println("提供了无效的数字数据(" + inputLine + ")!请重试...");
}
inputLine = "";
}
System.out.println("============================================");
System.out.println();
// 将 List<Integer> 转换为 int[]...
int[] newArray = new int[valuesList.size()];
for (int i = 0; i < valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// 显示 int[] 数组
for (int i = 0; i < newArray.length; i++) {
System.out.println(i + " 号输入为 " + newArray[i]);
}
英文:
And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:
--> 1
--> 2
--> 10 11 12 13 14 15 16
--> 20
--> 21
Enter nothing to end data entry and view array contents:
Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
System.out.println("Enter all the Integer values you would like");
System.out.println("stored into your int[] array. You can enter");
System.out.println("them either singular or multiple values on a");
System.out.println("single line spaced apart with a single white");
System.out.println("space. To stop numerical entry and view your");
System.out.println("array contents just enter nothing.");
System.out.println("============================================");
System.out.println();
String inputLine = "";
while (inputLine.isEmpty()) {
System.out.print("Enter a numerical value: --> ");
inputLine = scnr.nextLine().trim();
// If nothing is supplied then end the 'data entry' loop.
if (inputLine.isEmpty()) {
break;
}
//Is it a string line with multiple numerical values?
if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
String[] values = inputLine.split("\\s+");
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
//Is it a string line with a single numerical value?
else if (inputLine.matches("\\d+")) {
valuesList.add(Integer.valueOf(inputLine));
}
// If entry is none of the above...
else {
System.err.println("Invalid numerical data supplied (" + inputLine + ")! Try again...");
}
inputLine = "";
}
System.out.println("============================================");
System.out.println();
// Convert List<Integer> to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i < valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// Display the int[] Array
for (int i = 0; i < newArray.length; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
答案3
得分: 1
你的while
循环条件应该是只要newArraySize
小于实际大小即可。以下是带有一些修改的修正示例:
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
} catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i < newArraySize; i++){
System.out.println("第 " + i + " 个输入是 " + newArray[i]);
}
英文:
Your while
loop condition should be as long as newArraySize
is less than the actual size. Here is a fix with some modifications:
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
答案4
得分: 0
使用Java Stream API的解决方案:
Scanner sc = new Scanner(System.in);
System.out.println("输入20个数字:");
int[] arr = IntStream.generate(sc::nextInt) // 创建一个无限流,生成由扫描实例的`nextInt`方法提供的值
.limit(20) // 从流中取出20个值
.toArray(); // 将它们放入数组
System.out.println(Arrays.toString(arr)); // 一次性打印数组内容
此外,还有一个工具方法Arrays.setAll
,允许通过IntUnaryOperator
设置数组的值:
int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());
英文:
A solution using Java Stream API:
Scanner sc = new Scanner(System.in);
System.out.println("Input 20 numbers: ");
int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance
.limit(20) // take only 20 values from stream
.toArray(); // put them into array
System.out.println(Arrays.toString(arr)); // print array contents at once
Also, there's a utility method Arrays.setAll
allowing to set array values via IntUnaryOperator
:
int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());
答案5
得分: 0
While循环应该有数组长度的条件,可以尝试以下代码,代码会在第21次输入后停止接受输入,并显示数组元素。
import java.util.Scanner;
public class AarrayScanner {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt() && newArraySize < newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("第 " + i + " 个输入是 " + newArray[i]);
}
}
}
英文:
While loop should have condition for Array Length, kindly try below code which will stop taking inputs after 21st input and array elements will be displayed.
import java.util.Scanner;
public class AarrayScanner {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt() && newArraySize < newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论