我试图在一行代码中获得多个输入。
例如在c ++中,我们可以像这样-
int a,b,c;
cin>>a>>b>>c;
Java中也有可能吗?
最佳答案
您可以为此使用数组,例如:
public static void main(String[] args) {
int[] values = new int[3];
Scanner in = new Scanner(System.in);
for(int i = 0; i < values.length; i++) {
values[i] = in.nextInt();
}
System.out.println(Arrays.toString(values));
}
更新2
在Java 8中,上述解决方案可以使用较短的版本:
Scanner in = new Scanner(System.in);
Integer[] inputs = Stream.generate(in::nextInt).limit(3).toArray(Integer[]::new);
更新1
还有另一种方法,它更接近
cin
:public class ChainScanner {
private Scanner scanner;
public ChainScanner(Scanner scanner) {
this.scanner = scanner;
}
public ChainScanner readIntTo(Consumer<Integer> consumer) {
consumer.accept(scanner.nextInt());
return this;
}
public ChainScanner readStringTo(Consumer<String> consumer) {
consumer.accept(scanner.next());
return this;
}
}
public class Wrapper {
private int a;
private int b;
private String c;
public void setA(int a) {
this.a = a;
} /* ... */
}
public static void main(String[] args) {
ChainScanner cs = new ChainScanner(new Scanner(System.in));
Wrapper wrapper = new Wrapper();
cs.readIntTo(wrapper::setA).readIntTo(wrapper::setB).readStringTo(wrapper::setC);
System.out.println(wrapper);
}