【问题标题】:Iterating Through A Split Index With For Loop使用 For 循环遍历拆分索引
【发布时间】:2018-12-09 04:10:26
【问题描述】:

我有一个程序,用户输入 5 个单词的整数,用空格分隔。然后程序输出与数字对应的字符。例如:sPaghetti omElette Apple Crouton Exciting2 3 1 1 1 将导致 PEACE 的输出。

这是我的代码:

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));
}

当尝试使用 charAt() 遍历索引时,我不断得到一个

required: int
found: String

错误和转换为 int 似乎不起作用。我该如何解决这个问题?

【问题讨论】:

标签: java for-loop split


【解决方案1】:

你需要在两个地方改变:

首先,您需要使用Integer.parseInt("yourString")String 解析为int,因为您可以使用int 地址访问数组

其次是要获得正确的输出,您需要在索引处执行-1,因为数组从索引0 开始,如下所示:

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

【讨论】:

    【解决方案2】:
    System.out.println((int) intIndex[i]);
    

    这行代码抛出错误,因为您试图将 String 解析为不允许的 int 原语。

    使用Integer.parseInt(intIndex[i]) 获取一个Integer 对象,该对象可以通过自动拆箱分配给int priitive。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      相关资源
      最近更新 更多