2017-02-25 39 views
1

所以這段代碼要求輸入一個名字和一個數字1-20,但是如果你輸入的數字超過20或者小於1,程序仍然會運行,我知道我需要一個條件語句來確定「ano」停止並重新提出聲明並重新運行細分受衆羣,但我不知道如何將其實施到代碼中。如何在此程序中設置條件語句?

// library - for interactive input 
 
import java.util.Scanner; 
 

 
//--------------------------------- 
 
// program name header 
 
public class feb24a 
 
{ 
 
    //--------FUNCTION CODING --------------- 
 
    // FUNCTION HEADER 
 
    public static void seeit(String msg, String aname, int ano) 
 
    { 
 
    // statement to accomplish the task of this function 
 
    System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano); 
 
    // return statement without a variable name because it is a void 
 
    return; 
 
    } 
 

 
    //------------------- MAIN MODULE CODING TO CALL FUNCTIONS ---------------- 
 
    // Main module header 
 
    public static void main (String[] args) 
 
    {   
 
    String msg, aname; 
 
    int ano, again, a, b; 
 

 
    msg = "Hello"; 
 
    a = 1; 
 
    b = 20; 
 

 
    //Loop control variable 
 
    again = 2;  \t  \t 
 
    while(again == 2) 
 
    { 
 
     System.out.print("\n enter NAME: ");  \t 
 
     Scanner username = new Scanner(System.in); 
 
\t 
 
     aname = username.nextLine(); 
 
\t 
 
     System.out.print("\n enter number 1-20: ");  \t 
 
     Scanner userno = new Scanner(System.in); 
 
\t 
 
     ano = userno.nextInt(); 
 
     seeit(msg, aname, ano); 
 
\t 
 
     //ask user if they want to do it again, 2 for yes any other for no 
 
     System.out.print("\n do you want to do this again? 2 for yes "); 
 
\t 
 
     Scanner useragain = new Scanner(System.in);  \t 
 
     again = useragain.nextInt(); 
 
    } //terminate the while loop 
 
    }  \t 
 
}

+0

整數a和b是從當我試圖插入一個 「如果那麼」 語句 –

+0

您只需使用例如:IF(I> 0 && I < = 20) –

+0

看起來你使用了一個標有「Javascript/HTML/CSS snippet」的圖標來輸入你的問題。 Javascript不是Java。請不要這樣做。 – ajb

回答

0

替換這個while循環:

Scanner scanner = new Scanner(System.in); 
    while (again == 2) { 
     ano = 0; 

     System.out.print("\n enter NAME: "); 
     aname = scanner.nextLine(); 

     while (ano < 1 || ano > 20) { 
      System.out.print("\n enter number 1-20: "); 
      ano = scanner.nextInt(); 
     } 

     seeit(msg, aname, ano); 

     System.out.print("\n do you want to do this again? 2 for yes "); 
     again = scanner.nextInt(); 
    } 
+0

謝謝,現在我只需要解構它,看看它如何工作以備將來使用! –

0

嘗試圍繞你的肛= userno.nextInt()在while循環。 (即,while(ano < 1 || ano> 20)),並在while循環中放置提示。這樣,它會繼續閱讀一個新的號碼,直到它終於不再滿足while循環,並且會爆發。

+0

我不完全知道你的意思...... –

+0

我試着圍繞「ano = username.nextLine();」在你建議的while循環中,但不會定義ano嗎? –

+0

我修正了我的答案,用||替換&&。不,ano仍然會被定義。你可以刪除while循環,只需添加一個inner while循環,就像Pavlo上面演示的那樣。 –