在 Java 程序扫描器只工作一次而 i/ve 使用了两次
In Java Program Scanner is Working only once whereas i/ve used it twice
import java.util.Scanner;
class Student1{
int a;
String b;
void get(int c, String d){
a = c;
b = d;
}
void show(){
System.out.print("Id is " + a +"\n");
System.out.print("Name is " + b);
}
public static void main(String args[]){
Scanner one = new Scanner(System.in);
System.out.print("Enter Id");
int e = one.nextInt();
System.out.print("Enter Your Name");
String f = one.nextLine();
Student1 s = new Student1();
s.get(e ,f);
s.show();
}
}
当程序执行时它只询问 Id 之后它显示结果它从不询问 Name
同时使用 nextInt()
和 nextLine()
会变得复杂。你可以试试这个只使用 nextLine()
;
的版本
public static void main(String args[]){
Scanner one = new Scanner(System.in);
System.out.print("Enter Id");
String number =one.nextLine();
int e = Integer.parseInt(number);
System.out.print("Enter Your Name");
String f = one.nextLine();
Student1 s = new Student1();
s.get(e ,f);
s.show();
}
为什么 nextInt() 和 nextline() 会产生一些问题:
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
您必须在整数后输入换行符。为此,该空白字符串充当 one.nextLine()
的输入。为避免这种情况,一种方法是在 String f = one.nextLine()
;
之前再添加一个 one.nextLine()
语句
仅使用 nextLine()
方法并更改代码的以下行以提高效率
Student1 s = new Student1();
s.get(e ,f);
为 Student1 创建构造函数 class
Student1(int c, String d)
{
a = c;
b = d;
}
main() 方法内部
Student1 s = new Student1(e,f);
您可以在创建对象时使用构造函数初始化变量。
import java.util.Scanner;
class Student1{
int a;
String b;
void get(int c, String d){
a = c;
b = d;
}
void show(){
System.out.print("Id is " + a +"\n");
System.out.print("Name is " + b);
}
public static void main(String args[]){
Scanner one = new Scanner(System.in);
System.out.print("Enter Id");
int e = one.nextInt();
System.out.print("Enter Your Name");
String f = one.nextLine();
Student1 s = new Student1();
s.get(e ,f);
s.show();
}
}
当程序执行时它只询问 Id 之后它显示结果它从不询问 Name
同时使用 nextInt()
和 nextLine()
会变得复杂。你可以试试这个只使用 nextLine()
;
public static void main(String args[]){
Scanner one = new Scanner(System.in);
System.out.print("Enter Id");
String number =one.nextLine();
int e = Integer.parseInt(number);
System.out.print("Enter Your Name");
String f = one.nextLine();
Student1 s = new Student1();
s.get(e ,f);
s.show();
}
为什么 nextInt() 和 nextline() 会产生一些问题:
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
您必须在整数后输入换行符。为此,该空白字符串充当 one.nextLine()
的输入。为避免这种情况,一种方法是在 String f = one.nextLine()
;
one.nextLine()
语句
仅使用 nextLine()
方法并更改代码的以下行以提高效率
Student1 s = new Student1();
s.get(e ,f);
为 Student1 创建构造函数 class
Student1(int c, String d)
{
a = c;
b = d;
}
main() 方法内部
Student1 s = new Student1(e,f);
您可以在创建对象时使用构造函数初始化变量。