0

記号 & の後の文字が数字か文字かをチェックするメソッドを取得しようとしています。数値の場合、バイナリに変換されます。文字の場合は 16 に設定され、別の単語が使用されている場合は 1 ずつ増加します。問題は、何らかの理由でこれがうまくいかないことです。助言がありますか?

try {
       ReadFile files = new ReadFile(file.getPath());
       String[] anyLines = files.OpenFile();

       int i;

       for (i=0; i<anyLines.length; i++) {
           String input = anyLines[i];
           String[] lines = input.split("\n");

           int wordValue = 16;

           Map<String, Integer> wordValueMap = new HashMap<String, Integer>();

           for (String line : lines) {
               // if line doesn't begin with &, then ignore it
               if (!line.startsWith("&")) {
                   continue;
               }

               // remove &
               line = line.substring(1);

               Integer binaryValue = null;

               if (line.matches("\\d+")) {
                   binaryValue = Integer.toBinaryString(131072 +
                              Integer.parseInt(anyLines[i])).substring(2,18);
               }
               else if (line.matches("\\w+")) {
                   binaryValue = wordValueMap.get(line);

                   if (binaryValue == null) {
                       binaryValue = wordValue;
                       wordValueMap.put(line, binaryValue);
                       wordValue++;
                   }
               }
           }
       }

入力:

&4
...
&hello
...
&ok

出力:

(5 translated into binary) : 0000000000000100
...
(16 translated into binary)
...
(17 translated into binary, or 16+1)

メソッドの出力は次のとおりです。

101
1001100
1001100
1001100
1001100
1001100
1001100
1001100
&5
1110110000010000 
&hello
1110001100001000 
&goodbye
1110101010001000 
(NEXT)
&goodbye
1111000010001000 
&hello
1110001110001000 
&BILL
1110001100000110 
&NEXT
1110101010000111 
(BILL)
&BILL
1110101010000111 

そして、これが私が読んでループしている元のテキストです(変更なしのanyLines [i]):

&5
var1 
&hello
var2 
&goodbye
var2 
(NEXT)
&goodbye
var3 
&hello
var4 
&BILL
var5 
&NEXT
var6 
(BILL)
&BILL
var5 

var は、値を持つ単なる変数です。私はすでにそれらの世話をしました。


これが私の試みです:

String input = "This is a test line\n"
           + "&hello\n"
           + "&4\n"
           + "&32";

String[] lines = input.split("\n");
int wordValue = 26;

Map<String, Integer> wordValueMap = new HashMap<String, Integer>();

for (String currentLine : lines)
{
if (!currentLine.startsWith("&"))
{
    continue;
}

currentLine = currentLine.substring(1);
Integer value;

if (currentLine.matches("\\d+"))
{
    value = Integer.parseInt(currentLine);
}
else if (currentLine.matches("\\w+"))
{
    value = wordValueMap.get(currentLine);

    if(value == null)
    {
        int binaryValue = wordValue++;
        wordValueMap.replace(currentLine, binaryValue);
        /*
         * This is just there to ensure that the print statement below doesn't have a 
         * null value.
         */
        value = binaryValue;
    }
}
else
{
    System.out.println("Invalid input");
    break;
}

System.out.println(Integer.toBinaryString(value));
}
4

1 に答える 1