How can I get many outputs using only one input?

Viewed 93

I want to change decimal to binary, octagonal, hexadecimal, By setting only one input(decimal) int i, I want to get 3 output: binary, octal, hexadecimal. But my problem is that when I write 'while' once to change to binary using int i, I can't get proper answer about next 'while' to change to octagonal using int i. I thought my code about octal was wrong, but when I set another int o, it worked properly...I think the result of first 'while' is used as input in next 'while'. I wonder if I use 'while' once using int i, then can't I use that original int i in next 'while'? I want to know how to get 3 output using only one input. For example,

input output
2017 b 11111100001
o 3741
h 7e1

It's my first time studying coding, so my question can be weird. Sorry:( Code below is I made using two input.

import java.util.Scanner;


public class LA {

    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int i = scn.nextInt();
        String ab = "";
        while (i > 0) {
            ab = (i % 2) + ab;
            i /= 2;
        }
        
        System.out.println("b " + ab);
        
        int o = scn.nextInt();
        String cd = "";
        while (o > 0) {
            cd = (o % 8) + cd;
            o /=8;
        }
        System.out.println( "o " + cd);
    }
}
3 Answers

You first while loop changes the value of i. At the end of this while loop i=0 so the next while loop will fail immediat.

Just keep the input in a separate variable which you don't change and copy it to i before each while loop:

int input = scn.nextInt();

int i= input;
while () {}

i=input;
while(i>0) { }

As far as I see and according to documentation. https://www.tutorialspoint.com/java/util/scanner_nextint.htm

You are calling scn.nextInt() 2 times and should be only called 1 time. Because scn.nextInt() expect input from keyboard.

Save original input in another variable. Here is the code:

import java.util.Scanner;


public class LA {

    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int originalInput = scn.nextInt();
        int i = originalInput; // copy by value, not by reference.
        String ab = "";
        while (i > 0) {
            ab = (i % 2) + ab;
            i /= 2;
        }
        
        System.out.println("b " + ab);
        
        
        int o = originalInput; // again copy original input here.
        String cd = "";
        while (o > 0) {
            cd = (o % 8) + cd;
            o /=8;
        }
        System.out.println( "o " + cd);
        
    }
}

I'm not sure if you're trying to do it the hard way on purpose, but you can also use System.out.printf() for octal and hex, and Integer.toBinaryString(anInt) for binary.

Related