如何将输入的内容(84 23 75 24)转化为数组?

huangapple go评论92阅读模式
英文:

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&lt;Integer&gt; l = new ArrayList&lt;Integer&gt;();
String[] ss = &quot;75 69 35 95 90 45 66&quot;.split(&quot; &quot;);
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&lt;Integer&gt; arrayList = new ArrayList&lt;Integer&gt;();
while(in.hasNextInt()) {
  arrayList.add(in.nextInt());
}
System.out.println(arrayList);

If the input is a string

String str[] = &quot;75 69 35 95 90 45 66&quot;.split(&quot; &quot;);
        
int len = str.length;
int numbers[] = new int[len];
int index = 0;
while(len &gt; 0) {
  try {
    numbers[index] = Integer.parseInt(str[index]);
  } catch (NumberFormatException e) {
    // something to do
  }
  System.out.println(numbers[index]);
  index++;
  len--;
}

huangapple
  • 本文由 发表于 2020年8月18日 08:24:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63460230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定