[英]Converting decimal to binary in Java
I'm trying to write a code that converts a number to binary, and this is what I wrote. 我正在尝试编写一个将数字转换为二进制的代码,这就是我写的内容。 It gives me couple of errors in Eclipse, which I don't understand. 它给了我Eclipse中的几个错误,我不明白。 What's wrong with that? 这有什么问题? Any other suggestions? 还有其他建议吗? I'd like to learn and hear for any comments for fixing it. 我想学习和听取任何修复它的意见。 Thank you. 谢谢。
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages: 错误消息:
parseInt(String)
in the type Integer
is not applicable for the arguments ( String[]
) 该方法parseInt(String)
在类型Integer
是不适用的参数( String[]
(
", ; expected 令牌上的语法错误“ (
”,;预期 )
", ; 令牌上的语法错误“ )
”,; expected 预期 void
is an invalid type for the variable Binary
void
是变量Binary
的无效类型 Integer.toBinaryString(int) should do the trick ! Integer.toBinaryString(int)应该可以做到!
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error. 顺便说一句,更正你的语法,如果你正在使用Eclipse我肯定他抱怨很多错误。
Working code : 工作代码:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString()
. 也许你不想使用toBinaryString()
。 You said that you are learning at the moment, so you can do it yourself like this: 你说你正在学习,所以你可以这样做:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. 我建议你先在IDE中编译你的程序。 If you are not using an IDE I suggest you get a free one. 如果您没有使用IDE,我建议您免费使用IDE。 This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it. 这将显示您的错误在哪里,我建议您纠正错误,直到它编译之后再担心如何改进它。
For starters you've declared a method inside a method. 对于初学者,你已经在方法中声明了一个方法。 The main method is the method that runs first when you run your class. 主要方法是在运行类时首先运行的方法。 ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array. ParseInt采用字符串,而args是字符串数组 ,因此我们需要采用数组的第一个(从0开始)索引。
mod
is not a valid operator, the syntax you wanted was %
mod
不是有效的运算符,你想要的语法是%
You can use System.out.print
to print on the same line rather than println
您可以使用System.out.print
在同一行而不是println
上打印
Try these corrections and let me know how you get on: 尝试这些更正,让我知道你是如何得到的:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
There are a two main issues you need to address: 您需要解决两个主要问题:
For the first, people have already pointed out how to write that method. 首先,人们已经指出了如何编写该方法。 Note that normal method names in java are usually spelled with the first letter lowercase. 请注意,java中的常规方法名称通常拼写为首字母小写。
For the second, you're never changing the value of int1
, so you'll end up printing the LSB of the input in a tight loop. 对于第二个,你永远不会改变int1
的值,所以你最终会在紧密的循环中打印输入的LSB。 Try something like: 尝试类似的东西:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation: 说明:
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. 然后你会注意到你正在以“错误的顺序”打印数字 - 让它们将MSB打印到LSB更自然。 You're outputting in reverse. 你正在反向输出。 To fix that, you'll probably be better off with a for
loop, checking each bit from MSB to LSB. 要解决这个问题,使用for
循环可能会更好,检查从MSB到LSB的每个位。
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. for循环的想法是查看int中的32位中的每一位,从MSB开始,以便从左到右打印它们。 Something like this 像这样的东西
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i
is a left shift. 1<<i
是左移。 Similar to the right shift, but in the other direction. 类似于右移,但在另一个方向。 (I haven't tested this at all.) (我根本没有测试过这个。)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes. 一旦你开始工作,我建议你做一个进一步的练习,你尝试做同样的事情,但不要打印出前导的零。
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
Well, first I assume you know about error messages. 好吧,首先我假设您了解错误消息。 Second, your code is bleak (syntax and indentation is not correct). 其次,你的代码很惨(语法和缩进不正确)。 I would suggest the code below, 我会建议下面的代码,
import java.util.Scanner;
public class IntToBinary
{
public static void main(String[] args)
{
int number = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an integer : ");
number = sc.nextInt();
convertToBinary(number);
sc.close();
}
public static void convertToBinary(int num)
{
String str = "";
for(int a = 0; a < 8; a++)
{
if(num % 2 == 1)
{
str = "1" + str;
}
if(num % 2 == 0)
{
str = "0" + str;
}
num = num / 2;
}
System.out.println("The binary conversion is : " + str);
}
}
Hope it helps!! 希望能帮助到你!!
Here is a small bittesting code I made for Android. 这是我为Android制作的一个小测试代码。
int myres = bitTest(7, 128); int myres = bitTest(7,128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards Mikael Andersson 最诚挚的问候Mikael Andersson
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.