简体   繁体   English

使用for循环遍历拆分索引

[英]Iterating Through A Split Index With For Loop

I have a program in which a user inputs 5 words integers separated with spaces. 我有一个程序,其中用户输入5个单词的整数,并用空格分隔。 The program then outputs the characters corresponding to the numbers. 然后程序输出与数字相对应的字符。 eg: sPaghetti omElette Apple Crouton Exciting and 2 3 1 1 1 would result in the output of PEACE . 例如: sPaghetti omElette Apple Crouton Exciting2 3 1 1 1将导致PEACE的输出。

Here's my code: 这是我的代码:

import java.util.Scanner;
Scanner userInput = new Scanner(System.in);


System.out.print("Enter five words: ");
String fiveWords = userInput.nextLine();

// Split string by word
String[] wordIndex = fiveWords.split(" ");


System.out.print("Enter five integers: ");
String fiveInts = userInput.nextLine();

// Split string by integer
String[] intIndex = fiveInts.split(" ");


for (int i = 0; i < 5; i++) {
     // Next line doesn't work, though I believe it should
     System.out.println((int) intIndex[i]);
     // Because of previous line, this one shouldn't work
     System.out.println(wordIndex[i].charAt(number));
}

When trying to iterate through the index using charAt() I keep getting a 当尝试使用charAt()遍历索引时,我不断收到

required: int
found: String

error and casting to an int doesn't seem to work. 错误并强制转换为int似乎不起作用。 How might I fix this? 我该如何解决?

System.out.println((int) intIndex[i]);

this line of code is throwing error because you are trying to parse String as int primitive which is not allowed. 这行代码将引发错误,因为您尝试将String解析为不允许的int原语。

use Integer.parseInt(intIndex[i]) to get a Integer object which can be assigned to int priitive through auto unboxing. 使用Integer.parseInt(intIndex[i])获得一个Integer对象,可以通过自动拆箱将其分配给int原始对象。

You need to change at two places: 您需要在两个地方进行更改:

First is you need to parse the String to int with Integer.parseInt("yourString") because you can access array with int address 首先,您需要使用Integer.parseInt("yourString")String解析为int,因为您可以使用int地址访问数组

Second is to get correct output you need to do -1 at index because array starts at index 0 like below: 其次是获得正确的输出,您需要在索引处执行-1 ,因为数组从索引0开始,如下所示:

for (int i = 0; i < 5; i++) {
    int number = Integer.parseInt(intIndex[i]);
    System.out.print(wordIndex[i].charAt(number-1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM