2017-09-28 57 views
2
String lottoNumbers = ""; 
     Scanner scan = new Scanner(System.in); 
     System.out.println("To buy a ticket we need your numbers..."); 


     for (int i = 1; i <= 6; i++) 
     { 
      System.out.println("Please enter number " + i); 
      int userNum = scan.nextInt(); 

      if (userNum >= 1 && userNum <= 49) 
      { 
       lottoNumbers = lottoNumbers + userNum; 
       if (i < 6) lottoNumbers = lottoNumbers + ", "; 
      } 

      else 
       do { 
        System.out.println("Numbers must be between 1 and 49. \nPlease try again."); 
        userNum = scan.nextInt(); 
        } 
       while (userNum <1 || userNum >49); 
     } 

     System.out.println("You selected numbers " + lottoNumbers); 
     System.out.println("Ticket has been printed, please pay £2."); 

所以這個的目的是我們正在練習,做,做while循環。我們要創建這個while while循環,用戶輸入1到49之間的6個數字。如果他們進入這個範圍以外,他們需要重新輸入,直到他們的輸入介於1和49之間。從一個循環連接結果

我遇到的問題是如果他們輸入全部6在1 - 49第一次,輸出結合正確,即「你的號碼是1,2,3,4,5,6」

但是,如果他們搞砸了第四個條目,輸出將錯過這個。 I.e「你的號碼是1,2,3,5,6」

不太確定我在哪裏出錯。請注意,我們並沒有長時間啓動Java,因此我在此階段可以使用的解決方案類型受到限制。

的僞代碼,我只好跟着是:

1.1. Declare a String variable to hold the output 
1.2. Declare scanner variable 
1.3. Print 「To buy a ticket we need your numbers…」 
1.4. Loop 6 times 
1.4.1. Print 「Please enter lotto number x」 
1.4.2. Declare variable to hold users num 
1.4.3. Store users num 
1.4.4. If number is between 1 and 49 then 
1.4.4.1.1. concatenate the users number plus a comma to the output 
1.4.5. Else 
1.4.5.1.1. Do Loop 
1.4.5.1.1.1. Print 「numbers must be between 1 and 49 please try again」 
1.4.5.1.1.2. Store users num 
1.4.5.1.2. Loop While users num < 0 or users num> 49 
1.4.6. End If 
1.5. End Loop 
1.6. Print 「You selected numbers 「 + output 
1.7. Print 「Ticket has been printed – please pay £2」 
+0

是不是因爲你的for循環只運行了6次? – procrastinator

回答

0

當用戶在主循環中輸入數字超出範圍時,追趕do { } while ()循環不處理輸入。它確實檢查有效性,但它不會在任何地方使用它。

你需要做的是,一旦用戶在追趕循環中糾正自己,追加值到字符串。

if (userNum >= 1 && userNum <= 49) { 
    lottoNumbers = lottoNumbers + userNum; 
    if (i < 6) lottoNumbers = lottoNumbers + ", "; 
} else { 
    do { 
     System.out.println("Numbers must be between 1 and 49. \nPlease try again."); 
     userNum = scan.nextInt(); 
    } while (userNum < 1 || userNum > 49); 
    // Process valid input here 
    lottoNumbers = lottoNumbers + userNum; 
    if (i < 6) lottoNumbers = lottoNumbers + ", "; 
} // Note the extra brackets around else block 
+0

完美謝謝。我忘記了所有關於糾正輸入的問題。 – Stephen

+0

請務必將問題標記爲已回答! –

1

那麼在你的其他部分,你要求用戶輸入一個新的號碼,保存這一點,但你不加/它串連到你的String lottoNumbers。

此外,我會小心你從else循環添加這個,所以你不會錯誤地添加一個額外的數字。

+0

謝謝!你們一如既往的好棒 – Stephen