调用一个java方法,询问用户公司中的员工数量(没有参数,返回值为> = 0)

时间:2015-07-13 06:32:35

标签: java

我想在用户输入负数时在else中显示语句,我知道这个循环将是无限循环,但我不知道如何打破它。我尝试输入“break”,但它显示错误:

  

需要一份退货声明。

我应该只使用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");
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

你想要的第一件事是每个循环都要求输入。此外,对于每种情况,您都应该在方法中获得回报。编译器不知道你的循环是无限的,因此它需要返回:

import java.util.Scanner;

class Number{

  public static void main(String[] args){
    int numEmployee = workers();
    System.out.println("Number of empoyees: " + numEmployee);
  }

  public static int workers(){
    int number = 0;

    System.out.println("How many employees do you have?");

    Scanner input = new Scanner(System.in);

    while(true){
      number = input.nextInt();
      if(number >= 0){
        return number;
      }else{
        System.out.println("Please enter a positive number");
      }
    }
    return 0; //Added this
  }
}

答案 1 :(得分:1)

建议的更改:

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;
  }
}

答案 2 :(得分:0)

你的方法应该是:

public static int workers() {
    System.out.println("How many employees do you have?");

    Scanner input = new Scanner(System.in);
    int number;
    boolean isValid = false;

    int numEmployee = 0;
    while (!isValid) {
        number = input.nextInt();
        if (number >= 0) {
            numEmployee = number;
            isValid = true;
        } else {
            System.out.println("Please enter a positive number");
        }
    }

    return numEmployee;
}