重複の可能性:
Javaで文字列を比較するにはどうすればよいですか?
私はJavaにかなり慣れていないので、2進数から10進数へのコンバーターを作成できたので、16進数から10進数へのコンバーターを作成しようとしています。
私が抱えている問題は、基本的に、文字列内の特定の文字を別の文字列と比較することです。これは、比較される現在の文字を定義する方法です。
String current = String.valueOf(hex.charAt(i));
これは私がキャラクターを比較しようとする方法です:
else if (current == "b")
dec += 10 * (int)Math.pow(16, power);
12などの数字だけを入力してコードを実行しようとすると機能しますが、「b」を使用しようとすると、奇妙なエラーが発生します。プログラムを実行した結果全体は次のとおりです。
run:
Hello! Please enter a hexadecimal number.
2b
For input string: "b" // this is the weird error I don't understand
BUILD SUCCESSFUL (total time: 1 second)
数値変換だけでプログラムを正常に実行する例を次に示します。
run:
Hello! Please enter a hexadecimal number.
22
22 in decimal: 34 // works fine
BUILD SUCCESSFUL (total time: 3 seconds)
これについての助けをいただければ幸いです、ありがとう。
編集:メソッド全体をここに置くと便利だと思います。
編集2:解決しました!誰が答えを受け入れるべきかわかりませんが、それらはすべてとても良くて役に立ちました。とても矛盾しました。
for (int i = hex.length() - 1; i >= 0; i--) {
String lowercaseHex = hex.toLowerCase();
char currentChar = lowercaseHex.charAt(i);
// if numbers, multiply them by 16^current power
if (currentChar == '0' ||
currentChar == '1' ||
currentChar == '2' ||
currentChar == '3' ||
currentChar == '4' ||
currentChar == '5' ||
currentChar == '6' ||
currentChar == '7' ||
currentChar == '8' ||
currentChar == '9')
// turn each number into a string then an integer, then multiply it by
// 16 to the current power.
dec += Integer.valueOf(String.valueOf((currentChar))) * (int)Math.pow(16, power);
// check for letters and multiply their values by 16^current power
else if (currentChar == 'a')
dec += 10 * (int)Math.pow(16, power);
else if (currentChar == 'b')
dec += 11 * (int)Math.pow(16, power);
else if (currentChar == 'c')
dec += 12 * (int)Math.pow(16, power);
else if (currentChar == 'd')
dec += 13 * (int)Math.pow(16, power);
else if (currentChar == 'e')
dec += 14 * (int)Math.pow(16, power);
else if (currentChar == 'f')
dec += 15 * (int)Math.pow(16, power);
else
return 0;
power++; // increment the power
}
return dec; // return decimal form
}