每当用户输入负数时,我想在 else 中显示该语句,我知道这个 while 循环将是无限循环,但我不知道如何打破它。我尝试输入“break”,但显示错误:
need a return statement.
我应该只使用 if 语句还是编写正确的代码?
import java.util.Scanner;
class number{
public static void main(String[] args){
workers();
int numEmployee;
}
public static int workers(){
System.out.println("How many employees do you have?");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int numEmployee;
while(true){
if(number >= 0){
numEmployee = number;
return numEmployee;
}else{
System.out.println("Please enter a positive number");
}
}
}
}
最佳答案
建议更改:
import java.util.Scanner;
// Always capitalize your public class name (and the corresponding source file)
public class Number{
public static void main(String[] args){
// Get #/employees
int numEmployee = Number.workers();
System.out.println ("#/employees=" + numEmployee);
}
public static int workers(){
// Loop until we get a valid number
int number;
do {
System.out.println("How many employees do you have?");
Scanner input = new Scanner(System.in);
number = input.nextInt();
} while (number <= 0)
// Return the final value
return number;
}
}
关于java - 调用一个java方法,询问用户公司的员 worker 数(无参数,返回值> = 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31376744/