我对使用扫描仪类读取输入有疑问。通常是这样的。如果我使用 print 而不是 println,我可以在同一行中获取输入
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter loan amount: ");
double loanAmount = sc.nextDouble();
}
}
现在我想以其他方式扩展扫描仪的使用,但我无法这样做。
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
double val = 0.0;
System.out.println(""Enter a command push n,add");
Calculator xyz = new Calculator();
while(true) {
input = sc.next();
if(input.equals("push")+val) {
val = sc.nextDouble();
xyz.push(val);
abc.getValues();
}
if(input.equals("add"))
xyz.add();
}
}
}
在上面我想在输入“push”后读取同一行中的值 例如,当我运行上面的代码时,我将得到如下的o/p
Enter a command
push
4
4.0
但我希望 o/p 为:
Enter a command
push 4
4.0
最佳答案
试试这个:-
public class A{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a command");
while(true){
String val[]=sc.nextLine().split(" ");
//System.out.println("push "+val[1]);
System.out.println(Double.parseDouble(val[1]));
}
}
}
输出:-
Enter a command
push 4
4.0
push 5
5.0
push 6
6.0
希望对您有帮助。
关于java - 使用 Scanner 类读取输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22625363/