我有这个程序,它将根据用户输入的指定值输出字母或单词。例如,当用户输入字母 a 时,用户将再次输入数字(例如 2),输出将为 c。在我的程序中,当用户键入一个字母并且该字母直到 z 时,它就可以工作。然而,当用户输入的单词超过字母 z 的数量时,将不会有输出。例如用户输入 xyz,然后输入 4 要跳过,则没有输出。
public class FinalsActivity2 {
Scanner fc = new Scanner(System.in);
char characters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
File file = new File("C:\\Users\\TeonGo\\Desktop\\final2.txt");
PrintWriter pw = new PrintWriter(file);
public FinalsActivity2() throws IOException {
System.out.print("Enter text:");
String text = fc.nextLine();
System.out.print("Enter number:");
int num = Integer.parseInt(fc.nextLine());
try {
for (int f = 0; ; f++) {
for (int c = 0; c < 26; c++) {
if (text.charAt(f) == characters[c]) {
pw.print(characters[num + c]);
}
}
}
} catch (Exception e) {
}
pw.close();
}
public static void main(String[] args) throws IOException {
new FinalsActivity2();
}
}
最佳答案
您没有看到任何输出,因为当您尝试访问 z
之后的 characters
数组时,您收到了 ArrayIndexOutOfBoundsException
,因为您是吞下异常你就看不到它了。
如果您想在到达 z
之后返回到 characters
数组,请使用取模结果来获取索引。像这样的东西。
for (int f = 0; f < text.length(); f++) {
for (int c = 0; c < characters.length; c++) {
if (text.charAt(f) == characters[c]) {
int idxToGet = (num + c) % characters.length;
pw.print(characters[idxToGet]);
}
}
}
如果您只想忽略任何超过 z
的内容,请使用以下内容
for (int f = 0; f < text.length(); f++) {
for (int c = 0; c < characters.length; c++) {
int idxToGet = num + c;
if (text.charAt(f) == characters[c] && idxToGet < characters.length) {
pw.print(characters[idxToGet]);
}
}
}
关于java - 当用户输入数字跳过字母时,跳过字母(字母 z)时无输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36578281/