gpt4 book ai didi

java - 调用一个java方法,询问用户公司的员 worker 数(无参数,返回值> = 0)

转载 作者:行者123 更新时间:2023-11-30 03:20:49 25 4
gpt4 key购买 nike

每当用户输入负数时,我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com