[英]Java while loop not working
该程序允许用户输入一个短语并将其转换为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++;
}
}
尽管这不能解决您的问题,但可以解决您的意图:
public static String rot13(String s) {
String r = "";
for (byte b : s.getBytes())
r += (char)((b + 13 - 'A') % 26 + 'A');
return r;
}
您的代码执行起来实在太复杂了。 确实,所有工作都可以在一行中完成。 使用字节算术而不是数组查找等。简单/更少的代码始终是最好的方法。
请不要对效率低下等发表评论。这是一个有效的基本实现(经过测试)。 读者可以自由地将其作为练习进行改进。
我以不同的方式实现了它,但是它可以像您期望的那样工作,仅适用于您的示例中的大写字母:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class WhileLoopIssue {
public static void main( String[] args ) throws IOException {
BufferedReader myInput = new BufferedReader( new InputStreamReader(
System.in ) );// Buffered Reader reads the
// number inputed
final List<String> letterList = Arrays.asList( "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" );
System.out.println( "Enter a phrase: " );
String phrase = myInput.readLine();
final String[] letters = phrase.split( "" ); // Split input phrase
final StringBuffer buffer = new StringBuffer(); // Variable to save letters. Could be a String as well.
for ( int i = 0; i < letters.length; i++ ) {
final int letterIndex = letterList.indexOf( letters[i] ); // Get the numeric value of the letter
if ( letterIndex < 0 ) // Skip iteration if not found. Maybe a lowercase, or an empty String
continue;
final int nextLetterIndex = 13 + letterIndex; // Actual value of the letter + 13
if ( nextLetterIndex > letterList.size() ) {
buffer.append( nextLetterIndex % letterList.size() ); // Actual value greater than the total number of letters in the alphabet, so we get the modulus for the letter
} else {
buffer.append( letterList.get( nextLetterIndex ) ); // Letter in the range, get it
}
}
System.out.println( buffer.toString() );
}
}
您的代码很可能会在内部while循环中中断,因为您没有重置i
的值。 否则,您将击中StringIndexOutOfBounds。 我建议在您的外部while循环中初始化i
,或者最好将int i = 0;
在外部while循环中。
您需要在每次迭代中重置i。 可能会在数组“ key”的末尾找到第一个字母。 您的代码将从那里找到下一个输入char,我想这不是您想要的,并且找不到该char并将抛出SIOBException。 我更改了while循环,并删除了变量y的两次增量。 看一看
while (y < length) {
i = 0; //Every Time you want to search from start of the array
//so just reset the i.
String letter = Character.toString(phrase.charAt(y));
while(!(letter.equals(key[i]))){
i++;
}
num = i;
System.out.println(keyA[num]);
y++;
}
我假设您输入的内容仅是大写字母的短语,否则您将遇到SIOBException,因为您将无法在数组中找到该字母。
顺便提一句,您应该使用其他一些有效进行搜索的数据结构(例如哈希图)来代替这些数组。 您对整个数组的线性搜索未优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.