Java while循环不起作用

时间:2013-09-13 01:13:47

标签: java arrays string loops while-loop

该程序允许用户输入一个短语并将其转换为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++;
        }
    }
}

5 个答案:

答案 0 :(得分:1)

查看有关代码的评论。

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

    }

答案 1 :(得分:1)

虽然这不能解决您的问题,但它可以回答您的意图:

public static String rot13(String s) {
    String r = "";
    for (byte b : s.getBytes())
        r += (char)((b + 13 - 'A') % 26 + 'A');
    return r;
}

您的代码太复杂了,无法正常运行。真的,所有的工作都可以在一条线上完成。使用字节算术而不是数组查找等。简单/更少的代码始终是最好的方法。

请不要评论效率低下等问题。这是一个可行的(测试过的)基本实现。读者可以自由地改进它作为练习。

答案 2 :(得分:0)

我已经以不同的方式实现了它,但它按预期工作,仅在示例中为大写:

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

答案 3 :(得分:0)

由于您没有重置i的值,因此您的代码很可能会在内部循环中断开。如果不这样做,你将击中StringIndexOutOfBounds。我建议您在外部while循环中初始化i或更好,但只需在外部while循环中移动int i = 0;

答案 4 :(得分:0)

您需要在每次迭代中重置i。可能会发生第一个字母在数组“key”的末尾找到。你的代码将在那里找到下一个输入字符,我想这不是你想要的,并且不会找到该字符并且将抛出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,因为您将无法在数组中找到该字母。

请注意,您应该使用一些其他数据结构而不是那些数组,这些数据结构可以像hashmap一样高效搜索。您对整个阵列的线性搜索未进行优化。