将字符串数组转换为整数数组
所以基本上用户从扫描仪输入中输入一个序列。 12, 3, 4
等
它可以是任何长度的,它必须是整数。
我想将字符串输入转换为整数数组。
所以int[0]
将是12
, int[1]
将是3
,等等。
任何提示和想法? 我正在考虑实现if charat(i) == ','
获取之前的数字并将它们解析在一起并将其应用于数组中当前可用的插槽。 但我不太清楚如何编码。
你可以从扫描器读取整个输入行,然后拆分行,
然后你有一个String[]
,将每个数字解析为int[]
,索引一对一匹配…(假设有效输入,没有NumberFormatExceptions
)
String line = scanner.nextLine(); String[] numberStrs = line.split(","); int[] numbers = new int[numberStrs.length]; for(int i = 0;i < numberStrs.length;i++) { // Note that this is assuming valid input // If you want to check then add a try/catch // and another index for the numbers if to continue adding the others (see below) numbers[i] = Integer.parseInt(numberStrs[i]); }
正如YoYo的回答所示,在Java 8中可以更简洁地实现上述目标:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
处理无效输入
在这种情况下,你需要考虑你想要做什么,你想知道那个元素有错误的输入或只是跳过它。
如果您不需要知道无效输入但只想继续解析数组,则可以执行以下操作:
int index = 0; for(int i = 0;i < numberStrs.length;i++) { try { numbers[index] = Integer.parseInt(numberStrs[i]); index++; } catch (NumberFormatException nfe) { //Do nothing or you could print error if you want } } // Now there will be a number of 'invalid' elements // at the end which will need to be trimmed numbers = Arrays.copyOf(numbers, index);
我们应该修剪结果数组的原因是int[]
末尾的无效元素将由0
表示,需要删除这些元素以区分有效输入值0
。
结果是
输入:“2,5,6,坏,10”
产出:[2,3,6,10]
如果您以后需要了解无效输入,可以执行以下操作:
Integer[] numbers = new Integer[numberStrs.length]; for(int i = 0;i < numberStrs.length;i++) { try { numbers[i] = Integer.parseInt(numberStrs[i]); } catch (NumberFormatException nfe) { numbers[i] = null; } }
在这种情况下,错误输入(不是有效整数)元素将为null。
结果是
输入:“2,5,6,坏,10”
输出:[2,3,6,null,10]
您可以通过不捕获exception来提高性能( 有关此内容的更多信息,请参阅此问题 )并使用不同的方法来检查有效的整数。
逐行
int [] v = Stream.of(line.split(",\\s+")).mapToInt(Integer::parseInt).toArray();
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class MultiArg { Scanner sc; int n; String as; List numList = new ArrayList (); public void fun() { sc = new Scanner(System.in); System.out.println("enter value"); while (sc.hasNextInt()) as = sc.nextLine(); } public void diplay() { System.out.println("x"); Integer[] num = numList.toArray(new Integer[numList.size()]); System.out.println("show value " + as); for (Integer m : num) { System.out.println("\t" + m); } } }
但要终止while循环,你必须在输入结束时放置任何字符。
恩。 输入:
12 34 56 78 45 67 .
输出:
12 34 56 78 45 67