2016-01-29 115 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; 
    } 
}