所以我认为我的while循环甚至没有发生,我不太清楚为什么。这可能是一个明显的东西,但我似乎无法找到解决方案。此代码尝试执行的操作是使用变量“firstLetter”并添加到String“passcode”并继续添加while循环中指定的不同字符。但是它说我的变量可能还没有初始化,这让我觉得整个循环搞砸了并且没有被看到。我很擅长编码所以任何帮助将不胜感激
import java.util.Scanner;
public class Password
{
public static void main (String [] args)
{
System.out.println("This program will take a phrase by you and"
+ "\ncreate a strong and safe password that "
+ "\nwill be similar. Please enter a phrase.");
Scanner keyboard = new Scanner (System.in);
String message = keyboard.nextLine();
String firstLetter;
int index = 0,
number = 0, //a counting mechanism
spot = 2, // how many characters in each word you put down
pass = 1; //counting up the number of char in the password
if (message.charAt(0) == ' '){
System.out.println("Make sure the first character in your "
+ "phrase is not a space");
System.exit(1);
}//if
System.out.print("\nYour Password is: ");
char white = message.charAt(index);
firstLetter = Character.toString(white);
System.out.println(firstLetter);
index = 1;
String passcode;
while(index < message.length()) {
white = message.charAt(index);
if ((white != ' ') && (number != spot)) {
pass = pass + 1;
index = index + 1;
number = number + 1;
passcode = firstLetter + white;
}//if
else if (white != ' ') {
index = index + 1;
}//else if
else { spot = spot + 1;
number = 0;
index = index + 1;
}//else
}//while
System.out.print(passcode);
}
}
答案 0 :(得分:0)
您已声明了一个变量密码,如:
String passcode;
进入while循环时初始化它的唯一方法(意味着条件满足时),如果if ((white != ' ') && (number != spot)) {
如果它不满足条件怎么办?这意味着您没有传递代码的任何值,然后您尝试访问它,如:
System.out.print(passcode);
因此编译器抱怨相同。所以你需要对String声明做一些补充:
String passcode = "";//define it as well with default value and you might need to check defining values within if/else where its not already present
答案 1 :(得分:0)
只是简单地看一下代码,我觉得这不会编译并抱怨passcode变量没有被初始化。如果条件
怎么办?指数&lt; message.length()第一次不是真的,而且永远不会输入while循环!!
我想这可以解释为什么编译器会出错。
您可以将密码初始化为任何值,null或空字符串可能取决于您不确定的用例。
希望这有帮助。