使用循环数组获取输入并在输入“-1”后停止/打印最后 10 个元素的问题

Problems using circular array to take inputs and stop/print the last 10 elements once "-1" is entered

提问人:Limbo 提问时间:2/8/2022 更新时间:2/8/2022 访问量:311

问:

我有一个 Java 程序,它应该按照上面的标题描述进行操作。不幸的是,我现在遇到的问题是,无论我在扫描仪中输入什么,除了零和错误消息之外什么都没有。

代码:

 public static void main(String[] args) {

  //Set variable
  int count = 0;
  int numInput = 0;
  int arrSize = 10;

  //Set and initialize string
  int[] numArray = new int[arrSize];

  //Set and initialize Scanner
  Scanner sc = new Scanner(System.in);
  System.out.println("Please input some numbers. Stop by typing -1:");

  while (numInput != -1) {
     numInput = sc.nextInt();
     //Check if input is integer or not
     if (numInput == (int)numInput) {
        if (count == -1) {
           count = numArray.length - 1;
        } else if (count == numArray.length) {
           //Append input to array
           numArray[count] = numInput;
           count++;
        }//End of conditional
     } else {
        //Error message
        System.out.println("Enter a valid integer:");
     }//End of conditional
  }//End of while loop

  //Print array with for loop
  for (int i = 0; i <= 10; i++) {
     System.out.print(numArray[i] + " ");
  }//End of for loop

  System.out.println("\n");

  sc.close();

}// End of main

输出:

0 0 0 0 0 0 0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at last10.main(last10.java:42)
Java 数组 循环 if-statement java.util.scanner

评论

0赞 Namandeep_Kaur 2/8/2022
打印数组的循环从 0 开始,一直到 10,总共有 11 个元素,而大小为 10。fornumArray
0赞 Rogue 2/8/2022
你不想迭代,直到 ,而是 .也总是真的,是一个,不能是其他任何东西。使用 ,除非整数可用,否则不会收到值。你的循环中也有一些逻辑错误,@alonealgorithm下面的答案可以解决。i <= 10i < numArray.lengthnumInput == (int) numInputnumInputintScanner#nextIntwhile

答:

1赞 alonealgorithm 2/8/2022 #1

就像Namandeep_Kaur评论所说的那样,您的 for 循环条件不正确。您希望它是,而不是因为您的 numArray 长度设置为 10,但是数组索引在 Java 中是从零开始的。因此,您将访问从索引 0 开始的元素。numArray 将包含索引 0-9 处的元素。从本质上讲,当循环等于 10 时,您的循环将希望停止,因为那时条件为 false,并且您不会尝试访问不存在的元素。我还重构了您的程序。i < 10i <= 10i10 < 10numArray[10]

import java.util.Scanner;
import java.util.InputMismatchException;

public class LimboProgram {

public static void main(String[] args) {

 //Set variable
 int count = 0;
 int numInput = 0;
 int arrSize = 10;

 //Set and initialize string
 int[] numArray = new int[arrSize];

 //Set and initialize Scanner
 Scanner sc = new Scanner(System.in);
 System.out.println("Please input some numbers. Stop by typing -1:");

 while (numInput != -1) {
  
  try
  {
     // you do not need to check if numInput is a number because 
     // sc.nextInt() will throw an error if the input is not a number.
     numInput = sc.nextInt();
     
     if ( numInput == -1 ) {
        break;
     }
     
     // You can achieve a circular rotation using the modulo (%) operator.
     // So, if count becomes 10, then 10 % 10 results in 0. If count is 11,
     // then 11 % 10 results in 1. This allows you to "circle" the array.
     count = count % numArray.length;
     numArray[count] = numInput;
     count++;
  }
  catch (InputMismatchException e) {
     System.out.println(e);
  }
  
 }


 for (int i = 0; i < 10; i++) {
    System.out.print(numArray[i] + " ");
 }

 System.out.println("\n");

 sc.close();

 }

}

我希望这是您在程序中寻找的结果。如果有什么我可以进一步澄清的,我很乐意。

评论

1赞 Limbo 2/8/2022
您的代码有效。谢谢!
0赞 Darkman 2/8/2022 #2

圆形阵列?下面是一个示例。

public class Main
{
    public static void main(String[] args)
    {
        final byte[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        System.out.println(array[cycle(-1,10)]); // 9
    }

    public static final int cycle(final int index, final int quantity)
    {
        return ((index % quantity) + quantity) % quantity;
    }
}