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

标签 java

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

相关文章:

java - int 是 Java 中的对象吗?

java - 并行运行操作,同时保留有序的增量输出

java - 如何在不使用 put() 方法的情况下向 Map 添加条目

java - 获取特定程序的 JVM 属性

java - 在 ListView 中选择一行

java - GraphView不显示点

java - 为什么在 SQL 中使用别名会返回错误?

互联网上的 Java UDP 客户端/服务器不起作用

java - css hover with selenium 2.20+

java - Eclipse - 无法在本地主机上发布 Tomcat8.0 服务器的服务器配置