所以,今天刚开始使用 Java
,在看了一个关于这个人如何使用它来查找一个区域的教程之后,我开始研究 Scanner
对象三角形。也许我做错了什么,但是,我决定搞砸一下,看看是否可以将“if”语句合并到其中。
import java.util.Scanner;
public class test {
static Scanner sc = new Scanner(System.in);
/*
* in = input from a keyboard or other device.
* System is a class.
*/
public static void main(String[] args){
{
String password;
//this is our variable - password
System.out.print("Enter your password:");
password = sc.next();
//we have gotten the user to input the words, now to work on displaying a final message
//using if
if (password.equals(one))
System.out.println("You have logged in successfully");
}
}
}
那是我的代码,如果它看起来很糟糕,我深表歉意 - 仍在努力学习。
我的问题是,我希望我的 if 语句仅在他们输入特定密码(“一个”)时通过。但是,我收到一个错误,因为它说值“一”无法解析为变量。当我输入数字时,它工作正常。
我做错了什么,我该如何解决?
最佳答案
首先,类总是大写的,所以 public class test
应该是 public class Test
。
您需要明确地与字符串进行比较。由于 one
未在任何地方定义,因此您的代码将无法运行。
替换:
if (password.equals(one))
与
if (password.equals("one"))
一切顺利。
相反,您也可以在类的 header 中声明密码:
String pw = "one";
然后检查
if (password.equals(pw))
但请记住,在任何编程语言中,以这种方式处理密码永远都不安全。密码应该被散列并存储在数据库中。但是,由于您仍在学习,我可能会考虑将第二种方法(声明要比较的字符串)作为“更干净”的方法。
编辑 - 您的代码如何使用简单的变量声明
import java.util.Scanner;
public class Test {
String pw = "one";
String pw2;
/* this is the constructor for your class
you can override existing variables or
set a variable that is declared in the header of your class
inside the constructor of your class. It will run whenever you
create a new object for that class */
public Test(String pw2Param) {
this.pw2 = pw2Param;
}
public static void main(String[] args){
{
Scanner sc = new Scanner(System.in);
// instantiate an object that will hold the information you need
Test obj = new Test("two");
System.out.println(obj.pw);
// "one"
System.out.println(obj.pw2);
// "two"
System.out.println("Enter your password:");
String password = sc.next();
if (password.equals(obj.pw)) {
System.out.println("You have typed 'one' and logged in successfully");
} else if(password.equals(obj.pw2)) {
System.out.println("You have typed 'two' and logged in successfully");
} else {
System.out.println("I didn't get that");
}
}
}
}
我希望这是有道理的:)
我也是初学者,但我发现在我的控制台中使用 javac
编译我的 java 代码是个好习惯。与我使用过的任何 ide 相比,它是无情的,并且会指出一些 ide 可能会为您原谅/纠正的一般错误。
关于java - Java 新手,想知道 Scanner 读取的 if 语句和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31591235/