简体   繁体   English

如何在用户输入时使用 while 循环?

[英]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.这正在 Zybooks 上进行测试,我尝试过的一切都导致程序超时。 I can't figure out why, I think my while loop is very logical?我想不通为什么,我觉得我的 while 循环很合乎逻辑? 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.如果 userInput 大于 largestInt,则将 userInt 值赋给 largestValue,直到 userInt 为负数,然后返回 largestInt。

Your loop condition is based on userInput , which doesn't change inside the loop.您的循环条件基于userInput ,它在循环内不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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