所以我尝试在我的程序中进行密码检查,目标是,如果用户输入正确的密码,程序将回复:"你通过",如果不是"你& #39;错了"。问题是Eclipse告诉我" Fish(这是密码)无法解析为变量"
import java.util.Scanner;
public class Password {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = Fish;
System.out.println("What is the password? ");
scan.nextLine();
if (scan.equals(password)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
我尝试以Eclipse的方式解决问题,但是在我运行程序后输入错误的密码时,我得到了错误的密码:
import java.util.Scanner;
public class Password {
private static final String Fish = null;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = Fish;
System.out.println("What is the password? ");
scan.nextLine();
if (scan.equals(password)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
我尝试在线查看,我实际上正在阅读Java Programming for Dummies,但仍然没有运气,希望你可以帮助我,我很感激!
谢谢!
答案 0 :(得分:0)
你已经为它编写了一些错误的语法。试试这段代码。我添加了必要的注释,让你理解我在下面的代码中做了什么。
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = "Fish"; // assigning value to String password
System.out.println("enter value");
String temp=scan.nextLine(); //scanner takes nextline entered and assign it to temp
// if (scan.equals(password)) is wrong ,you want to compare value taken by scanner , what you have wriiten is incorrect. scan is object of Scanner.Not value taken by it
if(temp.equals(password)) //if entered value eqauls your assigned password value
{
System.out.println("You pass!"); // else print you pass
}
else
{
System.out.println("You're wrong!"); //else print "you are wrong"
}
答案 1 :(得分:0)
if (isValid(password))
{
System.out.println("You pass!");
}
else
{
System.out.println("You're wrong!");
}
答案 2 :(得分:0)
首先,你永远不会在变量中读取你的输入!然后你试图检查"扫描"之间的平等。 Scanner.Instead读取输入" scan.nextLine();"在一个变量中说" var"然后调用var.equals(密码)。还要检查你的String" Fish"最初是null,它会给你一个NullPointerException!
答案 3 :(得分:-1)
欢迎来到Java World!
在你的程序中,你通过在Scanner对象上调用equals来犯一个小错误。 还记得在完成后关闭可用的扫描程序资源。
请参阅以下代码。
import java.util.Scanner;
public class Password {
private static final String Fish = "Fish";
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("What is the password? ");
if (scan.nextLine().equals(Fish)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}