2016-01-29 118 views
0

似乎有一些与我的代码。我的代码检测到非整数,并不断要求用户输入一个正数#,但是当您插入一个负数#时,它只是要求用户输入一次正数。哪里不对?一定要用我的do-while循环。 我只关注第一个N,然后我可以做第二个N。第一个do-while循环无法正常工作

import java.util.Scanner; 

public class scratch { 

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    int firstN = 0; 
    int secondN = 0; 
    boolean isNumber = false; 
    boolean isNumPos = false; 

    System.out.print("Enter a positive integer: "); 

    do { 
     if (input.hasNextInt()) { 
      firstN = input.nextInt(); 
      isNumber = true; 
     } 
     if (firstN > 0) { 
      isNumPos = true; 
      isNumber = true; 
      break; 
     } else { 
      isNumPos = false; 
      isNumber = false; 
      System.out.print("Please enter a positive integer: "); 
      input.next(); 
      continue; 

     } 

    } while (!(isNumber) || !(isNumPos)); 

    System.out.print("Enter another positive integer: "); 
    do { 
     if (input.hasNextInt()) { 
      secondN = input.nextInt(); 
      isNumber = true; 
     } 
     if (secondN > 0) { 
      isNumPos = true; 
      isNumber = true; 
     } else { 
      isNumPos = false; 
      isNumber = false; 
      System.out.print("Please enter a positive integer: "); 
      input.next(); 
     } 

    } while (!(isNumber) || !(isNumPos)); 

    System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN)); 

} 

public static int gCd(int firstN, int secondN) { 
    if (secondN == 0) { 
     return firstN; 
    } else 
     return gCd(secondN, firstN % secondN); 
} 

} 
+0

它失灵的负整数,小数负,或两者兼而有之?对负数为 –

+0

。 – EdtheBig

回答

1

你在这种情况下读出的输入两次:

 firstN = input.nextInt(); 
     ... 
     input.next(); 

添加一些指示变量或重新组织代码,以便当通过第一读取读取,避免第二个。

0

尝试这段代码

while (true){ 
    System.out.println("Please enter Positive number"); 
    boolean hasNextInt = scanner.hasNextInt(); 
    if(hasNextInt){ 
    int firstNum = scanner.nextInt(); 
    if(firstNum>0){ 
     break; 
    }else{ 
     continue; 
    } 
    }else{ 
    scanner.next(); 
    continue; 
    } 
}