英文:
How to make an input ( 84 23 75 24) into an array?
问题
我没有任何代码放在这里,因为这是开始。但我会要求输入数字,格式如下:"75 69 35 95 90 45 66"。如何处理输入以将其转换为数组?我知道如何扫描它并将其转换为字符串,但仅限于此。
英文:
I won't have any code to put here since this is the start of it. But I would be asking for the input of numbers that will be inputted like this "75 69 35 95 90 45 66"
What do I do with the input to turn it into an array, I know how to scan it and turn it into string but that's about it.
答案1
得分: 1
这是一个示例代码,可以使字符串“explode”。然后,每个项目都被转换为整数。
List<Integer> l = new ArrayList<Integer>();
String[] ss = "75 69 35 95 90 45 66".split(" ");
for (String s : ss) {
l.add(Integer.valueOf(s));
}
System.out.println(l);
英文:
Here is sample code that makes "explode" the string. Each item is then converted to integer.
List<Integer> l = new ArrayList<Integer>();
String[] ss = "75 69 35 95 90 45 66".split(" ");
for (String s: ss) {
l.add(Integer.valueOf(s));
}
System.out.println(l);
答案2
得分: 1
如果输入是一个合适的整数。
Scanner in = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while(in.hasNextInt()) {
arrayList.add(in.nextInt());
}
System.out.println(arrayList);
如果输入是一个字符串。
String str[] = "75 69 35 95 90 45 66".split(" ");
int len = str.length;
int numbers[] = new int[len];
int index = 0;
while(len > 0) {
try {
numbers[index] = Integer.parseInt(str[index]);
} catch (NumberFormatException e) {
// something to do
}
System.out.println(numbers[index]);
index++;
len--;
}
英文:
If the input is a proper integer.
Scanner in = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while(in.hasNextInt()) {
arrayList.add(in.nextInt());
}
System.out.println(arrayList);
If the input is a string
String str[] = "75 69 35 95 90 45 66".split(" ");
int len = str.length;
int numbers[] = new int[len];
int index = 0;
while(len > 0) {
try {
numbers[index] = Integer.parseInt(str[index]);
} catch (NumberFormatException e) {
// something to do
}
System.out.println(numbers[index]);
index++;
len--;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论