简体   繁体   English

在转换顺序有问题的java中将十进制转换为二进制

[英]Converting decimal to binary in java having trouble with reversing order

Hey so I'm taking my first cs course ever at my university its taught in java. 嘿所以我在我的大学里学习了我的第一门课程,用java教授。 I'm having trouble converting decimal to binary. 我在将十进制转换为二进制时遇到问题。 I seem to be able to get the correct output but its in reverse order, and I have no idea how to put it in the correct order, here is what I've coded so far, 我似乎能够得到正确的输出,但它的顺序相反,我不知道如何按正确的顺序排列,这是我到目前为止编码的,

import java.util.*;
public class lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
   System.out.print("Enter a decimal number to convert to binary: ");
   int x = input.nextInt();
   int y;
   String y1="";
   while(x!=0){
       y=x%2;
       x=x/2;
       y1 = Integer.toString(y);
       System.out.print(y1+" ");
     }    
}
}

您可以将数字存储在某个容器中(例如ArrayList ),然后在迭代时将其迭代回到前面打印每个数字。

要添加到Ivaylo答案,您还可以将其存储在StringBuilder并使用reverse方法将其反转

It seems you are showing the output in correct order only. 您似乎只以正确的顺序显示输出。 But if you want to reverse the current output you can use below code: 但是如果要反转当前输出,可以使用以下代码:

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number to convert to binary: ");
        int x = input.nextInt();
        int y;
        String y1="";
        String reverse = "";
        while(x!=0){
           y=x%2;
           x=x/2;
           y1 = Integer.toString(y);
         //  System.out.print(y1+" ");
           reverse = y1+" "+reverse;
         }          
        System.out.println("Reverse Order :"+reverse);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM