我想在单行代码中获取多个输入.. 例如在c ++中,我们可以像 -
int a,b,c;
cin>>a>>b>>c;
是否可以在java中使用?
答案 0 :(得分:2)
您可以使用数组来实现此目的,例如:
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);
}
答案 1 :(得分:0)
如果我正确地理解了你的问题你正在搜索这样的东西:
a = b = c = 3;
这样评估如下:
a = (b = (c = 3))
相当于:
c = 3;
b = c;
a = b;