使用HasNextInt方法从用户获取正整数

时间:2013-11-27 03:42:53

标签: java

我是Java的新手,正在研究一个应该从用户那里获得正整数的简单程序。这是我到目前为止的代码:

import java.util.Scanner;
public class Binary{
  public static void main( String [] args ){
    Scanner console = new Scanner(System.in);
    int number = getInt(console, "Enter a positive integer");
    System.out.println(number);
  }

  public static int getInt(Scanner console, String prompt){
    System.out.println(prompt);
    while(!console.hasNextInt() || console.nextInt() < 0){
      console.next();
      System.out.println("Not an integer; try again");
      System.out.println(prompt);
    }

    return console.nextInt();


  }  

}

目前,当输入任何整数时,它会生成两个输入字段,我想知道如何重构while循环,以便它只在提示后显示一个字段。提前谢谢!

2 个答案:

答案 0 :(得分:0)

while(!console.hasNextInt() || console.nextInt() < 0){
  console.next();
  System.out.println("Not an integer; try again");
  System.out.println(prompt);
}

您将在条件中要求新变量。

像这样构建它:

int input = console.nextInt();

while(!console.hasNextInt() || input < 0){
      System.out.println("Not an integer; try again");
      System.out.println(prompt);
      input = console.nextInt();
}

或者更合适:

do {
      input = console.nextInt();
      System.out.println("Not an integer; try again");
      System.out.println(prompt);
} while (!console.hasNextInt() || input < 0);

答案 1 :(得分:0)

你的逻辑错了,试试,

public static int getInt(Scanner console, String prompt){
   System.out.println(prompt);
   int num;

  while(console.hasNextInt()){
    num= console.nextInt();

    if(num >= 0){// If num is positive than break loop and return num
     break;
    }

   System.out.println("Not an integer; try again");
   System.out.println(prompt);
   }
    return num;
  }