gpt4 book ai didi

Java while 循环不工作

转载 作者:行者123 更新时间:2023-11-30 04:14:20 25 4
gpt4 key购买 nike

该程序允许用户输入一个短语并将其转换为ROT13,其中输入的每个英文字母将成为其后13位的字母(A变为N)。我当前的代码在输入 1 个字符时有效,但是我需要它按照字符数运行代码。我试图在开始时加入一个 while 循环,但它似乎不起作用。这是为什么?

import java.io.*;

public class J4_1_EncryptionErasetestCNewTry
{

public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed

String key [] = {"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"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};

System.out.println("Enter a phrase: ");
String phrase = myInput.readLine();

int length = phrase.length();
int y = 0, i = 0, num = 0;

while (y <= length) {
String letter = Character.toString(phrase.charAt(y));
y++;
while(!(letter.equals(key[i]))){
i++;
}
num = i;
System.out.println(keyA[num]);
y++;
}
}
}

最佳答案

查看代码注释。

public static void main(String[] args) {

BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed

String key [] = {"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"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};

System.out.println("Enter a phrase: ");
String phrase = "";

try {
phrase = myInput.readLine();
} catch (IOException e) {
e.printStackTrace();
}

int length = phrase.length();
int y = 0, i = 0, num = 0;

while (y < length) { // This should be y < length. Otherwise, it would throw a StringIndexOutOfBoundsException.
i=0; // Re-initialize
String letter = Character.toString(phrase.charAt(y));
// y++; // Unecessary incremental
while(!(letter.equalsIgnoreCase(key[i]))){
i++;
}
num = i;
System.out.print(keyA[num]);
y++;
}

}

关于Java while 循环不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18776707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com