フェデリコSteidlマルティネス:
だから、私は2日間のJavaを学習し、下にこのコードをコンパイル中にエラーメッセージに入って来てきました。私は何をしようとしたことは、システムの入力から名前を取得し、それはあなたがで行きたい名前であるかどうかを知りたい単純なプログラムです。完全に働きました。だから私はそれを変更したい:それは希望の名前ではない場合、あなたは多くの場合、あなたが好きな名前を再入力することができるはずです。私はブール値を持っている理由ですwhileループと一緒に、そこに「確認」。コンパイルされたとき、私ははっきりと宣言し、それを使用していたとしても、ブール「確認」のために、エラーメッセージ「ローカル変数の値が使用されていない確認」を取得します。私は単に周りの最初の宣言を移動しようとしたのだが、何も変更しませんでした。それは何の問題もないように、または再実行する私のループという問題を解決するためにはどのように誰もが知っていますか?
ちなみに、私は、Javaの拡張パックとVSのコードを使用しています。
import java.util.*;
public class Name{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
try{
boolean confirmed = false;
while(confirmed = false){
System.out.println("What's your name again?");
String enteredName = sc.nextLine();
System.out.println("So, your name is " + enteredName + "?\nEnter 'yes' to confirm or 'no' to type a new name.");
String confirmation = sc.nextLine();
if(confirmation.equalsIgnoreCase("yes") || confirmation.equalsIgnoreCase("yes.")){
System.out.println("Confirmed, " + enteredName + ".\n\nNow launching.");
confirmed = true;
}
else if(confirmation.equalsIgnoreCase("no") || confirmation.equalsIgnoreCase("no.")){
System.out.println("Please enter a new name.");
confirmed = false;
}
}
}
finally{
sc.close();
}
}
}
アービンド・クマールのAvinash:
あなたは近いいけないScanner
ためSystem.in
、それはまた閉じてSystem.in
。次のようにこれとは別に、あなたはあなたのコードを簡素化することができます。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String confirmation, enteredName;
do {
System.out.print("What's your name again?");
enteredName = sc.nextLine();
System.out
.print("So, your name is " + enteredName + "?\nEnter 'yes' to confirm or 'no' to type a new name.");
confirmation = sc.nextLine();
if (confirmation.equalsIgnoreCase("yes") || confirmation.equalsIgnoreCase("yes.")) {
System.out.println("Confirmed, " + enteredName + ".\n\nNow launching.");
}
} while (confirmation.equalsIgnoreCase("no") || confirmation.equalsIgnoreCase("no."));
}
}
サンプルを実行します。
What's your name again?Arvind
So, your name is Arvind?
Enter 'yes' to confirm or 'no' to type a new name.no
What's your name again?Kumar
So, your name is Kumar?
Enter 'yes' to confirm or 'no' to type a new name.no.
What's your name again?Avinash
So, your name is Avinash?
Enter 'yes' to confirm or 'no' to type a new name.yes
Confirmed, Avinash.
Now launching.