我正在尝试创建一个循环,继续循环,直到用户输入不存在的用户名。例如,maryj存在于数据库中。跟踪代码,我首先输入maryj,我将进入while循环并询问用户Please enter a another username.Enter your username:
。我再次输入maryj,但循环不要求我输入另一个用户名。它将自己移动到下一位代码。似乎while循环仅在第一次试用后才起作用,但如果我多次输入相同的用户名则不行。代码如下。
public void register() throws SQLException
{
Scanner stdin;
String sql_statement;
Statement select = connection.createStatement();
stdin = new Scanner(System.in);
System.out.print("Enter your user name: ");
user_name = stdin.next();
sqlz_statement = "SELECT " + "user_name " + "FROM" + " users" + " where user_name = "
+ "'" + user_name + "'";
result = select.executeQuery(sql_statement);
while(result.next())
{
System.out.println("Please select another username.");
System.out.print("Enter your user name: ");
user_name = stdin.next();
}
System.out.println("Enter your last name: ");
System.out.println("Enter your first name: ");
} // method register
答案 0 :(得分:1)
你错了,因为你只看了一次数据库,你应该这样做:
Boolean exist=true;
while (exist) {
System.out.print("Enter your user name: ");
user_name = stdin.next();
sqlz_statement = "SELECT " + "user_name " + "FROM" + " users" + " where user_name = "
+ "'" + user_name + "'";
result = select.executeQuery(sql_statement);
if (!result.next()) {exist=false}
else {System.out.println("Please select another username.");}
}
System.out.println("Enter your last name: ");
System.out.println("Enter your first name: ");