简体   繁体   中英

how to get the final output without pressing enter?

In the below code when i enter the input as***(i just don't enter the input one by one instead i copy and paste the entire input)***
4
101
1111
00110
111111

i am supposed to get
5
15
6
63
instead i get
5
15
6
and after i press enter here i get the 63

import java.util.Scanner;

public class VonNeumanLovesBinary {
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int no = scn.nextInt();
        while (no > 0)
        {
            int binary = scn.nextInt();
            int i = 0 ;
            int sum = 0;
            while(binary > 0 )
            {
                int digit = binary  % 10;
                sum += Math.pow(2,i) * digit ;
                binary /= 10;
                i++;

            }
            System.out.println(sum);
            no--;
        }
    }
}

This code is written Intellij IDE. Please help me out. this is the problem of the ide?

Its not the fault of the IDE. It is how it deals with copy-pasting text into the console.

The text is handed over to the Java code as you paste it, line by line. Input is only handed over once you finish the line . The previous lines are all terminated already with a newline symbol but the last line is not .

So you have to either add a newline to the end of your copy-pasta or hit enter to produce one yourself. So before you terminate the last line, the last line is never handed over to Java but is still only in the console.

For example, if you copy pasta this instead:

4
101
1111
00110
111111

(note the last, empty line)

it will work as expected, since you finished the 111111 line, ie it is 111111\n and not just 111111 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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