簡體   English   中英

Java while循環不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM