2017-09-24 98 views
-2
import java.util.Scanner; 
public class Application { 

public static void main(String[] args) { 
    do { 
    System.out.println("What is the command keyword to exit a loop in Java?\na. int\nb. continue\nc. break\nd. exit\nEnter your choice"); 
    Scanner ans = new Scanner(System.in); 
    char ans = sc.next().charAt(0); 
    if(ans=='c') 
     System.out.println("Correct"); 
    else 
     System.out.println("Wrong! Presss Y to try again."); 
    Scanner redo = new Scanner(System.in); 
    char redo = sc.next().charAt(0); 
    } 
    while(redo=='y'); 
} 

}什麼在我的代碼是錯誤的(Java字符輸入的初學者)

我剛開始學習Java,可以請你告訴我,什麼是錯在我的代碼,以及如何改進呢?謝謝

這是我收到的錯誤。

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Duplicate local variable ans 
sc cannot be resolved 
Duplicate local variable redo 
sc cannot be resolved 
redo cannot be resolved to a variable 

at Application.main(Application.java:9) 
+0

爲什麼你認爲之前是怎麼回事? –

+0

它不起作用。以下是錯誤...螺紋 異常「主要」 java.lang.Error的:未解決的編譯問題: \t重複的局部變量ANS \t SC不能得到解決 \t重複的局部變量重做 \t SC不能得到解決 \t重做無法解析爲變量 \t at Application.main(Application.java:9) –

+0

請不要在註釋中發佈錯誤。請改編你的問題。 –

回答

1

想你想獲得水木清華這樣的:

public class Application { 

    public static void main(String[] args) { 
     char redo; 
     do { 
      System.out.println("What is the command keyword to exit a loop in Java?\na. int\nb. continue\nc. break\nd. exit\nEnter your choice"); 
      Scanner scanner = new Scanner(System.in); 
      char ans = scanner.next().charAt(0); 
      if (ans == 'c') { 
       System.out.println("Correct"); 
       break; 
      } 
      else { 
       System.out.println("Wrong! Presss Y to try again."); 
       redo = scanner.next().charAt(0); 
      } 
     } 
     while (redo == 'y'); 
    } 

} 

問題的實現:

錯誤的變量定義

嘗試重新定義ans變量導致編譯錯誤。使用不同的變量名稱。對於前:

Scanner scanner = new Scanner(System.in); 
char ans = scanner.next().charAt(0); 

,而不是這個

Scanner ans = new Scanner(System.in); 
char ans = sc.next().charAt(0); 

也許你想打破循環,如果答案是正確的

所以最好添加休息的時候ans=='c'

if (ans == 'c') { 
    System.out.println("Correct"); 
    break; 
} 

雖然條件變量定義

定義redo可變do-while循環塊,否則你會得到編譯錯誤

+0

它導致這個錯誤.. \t本地變量重做可能沒有初始化 –

+0

我已經初始化爲零。非常感謝你的幫助 !你知道爲什麼它應該先設置爲零嗎? –

+0

如果您檢查我的提議中沒有break語句的'redo'值,它應該使用某個值(smth而不是'y')進行初始化,否則會打破邏輯。但是,如果在'ans =='c''時使用break語句,比在'redo'檢查之前得到循環(所以在這種情況下redo ='0'的定義不是必需的) –

0

在以下2語句中複製局部變量「ans」。重命名任何人到另一個。

Scanner ans = new Scanner(System.in); 
    char ans = sc.next().charAt(0); 
+0

這個問題中編輯它,並且仍然存在錯誤 –

+0

@AhmedRefaat將掃描儀更改爲Scanner sc。花時間學習如何使用eclipse。這裏是一個教程https://www.youtube.com/watch?v = xO5DpU2j-WE – caot

+0

@Ahmed在鏈接中提供相關問題和示例https://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class -in-java – caot

相關問題