简体   繁体   中英

How do you use a while loop with user input?

import java.util.Scanner;

public class Max {
   
   public int findMax() {
      /* Type your code here. */
      Scanner scan = new Scanner(System.in);
      int userInput = scan.nextInt();
      int largestInt = 0;
      
      while (userInput > 0) {
         if (userInput > largestInt) {
            largestInt = userInput;
         }
      }
      return largestInt;
   }
   
   public static void main(String[] args) {
      Max test = new Max();
      System.out.println(test.findMax());
   }
}

This is being tested on Zybooks, and everything I have tried has resulted in the program timing out. I can't figure out why, I think my while loop is very logical? what am I missing?

1:Compare output
0 / 1
Program timed out
Output differs. See highlights below.
Input
2 77 17 4 -1
Your output

Expected output
77

If userInput is greater than largestInt, assign userInt value to largestValue until userInt is negative, and return largestInt.

Your loop condition is based on userInput , which doesn't change inside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM