简体   繁体   English

如何更改打印的方向?

[英]How can I change the orientation of a print?

switch (oper){
    case ('A'):
    case ('a'):
        do{
            System.out.print(num%2);
            num=(num/2);
        }while(num>=1);
        break; 
}

So I got this code to convert from decimal to binary, it outputs the result in binary but turned around for example, the number 50 is outputed as 010011 instead of 110010, anyone know a way to turn around the print?所以我得到了这个代码从十进制转换为二进制,它以二进制输出结果,但反过来,例如,数字 50 输出为 010011 而不是 110010,有人知道如何转换打印吗?

There is no "magic switch" that you can just turn on to print backwards.没有“魔术开关”可以打开以向后打印。 What you can do, however, is to push all the strings you want to print onto a stack , and then print them as you pop them.但是,您可以做的是将要打印的所有字符串推送到堆栈上,然后在弹出它们时打印它们。

Stack<String> stack = new Stack<>();
do{
    stack.push(Integer.toString(num % 2));
    num=(num/2);
}while(num>=1);
while (!stack.empty()) {
    System.out.println(stack.pop());
}

This works because a stack is a Last In First Out data structure.这是有效的,因为堆栈是后进先出数据结构。 What gets pushed last gets popped first .最后推送的内容首先弹出。

Simply use a StringBuilder https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/StringBuilder.html#reverse()只需使用StringBuilder https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/StringBuilder.html#reverse()

StringBuilder str = new StringBuilder();
str.append();
System.out.print(str.reverse().toString());

From your code provided:从您提供的代码中:

StringBuilder str = new StringBuilder();

switch (oper){
    case ('A'):
    case ('a'):
        do{
            str.append(num%2);
            num=(num/2);
        }while(num>=1);
        break; 
}

System.out.print(str.reverse().toString());

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

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