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

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

Exiting a loop when there are no more inputs

问题

  1. 我正在编写一些非常基础的 Java 代码思路是使用循环将最多 20 个数字写入一个数组我希望在没有剩余值时退出循环当前我的代码会写入数组但我无法使其在不输入非整数值的情况下退出循环我已阅读了一些其他帖子但它们往往使用字符串方法这会使我的代码显得有些臃肿我觉得应该有一个简单的解决方案但我似乎想不出来....
  2. import java.util.Scanner;
  3. public class getArray {
  4. public static void main(String[] args) {
  5. Scanner scnr = new Scanner(System.in);
  6. int[] newArray = new int[20];
  7. int newArraySize = 0;
  8. while (scnr.hasNextInt()) {
  9. newArray[newArraySize] = scnr.nextInt();
  10. newArraySize += 1;
  11. continue;
  12. }
  13. for (int i = 0; i < newArraySize; i++) {
  14. System.out.println("第 " + i + " 个输入是 " + newArray[i]);
  15. }
  16. }
  17. }
英文:

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....

  1. import java.util.Scanner;
  2. public class getArray{
  3. public static void main (String[] args){
  4. Scanner scnr = new Scanner(System.in);
  5. int[]newArray = new int[20];
  6. int newArraySize = 0;
  7. while (scnr.hasNextInt()){
  8. newArray[newArraySize] = scnr.nextInt();
  9. newArraySize += 1;
  10. continue;
  11. }
  12. for (int i = 0; i &lt; newArraySize; i++){
  13. System.out.println(&quot;The &quot; + i + &quot; input is &quot; + newArray[i]);
  14. }
  15. }
  16. }

答案1

得分: 2

如果我理解正确的话,您希望限制输入的数字数量与数组大小相匹配?

  1. public static void main(String[] args) {
  2. Scanner scnr = new Scanner(System.in);
  3. int[] newArray = new int[20];
  4. int newArraySize = 0;
  5. while (newArraySize < newArray.length && scnr.hasNextInt()) {
  6. newArray[newArraySize] = scnr.nextInt();
  7. newArraySize++;
  8. }
  9. for (int i = 0; i < newArraySize; i++) {
  10. System.out.println("第 " + i + " 个输入为 " + newArray[i]);
  11. }
  12. }
英文:

If I understand correctly, then you want the input of numbers to be limited to the size of the array?

  1. public static void main(String[] args) {
  2. Scanner scnr = new Scanner(System.in);
  3. int[] newArray = new int[20];
  4. int newArraySize = 0;
  5. while (newArraySize &lt; newArray.length &amp;&amp; scnr.hasNextInt()) {
  6. newArray[newArraySize] = scnr.nextInt();
  7. newArraySize++;
  8. }
  9. for (int i = 0; i &lt; newArraySize; i++) {
  10. System.out.println(&quot;The &quot; + i + &quot; input is &quot; + newArray[i]);
  11. }
  12. }

答案2

得分: 2

以下是翻译好的内容:

另一种选择是:允许输入单个数字或以空格分隔的多个数字,例如:

  1. // --> 1
  2. // --> 2
  3. // --> 10 11 12 13 14 15 16
  4. // --> 20
  5. // --> 21

输入空内容以结束数据输入并查看数组内容:

  1. Scanner scnr = new Scanner(System.in);
  2. List<Integer> valuesList = new ArrayList<>();
  3. System.out.println("请输入您想要存储在 int[] 数组中的所有整数值:");
  4. System.out.println("您可以逐个输入,也可以在一行上输入多个值,以单个空格分隔。");
  5. System.out.println("输入空内容以结束数字输入并查看数组内容。");
  6. System.out.println("============================================");
  7. System.out.println();
  8. String inputLine = "";
  9. while (inputLine.isEmpty()) {
  10. System.out.print("输入一个数字:--> ");
  11. inputLine = scnr.nextLine().trim();
  12. // 如果未提供任何内容,则结束“数据输入”循环。
  13. if (inputLine.isEmpty()) {
  14. break;
  15. }
  16. // 是否为包含多个数字值的字符串行?
  17. if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
  18. String[] values = inputLine.split("\\s+");
  19. for (String vals : values) {
  20. valuesList.add(Integer.valueOf(vals));
  21. }
  22. }
  23. // 是否为包含单个数字值的字符串行?
  24. else if (inputLine.matches("\\d+")) {
  25. valuesList.add(Integer.valueOf(inputLine));
  26. }
  27. // 如果输入不属于上述任何一种情况...
  28. else {
  29. System.err.println("提供了无效的数字数据(" + inputLine + ")!请重试...");
  30. }
  31. inputLine = "";
  32. }
  33. System.out.println("============================================");
  34. System.out.println();
  35. // 将 List<Integer> 转换为 int[]...
  36. int[] newArray = new int[valuesList.size()];
  37. for (int i = 0; i < valuesList.size(); i++) {
  38. newArray[i] = valuesList.get(i);
  39. }
  40. // 显示 int[] 数组
  41. for (int i = 0; i < newArray.length; i++) {
  42. System.out.println(i + " 号输入为 " + newArray[i]);
  43. }
英文:

And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:

  1. --&gt; 1
  2. --&gt; 2
  3. --&gt; 10 11 12 13 14 15 16
  4. --&gt; 20
  5. --&gt; 21

Enter nothing to end data entry and view array contents:

  1. Scanner scnr = new Scanner(System.in);
  2. List&lt;Integer&gt; valuesList = new ArrayList&lt;&gt;();
  3. System.out.println(&quot;Enter all the Integer values you would like&quot;);
  4. System.out.println(&quot;stored into your int[] array. You can enter&quot;);
  5. System.out.println(&quot;them either singular or multiple values on a&quot;);
  6. System.out.println(&quot;single line spaced apart with a single white&quot;);
  7. System.out.println(&quot;space. To stop numerical entry and view your&quot;);
  8. System.out.println(&quot;array contents just enter nothing.&quot;);
  9. System.out.println(&quot;============================================&quot;);
  10. System.out.println();
  11. String inputLine = &quot;&quot;;
  12. while (inputLine.isEmpty()) {
  13. System.out.print(&quot;Enter a numerical value: --&gt; &quot;);
  14. inputLine = scnr.nextLine().trim();
  15. // If nothing is supplied then end the &#39;data entry&#39; loop.
  16. if (inputLine.isEmpty()) {
  17. break;
  18. }
  19. //Is it a string line with multiple numerical values?
  20. if (inputLine.contains(&quot; &quot;) &amp;&amp; inputLine.replace(&quot; &quot;, &quot;&quot;).matches(&quot;\\d+&quot;)) {
  21. String[] values = inputLine.split(&quot;\\s+&quot;);
  22. for (String vals : values) {
  23. valuesList.add(Integer.valueOf(vals));
  24. }
  25. }
  26. //Is it a string line with a single numerical value?
  27. else if (inputLine.matches(&quot;\\d+&quot;)) {
  28. valuesList.add(Integer.valueOf(inputLine));
  29. }
  30. // If entry is none of the above...
  31. else {
  32. System.err.println(&quot;Invalid numerical data supplied (&quot; + inputLine + &quot;)! Try again...&quot;);
  33. }
  34. inputLine = &quot;&quot;;
  35. }
  36. System.out.println(&quot;============================================&quot;);
  37. System.out.println();
  38. // Convert List&lt;Integer&gt; to int[]...
  39. int[] newArray = new int[valuesList.size()];
  40. for (int i=0; i &lt; valuesList.size(); i++) {
  41. newArray[i] = valuesList.get(i);
  42. }
  43. // Display the int[] Array
  44. for (int i = 0; i &lt; newArray.length; i++) {
  45. System.out.println(&quot;The &quot; + i + &quot; input is &quot; + newArray[i]);
  46. }

答案3

得分: 1

你的while循环条件应该是只要newArraySize小于实际大小即可。以下是带有一些修改的修正示例:

  1. Scanner scnr = new Scanner(System.in);
  2. int[] newArray = new int[20];
  3. int newArraySize = 0;
  4. while (newArraySize < newArray.length){
  5. try {
  6. newArray[newArraySize] = scnr.nextInt();
  7. newArraySize++;
  8. } catch(Exception e){
  9. scnr.nextLine();
  10. }
  11. }
  12. for (int i = 0; i < newArraySize; i++){
  13. System.out.println("第 " + i + " 个输入是 " + newArray[i]);
  14. }
英文:

Your while loop condition should be as long as newArraySize is less than the actual size. Here is a fix with some modifications:

  1. Scanner scnr = new Scanner(System.in);
  2. int[]newArray = new int[20];
  3. int newArraySize = 0;
  4. while (newArraySize &lt; newArray.length){
  5. try {
  6. newArray[newArraySize] = scnr.nextInt();
  7. newArraySize++;
  8. }catch(Exception e){
  9. scnr.nextLine();
  10. }
  11. }
  12. for (int i = 0; i &lt; newArraySize; i++){
  13. System.out.println(&quot;The &quot; + i + &quot; input is &quot; + newArray[i]);
  14. }

答案4

得分: 0

使用Java Stream API的解决方案:

  1. Scanner sc = new Scanner(System.in);
  2. System.out.println("输入20个数字:");
  3. int[] arr = IntStream.generate(sc::nextInt) // 创建一个无限流,生成由扫描实例的`nextInt`方法提供的值
  4. .limit(20) // 从流中取出20个值
  5. .toArray(); // 将它们放入数组
  6. System.out.println(Arrays.toString(arr)); // 一次性打印数组内容

此外,还有一个工具方法Arrays.setAll,允许通过IntUnaryOperator设置数组的值:

  1. int[] arr = new int[20];
  2. Arrays.setAll(arr, (x) -> sc.nextInt());
英文:

A solution using Java Stream API:

  1. Scanner sc = new Scanner(System.in);
  2. System.out.println(&quot;Input 20 numbers: &quot;);
  3. int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance
  4. .limit(20) // take only 20 values from stream
  5. .toArray(); // put them into array
  6. 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:

  1. int[] arr = new int[20];
  2. Arrays.setAll(arr, (x) -&gt; sc.nextInt());

答案5

得分: 0

  1. While循环应该有数组长度的条件可以尝试以下代码代码会在第21次输入后停止接受输入并显示数组元素
  2. import java.util.Scanner;
  3. public class AarrayScanner {
  4. public static void main(String args[]) {
  5. Scanner scnr = new Scanner(System.in);
  6. int[] newArray = new int[20];
  7. int newArraySize = 0;
  8. while (scnr.hasNextInt() && newArraySize < newArray.length) {
  9. newArray[newArraySize] = scnr.nextInt();
  10. newArraySize++;
  11. }
  12. for (int i = 0; i < newArraySize; i++) {
  13. System.out.println("第 " + i + " 个输入是 " + newArray[i]);
  14. }
  15. }
  16. }
英文:

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.

  1. import java.util.Scanner;
  2. public class AarrayScanner {
  3. public static void main(String args[]) {
  4. Scanner scnr = new Scanner(System.in);
  5. int[] newArray = new int[20];
  6. int newArraySize = 0;
  7. while (scnr.hasNextInt() &amp;&amp; newArraySize &lt; newArray.length) {
  8. newArray[newArraySize] = scnr.nextInt();
  9. newArraySize++;
  10. }
  11. for (int i = 0; i &lt; newArraySize; i++) {
  12. System.out.println(&quot;The &quot; + i + &quot; input is &quot; + newArray[i]);
  13. }
  14. }
  15. }

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:

确定