问题描述
- Scanner录入出现错误,在线等,很着急!!!帮帮我
-
信息类:import java.util.Scanner; public class UserInf { final private String userName = new String("JiHe"); final private String passWord = new String("JiHe123"); public UserInf() { super(); // TODO Auto-generated constructor stub check(); } public void check() { System.out.println("Please input userName:"); Scanner sc = new Scanner(System.in); if (this.userName.equals(sc.nextLine())) { if (this.passWord.equals(sc.nextLine())) { System.out.println("Please input passWord:"); System.out.println("Check Pass !"); } } } }
测试类:
public class TestUser { public static void main(String[] args) { // TODO Auto-generated method stub UserInf user = new UserInf(); } }
问题:console只输出一句,无法输出第二句:
Please input userName: JiHe
恳请有爱心的你不吝惜赐教!
解决方案
if (this.passWord.equals(sc.nextLine())) {
你输入完名字紧接着输入密码,但是你现在没有输入密码啊
哈哈
少了一个输入密码的提示
System.out.println("Please input passWord:");
if (this.passWord.equals(sc.nextLine())) {
解决方案二:
楼上正解。。。。。。
解决方案三:
public void check() {
System.out.println("Please input userName:");
Scanner sc = new Scanner(System.in);
if (this.userName.equals(sc.nextLine())) {
System.out.println("Please input passWord:");
if (this.passWord.equals(sc.nextLine())) {
System.out.println("Check Pass !");
}
}
}
你注意提示sc.nextLine()的意思是要扫描当前行,并返回输入信息。你的写法是需要连续两次输入完成后,才会执行下面的checkpass!. 调整为上面的顺序
会每次都提示。要点是,在每次sc.nextLine()之前都要提示输入信息。
解决方案四:
public class DomDemoXMLUtil {
final private String userName = new String("JiHe");
final private String passWord = new String("JiHe123");
public DomDemoXMLUtil() {
check();
}
public void check() {
Scanner sc = new Scanner(System.in);
boolean flag = true;
do {
System.out.println("Please input userName:");
if (this.userName.equals(sc.next())) {
while (flag) {
System.out.println("Please input passWord:");
if (this.passWord.equals(sc.next())) {
System.out.println("Please input passWord:");
System.out.println("Check Pass !");
flag = false;
} else {
System.out.println("the passWord is error:");
}
}
} else {
System.out.println("the userName is error:");
}
} while (flag);
}
public static void main(String[] args) {
new DomDemoXMLUtil();
}
}
sc.nextLine()不是接收输入值,它是说输入之后才显示的值也就是你还没输入,也就是sc.nextLine()还没有值,也就是this.userName.equals(sc.nextLine())永远为false,改成sc.next()。
解决方案五:
import java.util.Scanner;
public class UserInf {
final private String userName = new String("JiHe");
final private String passWord = new String("JiHe123");
public UserInf() {
super();
// TODO Auto-generated constructor stub
check();
}
public void check() {
System.out.println("Please input userName:");
Scanner sc = new Scanner(System.in);
if (this.userName.equals(sc.nextLine())) {
System.out.println("Please input passWord:");
if (this.passWord.equals(sc.nextLine())) {
System.out.println("Check Pass !");
}
}
}
}
//试试
解决方案六:
你的代码没有问题,只是 System.out.println("Please input passWord:");
这行提示输入信息的位置放错了,执行到这行代码的时候,其实你的密码输入已经完成了。提到if判断之前就行了。
时间: 2025-01-25 12:23:17