在弄清楚如何使用数组创建嵌套循环时遇到问题



我目前在为当前问题定义嵌套循环和数组时遇到问题:

编写一个读取整数、单词列表和字符的程序。整数表示列表中有多少单词。程序的输出是列表中至少包含一次字符的每个单词。为了简化编码,在每个输出单词后面加一个逗号,甚至是最后一个逗号。在最后一个输出的末尾添加一行新行。假设列表中至少有一个单词将包含给定的字符。假设单词列表将始终包含少于20个单词。

这就是我目前拥有的

import java.util.Scanner;
public class labProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String[] userList = new String[20];
int numElements = scnr.nextInt();
char userChar = scnr.next().charAt(0);
int i;
for(i = 0; i < userList.length(); ++i) {
userList[i] = scnr.next();
}
}

}

我应该采取哪些步骤来定义和循环这个问题?

您需要通过添加一个内部for循环来遍历每个单词,该循环遍历单词[i]中的每个字符。在这个内部循环中,您可以检查当前角色是否与您想要的目标角色匹配。

//loops through the list of words
for(int i = 0; i < userList.length; i++){
boolean letterExists = false;
// inner for loop will iterate through each character in wordlist[i]
for(int j = 0; j < userList[i].length; j++) {
char currentLetter = userList.charAt(j);
if(currentLetter ==  userChar)
letterExists = true;
}
// print if the user exists
if(letterExists)
System.out.println(userList[i]);
}

您可以交换一些指令的顺序,使数组变得任意长。

这里有一个例子:

import java.util.Scanner;
public class LabProgram { 
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements = scnr.nextInt();   // ask the user the elements of the array
String[] userList = new String[numElements];    // create the array
char userChar = scnr.next().charAt(0);  // ask the user for the char to search
// adding the strings to the array
for(int i = 0; i < userList.length; ++i) {
userList[i] = scnr.next();  
}
// searching the char in the strings and printing the matched strings
System.out.println("Matched Strings: ");
for (int i=0; i < userList.length; i++) 
for (int j=0; j < userList[i].length(); j++)
if (Character.compare(userList[i].charAt(j), userChar) == 0) {
System.out.print(userList[i] + ",");
continue;
}    
}
}

还可以考虑不使用指令continue,而是可以使用新的数组来存储匹配的字符串。

最新更新