2014-10-10 20 views
-3

我想嘗試使這種輸出,但我的代碼有一些錯誤。最好是使用下面的if/else語句,還是使用另一個循環?Java時間表

這是我想要的輸出:

Do you wish to continue >> Y 
Please enter the integer >> 2 
table 2 

1 x 2 = 2 

2 x 2 = 4 

... 

12 x 2 = 24 

Do you want to continue >> T 

這裏是我當前的代碼:

import java.util.Scanner; 
    public class tugas6{ 

    public static void main(String[] args){ 

    Scanner input = new Scanner(System.in); 

    int pilihan; 
    int i, j; 

    System.out.println("Do you want to continue >>"); 
    pilihan = input.nextInt(); 

    if (pilihan==y) 

    System.out.println("Please enter the integer >>"); 
    Scanner in = new Scanner(System.in); 
    j = in.nextInt(); 

    System.out.println("table" +j); 

    for (i = 1 ; i <= 12 ; i++) 
    System.out.println(+i+"*"+j+" = "+(i*j)); 

    else (pilihan==t) 
    System.out.println("Thank you"); 
    } 
    } 
     } 

謝謝。

+2

你的問題是什麼呢?首先'y'不是一個整數。 – proulxs 2014-10-10 17:49:48

+0

'if(pilihan == y)'後面缺少一個括號' – Brian 2014-10-10 17:50:37

回答

1

我看到一些問題,第一個字符文字應該用''個字符包圍。接下來你的if需要一個代碼塊(花括號),因爲它由多個語句組成。你不需要in,因爲你有input。所以,你的代碼應該是這樣的,

if (pilihan=='y') { 
    System.out.println("Please enter the integer >>"); 
    j = input.nextInt(); 
    System.out.println("table" +j); 
    for (i = 1 ; i <= 12 ; i++) 
    System.out.println(String.valueOf(i) + "*"+j+" = "+(i*j)); 
} else if (pilihan=='t') { 
    System.out.println("Thank you"); 
} 
0

讓使簡單

import java.util.Scanner; 
public class table{ 
    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 
     String choice; 
     int i, j; 
     System.out.println("Do you want to continue >>"); 
     choice = input.next(); 
     if(choice.equals("y")){ 
      System.out.println("Please enter the integer >>"); 
      j = input.nextInt(); 
      System.out.println("table" +j); 
      for(i = 1 ; i <= 12 ; i++){ 
       System.out.println(i+"*"+j+" = "+(i*j)); 
      } 
     }else{ 
      System.out.println("Thank you"); 
     } 
    } 
} 

你應該通過數據類型和比較的基礎去使用,如果在INT條件和字符串,你不要必須定義兩個掃描儀。

0

我會在很大程度上贊同krnaveen14,但有一個小小的變化。由於「y」與「Y」不同,並且我假設您希望它們相同,請將.toLowerCase添加到方法的.equlas部分。

公共靜態無效的主要(字串[] args){

Scanner input = new Scanner(System.in); 
    String pilihan = ""; 
    int i, j; 
    System.out.println("Do you want to continue >>"); 
    pilihan = input.next(); 
    if (pilihan.toLowerCase().equals("y")) 
    { 
    System.out.println("Please enter the integer >>"); 
    j = input.nextInt(); 
    System.out.println("table" +j); 
    for (i = 1 ; i <= 12 ; i++) 
     System.out.println(+i+"*"+j+" = "+(i*j)); 
    } 
else 
    System.out.println("Thank you"); 

}