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

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);

Related

Scanner nextLine, stuck in while loop or exiting at odd times

I started doing the CodeAbbey problems last night, they mentioned using stdIn since some the input data is long so copy/paste is much easier than by hand. I had never used the Scanner before so it looked easy enough. I got it working for single line inputs then I got a problem where the input was:
867955 303061
977729 180367
844485 843725
393481 604154
399571 278744
723807 596408
142116 475355
I assumed that nextLine would read each couple, xxxx yyyyy. I put the code in a while loop based on if nextLine is not empty. It runs, but I get weird output, and only after I hit return a few times.
package com.secryption;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input: ");
Scanner scanner = new Scanner(System.in);
String input = "";
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
String[] resultSet = input.split("\\s+");
for(String s : resultSet) {
System.out.println(s);
}
}
}
I thought I might need something after adding scanner.nextLine() to input. I tried a space and that didn't help. I tried a newline and that didn't make it better.
This "should" put all the numbers in a single array, nothing special. What am I missing with scanner?
EDIT: Ok so #Luiggi Mendoza is right. I found this How to terminate Scanner when input is complete? post. So basically it it working, I just expected it to do something.
The problem is here:
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
Scanner#nextLine reads the line and will continue reading. You're reading two lines and not storing the result of the first line read, just reading and storing the results of the second.
Just change the code above to:
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(" ");
}
hasNext() is an end of file indicator that terminates by combining keys control d on Mac ox and control z on windows pressing enter won't send the right message
to JVM

What is wrong with my Java coding? It is saying that it cannot find the symbol scanf. How should I recode this?

I am trying to make a Java code that enables the user to input any number and the Java makes a triangle out of that number using *
My code is not compiling, but I think I've finally almost got it down. The only problem is, that it is not recognizing scanf.
Here is my code:
import java.util.Scanner;
class triangle
{
public static void main(String[] args)
{
char print='*';
int row,col;
int noOfRows;
System.out.printf("Enter number of rows to be printed\n");
scanf("%d",noOfRows);
{
for(col=1;col<=row;col++)
{ // this brace is useless, since there is only one statement in this for loop
System.out.printf("%c",print);
} // same for this one
System.out.printf("\n");
}
}
}
How can I fix this?
scanf() and printf() are supported by C and C++ in java:
1. BufferedReader or Scanner for reading from console(System.in).
2. print() or println() for printing to console.(System.out).
You need to declare a new object of the scanner.
Also, to print, is System.out.println("");
You should use Scanner class like this: Scanner scanner = new Scanner(System.in); and do something like this:
System.out.println("Enter number of rows");
noOfRows = scanner.nextInt();
My friend, you use scanf in "C"of "C++" in java we use System.in

ArrayIndexOutOfBoundsException on a Split String in a array

So I am doing some problems on the UVa online problem judge, but on a relativity easy problem, I keep on getting a ArrayIndexOutOfBoundsException. To understand the code, here is the problem.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
The error message is:
reportException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:16)
And I am using the sample input given.
Edit:
I have already tried added println statements in the code and figured out that the number is not being read. I am trying to understand why.
OK, after some messing around on my machine I think I found what might be at least part of the problem. The issue is that I'm not sure what the precise input is, so I'm going off of what I could get working on my machine.
So you start up your program, and it waits for a prompt at this line:
int t = scan.nextInt();
You enter your integer, and the program moves on as expected:
Input: 100 // Then press enter to continue
The input is parsed, and now t is set to 100.
Then when your program enters your for loop, it comes across this line:
String d = scan.nextLine();
Yet for some reason the program doesn't wait for input! (Or at least it didn't on my machine)
I believe the issue lies here:
Input: 100 // Then press enter to continue
^^^^^^^^^^^
What I think is happening is that your input is really
Input: 100\n
^^
That character (\r\n on Windows) is what's input when you hit enter. It's a newline character that tells the console to go to the next line.
So as a result, what I think happens is this:
Input: 100\n
Scanner parses 100, leaving the \n in the input stream
Then at the nextLine() call, the scanner sees \n on the input stream, which denotes end of line, so it thinks you already input the entire line! Because what it thought was your input was only the newline character, it returns an empty string, because your "input" was an empty string and the newline character. Your program then goes to split the newline character by spaces, rightly returns an array with a single element, and then your program promptly crashes when accessing an out-of-bounds index.
What might work better is reading an entire line first and parsing the integer so your scanner doesn't get ahead of itself, like this:
int t = Integer.parseInt(scan.nextLine());
Just as a warning: This is what I've been able to come up with based on using OP's code as-is on my machine. I was unable to get a situation where the only element in parts was "donate". I will update further as I get more info.
The error message means the array parts's length less than 2, sometimes.
It means the variable d does not always contain the string BLANK SPACE, " ", what you split by.
try this code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
/*
* Add IF statement,
*/
if (parts.length() > 1) {
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
}

Scanner NoSuchElementException

I made a program that asks for 3 integers to output type of triangle. Everything runs and compiled successfully, however, it seems the part where it asks the user to see if they want to loop it again, the online compiler outputs the error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at Assignment5.main(Assignment5.java:56)
import java.util.Scanner;
public class Assignment5 {
public static void main (String[]args)
{
for (int a = 0; a < Integer.MAX_VALUE; a++)
{
Scanner userInput = new Scanner(System.in);
Scanner answer = new Scanner(System.in);
int x,y,z;
System.out.println("Enter the sides of the triangle: ");
x = userInput.nextInt();
y = userInput.nextInt();
z = userInput.nextInt();
Tri isos = new Tri(x,y,z);
Tri equal = new Tri(x,y,z);
Tri scalene = new Tri(x,y,z);
// check the equilateral triangle
System.out.println(equal.toString() + " triangle:");
if (equal.is_isosceles())
System.out.println("\tIt is isosceles");
else
System.out.println("\tIt is not isosceles");
if (equal.is_equilateral())
System.out.println("\tIt is equilateral");
else
System.out.println("\tIt is not a equilateral");
if (equal.is_scalene())
System.out.println("\tIt is scalene");
else
System.out.println("\tIt is not scalene");
System.out.println("Would you like to enter values again? (y/n)" );
String input = answer.next(); //Exception is thrown from here
if (input.equals("y"))
{
System.out.println("ok");
}
else if(!input.equals("y"))
{
System.out.println("Ok, bye.");
break;
}
}
}
}
NoSuchElementException:
Thrown by the nextElement method of an Enumeration to indicate that
there are no more elements in the enumeration.
You're getting this exception because Scanner#next doesn't read the new line character, which is the character when you press enter (\n), so in the next for iteration, you're trying to read it, which causes the exception.
One possible solution is to add answer.nextLine() right after answer.next() in order to swallow this extra \n.
Example of your code:
Iteration (a) | input for scanner | Data for scanner
--------------+-----------------------+-------------------
0 | "Hello" (And enter) | Hello
1 | \n | PROBLEM!
to me it seems that answer.next() does not actually have any value assigned to it
usually int name = answer.next() name is assigned what ever answer is. What i mean is that name cant be assigned a value because answer.next() doesn't have one.
At least this is my understanding. The alternative is the get rid of answer.next and use the other scanner.
actually an edit to this.
a scanner reads from files or the console. You have one scanner already (userInput) the second scanner isn't actually doing anything as well as it being an actual scanner, it doesn't have anything to read.
get rid of answer as a scanner, replace is with an int, String, double and have
int answer = userInput.nextInt();
or
double answer = userInput.nextDouble();
or
String answer = userInput.nextLine();
As you said the code runs for you but doesn't when compiled and executed on an online compiler. The answer scanner is exhausted because it doesn't have any elements.
It's embarrassing but i once got the same error when compiling my code on an online compiler, it turned out i wasn't supplying input beforehand to the input section and was expecting the online compiler to ask for the input.
Since you are using two scanners to get input from console, try using the scanner userInput to take the input from a file instead. (It may vary for different online compilers, but there will be an option to provide input from file)

How do I make Java register a string input with spaces?

Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}

Categories

Resources