退出循环当没有更多输入时。

huangapple go评论70阅读模式
英文:

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 &lt; newArraySize; i++){
   System.out.println(&quot;The &quot; + i + &quot; input is &quot; + 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 &lt; newArray.length &amp;&amp; scnr.hasNextInt()) {
        newArray[newArraySize] = scnr.nextInt();
        newArraySize++;
    }

    for (int i = 0; i &lt; newArraySize; i++) {
        System.out.println(&quot;The &quot; + i + &quot; input is &quot; + 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:

--&gt; 1
--&gt; 2
--&gt; 10 11 12 13 14 15 16
--&gt; 20
--&gt; 21

Enter nothing to end data entry and view array contents:

Scanner scnr = new Scanner(System.in);
List&lt;Integer&gt; valuesList = new ArrayList&lt;&gt;();
System.out.println(&quot;Enter all the  Integer values you would like&quot;);
System.out.println(&quot;stored into your int[] array.  You can enter&quot;);
System.out.println(&quot;them either singular or multiple values on a&quot;);
System.out.println(&quot;single line spaced apart with a single white&quot;); 
System.out.println(&quot;space. To stop numerical entry and view your&quot;);
System.out.println(&quot;array contents just enter nothing.&quot;);
System.out.println(&quot;============================================&quot;);
System.out.println();
String inputLine = &quot;&quot;;
while (inputLine.isEmpty()) {
System.out.print(&quot;Enter a numerical value: --&gt; &quot;);
inputLine = scnr.nextLine().trim();
// If nothing is supplied then end the &#39;data entry&#39; loop.
if (inputLine.isEmpty()) {
break;
}
//Is it a string line with multiple numerical values?
if (inputLine.contains(&quot; &quot;) &amp;&amp; inputLine.replace(&quot; &quot;, &quot;&quot;).matches(&quot;\\d+&quot;)) {
String[] values = inputLine.split(&quot;\\s+&quot;);
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
//Is it a string line with a single numerical value?
else if (inputLine.matches(&quot;\\d+&quot;)) {
valuesList.add(Integer.valueOf(inputLine));
}
// If entry is none of the above...
else {
System.err.println(&quot;Invalid numerical data supplied (&quot; + inputLine + &quot;)! Try again...&quot;);
}
inputLine = &quot;&quot;;
}
System.out.println(&quot;============================================&quot;);
System.out.println();
// Convert List&lt;Integer&gt; to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i &lt; valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// Display the int[] Array
for (int i = 0; i &lt; newArray.length; i++) {
System.out.println(&quot;The &quot; + i + &quot; input is &quot; + 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 &lt; newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i &lt; newArraySize; i++){
System.out.println(&quot;The &quot; + i + &quot; input is &quot; + 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(&quot;Input 20 numbers: &quot;);

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) -&gt; 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() &amp;&amp; newArraySize &lt; newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i &lt; newArraySize; i++) {
System.out.println(&quot;The &quot; + i + &quot; input is &quot; + newArray[i]);
}
}
}

huangapple
  • 本文由 发表于 2020年10月11日 05:17:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64298392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定