Do-while 循环和数组

时间:2021-04-05 16:48:24

标签: java loops do-while do-loops

有人可以帮我做这个循环吗?我希望用户可以选择在程序结束时继续 Y/N 以重新运行或终止它。最好是 do-while 循环?

代码(Java):

public static void main(String[] args) {
  
   int size = 10; //size of array
   Scanner scan = new Scanner(System.in); //create scanner
  
   while (true)
   {
       System.out.println("Enter values: ");
       int[] myArray = new int[size]; //declare array 
      
       for(int i = 0; i < size; i++)
       {
           int userInput = scan.nextInt(); //receive user input
           myArray[i] = userInput;
       }
      
      
      
       System.out.print("You entered these values: "); //print all values entered by user
       
       for (int i=0; i<myArray.length; i++)
       {  
           System.out.print(" " + myArray[i]);
       }
      
       System.out.println("");
      
       IndexOfLargestBatista Object = new IndexOfLargestBatista(); //object of IndexOfLargest class
      
       System.out.println("Index of Largest value: " + Object.findIndex(myArray)); //pass array as parameter and get index number in return
      
       
      
   }

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

    public static void main(String[] args) {
        int size = 10; //size of array
        String nextInput;
        Scanner scan = new Scanner(System.in); //create scanner
        do {
            System.out.println("Enter values: ");
            int[] myArray = new int[size]; //declare array

            for (int i = 0; i < size; i++) {
                int userInput = scan.nextInt(); //receive user input
                myArray[i] = userInput;
            }


            System.out.print("You entered these values: "); //print all values entered by user

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

            System.out.println("");

            IndexOfLargestBatista largeIndex = new IndexOfLargestBatista(); //object of IndexOfLargest class

            System.out.println("Index of Largest value: " + largeIndex.findIndex(myArray)); //pass array as parameter and get index number in return

            System.out.println("Do you want to continue?: Y/N ");
            nextInput = scan.nextLine();

        } while (nextInput.equalsIgnoreCase("Y"));
    }
相关问题