[英]Trying to write a very simple program involving a password (java)
因此,我尝试在程序中进行密码检查,目的是,如果用户键入正确的密码,则程序将回答:“您通过”,如果不是,则为“您错了”。 问题是Eclipse告诉我“鱼(这是密码)无法解析为变量”
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傻瓜编程,但仍然没有运气,希望您能为我提供帮助,我将不胜感激!
谢谢!
您为它写了一些错误的语法。尝试这段代码。我添加了必要的注释,以使您了解以下代码。
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"
}
if (isValid(password))
{
System.out.println("You pass!");
}
else
{
System.out.println("You're wrong!");
}
首先,您永远不会读取变量中的输入!然后,您将尝试检查Scanner类型的“ scan”对象之间的相等性。相反,请读取输入“ scan.nextLine();”。 在变量中说“ var”,然后调用var.equals(password)。还请检查字符串“ Fish”最初是否为null,这将为您提供NullPointerException!
欢迎来到Java世界!
在您的程序中,您通过在Scanner对象上调用equals犯了一个小错误。 还记得完成后关闭可关闭扫描器资源。
请参考下面的代码。
import java.util.Scanner;
公共类密码{
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!");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.