NetBeans为什么不等待用户输入?
所以我在运行时遇到了代码问题(我刚刚开始,因此请帮助)。 NetBeans不会等待用户输入,因此它只是在输出中显示了一些奇怪的东西,在我的文本旁边。NetBeans为什么不等待用户输入?
package javalol;
/**
*
* @author sandy_000
*/
public class JavaLol {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String Printf="Please enter your first name:";
String Printl="Please enter your last name:";
System.out.println(Printf);
String firstName=System.in.toString();
System.out.println(Printl);
String lastName=System.in.toString();
Friend friend=new Friend(firstName, lastName);
System.out.println("How are ya, "+friend+"?!");
}
}
输出:
Please enter your first name:
Please enter your last name:
How are ya, Friend{[email protected], [email protected]}?!
BUILD SUCCESSFUL (total time: 2 seconds)
System.in
不读你的输入,因为它是一个标准的输入变量。这就是为什么输出是[email protected]
。
您必须使用Scanner
来读取输入(请记住为此导入java.util.Scanner
)。
像这样:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String Printf="Please enter your first name:";
String Printl="Please enter your last name:";
System.out.println(Printf);
String firstName=scan.next();
System.out.println(Printl);
String lastName=scan.next();
Friend friend=new Friend(firstName, lastName);
System.out.println("How are ya, "+friend+"?!");
scan.close();
}
为了获得良好的代码风格,最好是写printf
和printl
代替Printf
和Printl
。
如果您尚未覆盖Friend
类的toString()
方法,则会在输出中遇到另一个问题。因此,最好对变量使用getter
方法,并将输出更改为:System.out.println("How are ya, " + friend.getFirstName + friend.getLastName() + "?!");
我尝试在我的第一个代码(项目)中使用扫描仪,它带回了一个错误(我认为我想为扫描仪创建另一个类,但我不知道该怎么做,也没有神经) 。此外,在那个项目中,我尝试使用'System.in.read()',它在那里工作。 'toString()'是我的问题的核心吗?此外,如果是这样的话,我该如何制作课程(我不是指:“如何将文件添加到我的项目中?”,我的意思是:“我如何知道要在课堂上编写什么代码它的工作原理是什么?“)?附:我是一个初学者,所以在代码中轻松一下(解释'.next()'函数)。 –
为了理解'.next()'函数,您应该学会阅读[JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)。 'System.in.read()'没有达到你的期望值(参见[这里](http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read() )) – Blobonat
您不想调用'System.in.toString()'(调用'PrintStream.toString()')需要一个'扫描仪'或'读取器'并包装'System.in'来读取。 –