簡體   English   中英

Java-在一個數組列表中讀取值Chars並在另一個數組列表中將其轉換為字符串

[英]Java - reading values Chars in one array list and converting them into strings in another

我正在研究一個將用戶輸入轉換為摩爾斯電碼的程序。 為此,我有兩個文本文件,一個存儲摩爾斯字母表,另一個存儲英語字母表。

我試圖一一讀取用戶輸入中的字符,並將它們與字符數組列表中的字符進行比較以找到適當的索引。 然后,我只將平移變量附加在莫爾斯數組列表中該索引處的值。 (它們是經過組織的,這樣才能起作用)。

但是由於某種原因,當我將char與普通數組列表進行比較時,我收到了IndexOutOfBoundsException。

這是我的代碼:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class MorseCode
{
    public static String translate(String input) throws IOException
    {
        //Convert input to lowercase
        input.toLowerCase();
        //Create final statement
        String translation = "";

        //Store values
        ArrayList<String> morse = new ArrayList<String>();
        ArrayList<Character> normals = new ArrayList<Character>();

        //Scan and read file
        Scanner morseFile = new Scanner(new File("morsecode.txt"));
        Scanner normalsFile = new Scanner(new File("normals.txt"));
        while (morseFile.hasNext())
        {
            morse.add(morseFile.next());
        }
        while (normalsFile.hasNext())
        {
            normals.add(normalsFile.next().charAt(0));
        }

        //Begin checking for chars and converting
        for (int i = 0; i < input.length() + 1; i++)
        {
            //Set current char
            char currentChar = input.charAt(i);

            //Begin comparing chars
            for (int b = 0; b <= normals.size() + 1; b++)
            {
                //If char equals x
                if (currentChar == normals.get(b))
                {
                    //Append translation
                    translation += morse.get(b);
                }
                else
                {
                    //Nothing
                }
            }
        }
        return translation;
    }
}

在for循環的內部條件b <= normals.size() + 1刪除+ 1。 b <= normals.size()就足夠了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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