读取多个扫描仪输入 [英] Reading multiple Scanner inputs
问题描述
我要做的是有多个输入都有不同的变量。每个变量都是不同方程的一部分。我正在寻找一种方法来做到这一点,我想我有一个想法。我只是想知道这是否合法,如果有更好的方法可以做到这一点。
What I am trying to do is have multiple inputs that all have different variables. Each variable will be part of different equations. I am looking for a way to do this and, I think I have an idea. I just want to know if this would be legal and, if maybe there is a better way to do this.
import java.util.*;
public class Example{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter number.");
int a = dd.nextInt();
System.out.println("Enter number.");
int b = dd.nextInt();
System.out.println("Enter number.");
int c = dd.nextInt();
}
}
推荐答案
如果每个输入询问相同的问题,你应该使用 for
循环和一组输入:
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
或者正如Chip建议的那样,你可以从一行解析输入:
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
你走在正确的轨道上,你做了什么工作。这只是一种更好,更灵活的做事方式。
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
这篇关于读取多个扫描仪输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!