简体   繁体   English

Java while循环不起作用

[英]Java while loop not working

The program allows the user to enter a phrase and converts it to ROT13, where each English letter entered, becomes the letter 13 places after it(A becomes N). 该程序允许用户输入一个短语并将其转换为ROT13,在其中输入的每个英语字母都变成它之后的第13个字母(A变为N)。 My current code works when 1 character is entered, however I need it to run through the code the number of times there are characters. 当输入1个字符时,我当前的代码有效,但是我需要它遍历代码中存在字符的次数。 I've tried to put in a while loop at the beginning, but it doesn't seem to be working. 我已经尝试在开始时放入一个while循环,但是它似乎没有用。 Why is this? 为什么是这样?

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

See comments on code. 查看有关代码的注释。

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

    }

Although this doesn't answer your problem, it answers your intention: 尽管这不能解决您的问题,但可以解决您的意图:

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

Your code is far too complicated for what it's doing. 您的代码执行起来实在太复杂了。 Really, all the work can be done in one line. 确实,所有工作都可以在一行中完成。 Use byte arithmetic rather than array lookups etc. Simple/less code is always the best approach. 使用字节算术而不是数组查找等。简单/更少的代码始终是最好的方法。

Please no comments about inefficiencies etc. This is a basic implementation that works (tested). 请不要对效率低下等发表评论。这是一个有效的基本实现(经过测试)。 The reader is free to improve on it as an exercise. 读者可以自由地将其作为练习进行改进。

I have implemented it in a different way, but it works as you expect, only for uppercase as in your example: 我以不同的方式实现了它,但是它可以像您期望的那样工作,仅适用于您的示例中的大写字母:

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

You're code will most likely break in your inner while loop as you are not resetting the value of i . 您的代码很可能会在内部while循环中中断,因为您没有重置i的值。 By not doing so your gonna hit StringIndexOutOfBounds. 否则,您将击中StringIndexOutOfBounds。 I would recommend initialising i in your outer while loop or better yet just move int i = 0; 我建议在您的外部while循环中初始化i ,或者最好将int i = 0; inside the outer while loop. 在外部while循环中。

You need to reset i in each iteration. 您需要在每次迭代中重置i。 It may happen that first letter found toward the end of the array "key". 可能会在数组“ key”的末尾找到第一个字母。 Your code will find next input char there onward, I guess this is not what you want, and will not find that char and will throw SIOBException. 您的代码将从那里找到下一个输入char,我想这不是您想要的,并且找不到该char并将抛出SIOBException。 I have changed the while loop, removed twice increment in variable y as well. 我更改了while循环,并删除了变量y的两次增量。 Have a look 看一看

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

I am assuming what ever you enter as input is a phrase of ONLY upper-case alphabets, else you will come across the SIOBException as you you will not be able to locate that letter in your array. 我假设您输入的内容仅是大写字母的短语,否则您将遇到SIOBException,因为您将无法在数组中找到该字母。

Just on side note, instead of those arrays you should use some other data structures which are efficient for searching like hashmap. 顺便提一句,您应该使用其他一些有效进行搜索的数据结构(例如哈希图)来代替这些数组。 Your linear search across the array is not optimized. 您对整个数组的线性搜索未优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM