2016-02-07 156 views
-1

場景如下,如何在Java中設置參數?

裝飾者需要輸入房間的高度(2米到6米之間),然後輸入所有四面牆的長度(最小1米;最大25米)。

System.out.println("Enter Height of the room"); 
    Scanner hr = new Scanner(System.in); 
    int height = hr.nextInt(); 

System.out.println("Enter Length1 of the room"); 
    Scanner l1 = new Scanner(System.in); 
     int length = l1.nextInt(); 

System.out.println("Enter Length2 of the room"); 
      Scanner l2 = new Scanner(System.in); 
      int length2 = l2.nextInt(); 

System.out.println("Enter Length3 of the room"); 
      Scanner l3 = new Scanner(System.in); 
      int length3 = l3.nextInt(); 

System.out.println("Enter Length4 of the room"); 
      Scanner l4 = new Scanner(System.in); 
       int length4 = l4.nextInt(); 

我已經寫了掃描儀來接收用戶的輸入,但我不知道如何設置掃描儀的參數。我想讓程序執行的操作是接收用戶的輸入,如果(例如房間高度爲9米)輸入不在打印錯誤的參數內。

+1

是否真的需要創建這些很多'Scanner's的。 – Satya

+0

你不應該多次包裝一個流。這導致不可預知的結果。 –

+0

使用'if'條件來檢查用戶輸入。 –

回答

1

如果我理解它是正確的,你必須創建你所謂的參數。 Scanner不會做你想做的。

所以,再次,如果我理解它是正確的,你應該創建條件來檢查用戶是否給你正確的輸入。

而且你也只需要ONEScanner實例。所以:

Scanner scannerToUsAll = new Scanner(System.in); 

System.out.println("Enter Height of the room"); 
int height = scannerToUsAll.nextInt(); 

//here you check 
if (height < 2 && height > 6 ){ 
    System.out.println("The Height is not within the parameters (2 and 6)"); 
} 

如果你需要得到另一個輸入只需使用相同的掃描儀int length = scannerToUsAll.nextInt();

你需要控制你的應用程序退出或返回到相同問題的流程。在這裏,我建議:while

0
System.out.println("Enter Height of the room"); 
    Scanner sc = new Scanner(System.in); 
    int height = sc.nextInt(); 
    if (height < 2 || height > 6) 
    { 
     System.out.println("Error: height is invalid"); 
    } 

System.out.println("Enter Length1 of the room"); 
     int length1 = sc.nextInt(); 
     if (length1 < 1 || length1 > 25) 
     { 
      System.out.println("Error: length1 is invalid"); 
     } 

System.out.println("Enter Length2 of the room"); 
      int length2 = sc.nextInt(); 
      if (length2 < 1 || length2 > 25) 
      { 
       System.out.println("Error: length2 is invalid"); 
      } 

...等等...

+0

好的,歡呼聲...我會編輯我的帖子以刪除它。 @PeterLawrey – Carlene

相關問題