[英]java binary to decimal converter
This is one of my first Java programs and I am very confused why it doesn't work.这是我的第一个 Java 程序之一,我很困惑为什么它不起作用。 Help?帮助?
In addition, the else statement prints despite 'input' being given a correct value.此外,尽管 'input' 被赋予了正确的值,else 语句仍会打印。 Is there a structure for conditional statements that I'm missing?是否有我缺少的条件语句结构?
package beginning;
import java.util.Scanner;
import java.lang.Math;
// VERY BROKEN
public class BinaryDecimalConverter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Number Base To Convert: 1) Binary 2) Decimal ::");
String binOrDec = sc.next();
System.out.println("Enter Number ::");
long number = sc.nextInt();
double result = 0;
if ((binOrDec.equals("1")) || (binOrDec.equals("Binary"))) {
char[] bin = ("" + number).toCharArray(); // conversion must be String >> char[]
int index = bin.length - 1;
double aggregate = 0;
for (int i = 0; i < bin.length; i++) {
aggregate = ((Math.pow(2, i)) * (bin[index])); // when using Math.pow(a, b) - a must be 'double' data type
index = index - 1;
result = result + aggregate;
}
}
if (binOrDec.equals("2") || binOrDec.equals("Decimal")) {
// decimal-binary converter, unfinished.
}
else {
System.out.println("Invalid Input");
}
System.out.println("" + number + " >> " + result);
sc.close();
}
}
your code says: if binOrDec
is 2
or Decimal
, do nothing, else, print invalid input
.你的代码说:如果binOrDec
是2
或Decimal
,什么都不做,否则,打印invalid input
。 Computers do what you tell em to.计算机做你告诉他们做的事情。 I think you probably want an else
in front of that line to checks for 2/Decimal.我认为您可能希望在该行前面有一个else
来检查 2/Decimal。
'doesn't work' is not a great start. “不起作用”不是一个好的开始。 Help us help you:帮助我们帮助您:
Your bin
array is of type char[]
.您的bin
数组的类型为char[]
。 If I supply the binary number 1010
for example, it contains 4 characters: 1, 0, 1, and 0. That's characters .例如,如果我提供二进制数1010
,它包含 4 个字符:1、0、1 和 0。那就是characters 。 ascii characters. ascii 字符。 The ascii character 1
has a large numeric value (not 1
): ascii 字符1
具有大数值(不是1
):
char c = '1';
System.out.println(1 * c);
The above prints.... 49
.以上打印.... 49
。
So: aggregate = ((Math.pow(2, i)) * (bin[index]));
所以: aggregate = ((Math.pow(2, i)) * (bin[index]));
is multiplying by 48
or 49
depending on whether that character is a 1 or a 0. I think you may be looking for if (bin[index] == '1') aggregate = Math.pow(2, i);
乘以48
或49
具体取决于该字符是 1 还是 0。我想您可能正在寻找if (bin[index] == '1') aggregate = Math.pow(2, i);
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.