2013-10-24 54 views
-3
public static void main(String[] args) { 
    // TODO code application logic here 
    Scanner input = new Scanner(System.in); 
    do{ 
     System.out.print("Enter choice:"); 
     int choice; 
     choice = input.nextInt(); 
     switch (choice) 
     { 
      case 1: 
       FirstProject.areaRectangle(); 
       break; 
      case 2: 
       FirstProject.areaTriangle(); 
       break; 
      default: 
       System.out.println("lol"); 
       break; 
     } 
    }while (input.nextInt()!=0);  
} 




public static void areaRectangle() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Area of a rectangle."); 

    System.out.print("Enter the width: "); 
    double width; 
    width = input.nextInt(); 

    System.out.print("Enter the height: "); 
    double height; 
    height = input.nextInt(); 

    double areaRectangle = (width * height); 

    System.out.println("The Area of the rectangle is: " + areaRectangle); 


    } 
public static void areaTriangle() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Area of a triangle."); 

    System.out.print("Enter the base: "); 
    double base; 
    base = input.nextInt(); 

    System.out.print("Enter the height: "); 
    double height; 
    height = input.nextInt(); 

    double areaTriangle = (base * height)/2; 

    System.out.println("The Area of the triangle is: " + areaTriangle); 
} 
} 

這是我的代碼,它的工作原理,唯一困擾我的是我必須輸入除「0」之外的任何值才能保持循環。例如,如果我選擇案例1,它將執行該方法,但在完成之後,我必須輸入任何值以繼續循環。有任何想法嗎?Java:這段代碼有什麼問題?

+11

什麼 ...什麼是應該做的代碼?請在你的問題中多說一點。通過儘可能完整地填寫問題來幫助我們。 –

+0

這意味着混淆我們! – redFIVE

+2

@redFIVE在這種情況下沒有什麼問題 –

回答

7

這就是問題所在:

while (input.nextInt()!=0); 

,詢問了另一個號碼,但不記得它 - 它只是檢查它是否是0

我懷疑你想要的東西,像:

while (true) { 
    System.out.print("Enter choice:"); 
    int choice = input.nextInt(); 
    if (choice == 0) { 
    break; 
    } 
    switch (choice) { 
    // Code as before 
    } 
} 

有哪些需要編寫這些代碼的方法稍微難看的「無限直到手動斷開」循環,但在其他方面有點奇怪。例如:

int choice; 
do { 
    System.out.print("Enter choice:"); 
    choice = input.nextInt(); 
    switch (choice) { 
    // Code as before... except work out whether you want to print anything on 0 
    } 
} while (choice != 0); 

無論哪種方式,你應該考慮你想要什麼輸入0時發生 - 立即破發,或打印「笑」再破?你總是可以有:

case 0: 
    break; 

,如果你想switch語句不打印爲0

+0

謝謝你的答案先生,我我已經試過了,但是它總是會在第一種情況下停止循環,我總是必須輸入一個不包含0的值,以使「輸入選擇」再次出現。 – Lance

+0

什麼?我不明白你的意思。我提供的代碼絕對不是這種情況。我試過了。 –