简体   繁体   中英

Java Scanners: How to keep the same line after an input

I have a small code segment that I do not know how to fix. This is it:

System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();

The output is: y=3 on one line, and x+4 on the next. I would like them to be on the same line. How do I do this?

I'm not sure what you want to do there but maybe you just need to use one System.out.print? at the bottom of your code with example:

System.out.print("y= %d  x+%d", m , b);

It is bit confusing to understand your question why you want it ?

But here is a snippet you can try and see if it can be useful to you!

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;


 public class so1 {
     public static void main(String[] args) throws IOException {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String arrayStr = br.readLine();
         String[] auxStr = arrayStr.split(" ");
         int[] arr = new int[2];

        for(int i=0;i<auxStr.length;i++){
           arr[i]= Integer.parseInt(auxStr[i]);
        }

        System.out.println("y="+arr[0] + " x+"+arr[1]);
  }

}

Here is what you can get -

3 4
y=3 x+4

Update your question if you not find it useful . I will update accordingly.

Looks like this is how your program looks:

y=3<newline>
x+5<newline>

But you want it to look like:

y=3x+5

The problematic newlines come from using the scanner and the inherently buffered nature of standard input. In order for the scanner to know that it's reached the end of the number, there has to be whitespace (space, newline, etc.) And in order for the program to receive the input from STDIN, the character length of the int has to be larger than the buffer size, or ENTER has to be pushed.

TL;DR - What you want is very difficult to do, and maybe impossible, just using basic standard in. If you really want the output you desire you'll probably need to find a library for interacting with the console and use that.

However, if you reframe your input, you might be able to get something almost as good:

enter intercept: 5<enter>
enter slope:     3<enter>
y=3x+5

Your code, modified to produce that output:

System.out.print("enter intercept:");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("enter slope:    ");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
System.out.println("y="+m+"x+"+b);

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