java: Scanner asks for an extra value when using useDelimiter - java

So I wanna create this program that stores 4 values. the first one being string and the remaining 3 being integers. However, when i enter 4 values and press enter, i get an error java.util.InputMismatchException but when I enter 5 values, i get the result for my for values. for example lets say i input the following values:
Japan,1,2,3
I will get the java.util.InputMismatchException error. And if I enter the following values:-
Japan,1,2,3,4
I get the output as I want:-
Japan,1,2,3
Why is this happening? Here is my code
public class satisfaction {
public static void main(String args[])
{
Scanner src= new Scanner(System.in);
src.useDelimiter("\\,|\\n");
String name=src.next();
int a=src.nextInt();
int b=src.nextInt();
int c=src.nextInt();
System.out.println(name+","+a+","+b+","+c);
}
}

I've tested this a bit myself, and I think the \n in the pattern is not matching the line ending used by your console.
For me, I had to use \r\n instead, but you could also use System.lineSeparator() e.g. like this:
src.useDelimiter(",|" + System.lineSeparator());

The way it's written, it needs another comma at the end of the input. I would recommend checking the string to make sure it ends in a comma, and if not, append one.
I believe that if you enter Japan,1,2,3, it will give you the output you want.

Related

How do I make a program insert a new line every time it finds a space (or whitespace) within a string (in java)?

I'm a first year IT student and we recently had an activity that asks the programmer to create a program that will accept a sentence or a phrase, then detect if there is a space in that string and add a newline in between words that have a space after it.
For clarification, here's what the prompt should look like:
Enter a sentence or phrase: I am a student
then the output would be:
I
am
a
student
I tried to actually finish the code, but I was hit by a roadblock and got stuck. Here's my attempt though:
import java.util.*;
public class NumTwo{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
String phr;
System.out.print("Enter a phrase: ");
phr = in.nextLine();
if(phr.contains(" ")){
System.out.print(phr + "\n");
}
else{
}
}
}
any comments to what i might have done wrong will be very much appreciated
EDIT:
I tried using sir Christoph Dahlen's solution which was to use String.replace, and it worked! Thank you very much.
You are currently checking weither the input line contains any spaces at all, but you have to react to every space instead.
One way would be to split phr by spaces and concatenating it with newlines.
String result = String.join(System.lineSeparator(), phr.split(" "))

Is it possible to read a String and Numbers if they're on the same line (From a TXT file)

I had a hard time wording the title of my question.
In my given assignment I need to write a program to read from a text file.
For example:
(This is in the textfile, the numbers being the price of the item.)
Cappuccino, 3.50
Espresso, 2.10
Mochaccino, 5.99
Irish Coffee, 7.99
Caffe Americano, 6.40
Latte, 1.99
This is my code to read the text file:
public void readFile(){
while(x.hasNext()){
String item = x.next();
Double price = x.nextDouble();
System.out.printf("%s $%.2f \n", item, price);
}//end of whileLoop
}
public void closeFile(){
x.close();
}
My Output:
Cappuccino, $3.50
Espresso, $2.10
Mochaccino, $5.99
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at ReadTextFile.readFile(MiniProject.java:22)
at MiniProject.main(MiniProject.java:400)
The code works well, and expected until it reaches a menu item with two words, rather than a singular word.
How could I change my code to read both words before reading the price?
Here is a video of how I'd like my program to be able to read the file -
https://youtu.be/gIMxwKc-pw8
The Scanner class will read 'tokens'. When you call nextDouble, it will read a token without caring if it is a double or a string or whatnot, and will then attempt to convert it to a double. If that works, that's what you get. If it doesn't, you get an InputMismatchException.
So, what you want to accomplish here is that Irish Coffee is a single token (or possibly that your code is updated to keep reading tokens and concatenate them, that sounds more complicated). Furthermore, that comma is in your strings, and I bet you didn't want that.
Scanner works by separating tokens using a delimiter. Out of the box, the delimiter is 'any amount of whitespace' (so, spaces and newlines).
It sounds like what you need here is to redefine the delimiter: It is either a comma surrounded by any amount of whitespace, OR a newline:
scanner.useDelimiter("(\\s*,\\s*)|\r?\n");
would do the job. That gobbledygook in the middle is a regex. This one reads: EITHER [a] Any amount of whitespace, then a comma, then any amount of whitespace, OR [b] a newline.
Because the item name can be more than one word, I recommend using a method called split(). This will split the line based on a certain string and return an array of the parts of the string split on the value you gave the method. For example, "I do, a".split(", ") will split on a comma followed by a space and return the array ["I do", "a"]. In your example, the string that you would perform this operation on would be obtained by using scan.nextLine(). Then you have the first portion and the second portion that you are interested in. To convert the second element of the array to a double, you can use Double.parseDouble(arr[1]).
This code would work:
public void readFile(){
while(x.hasNextLine()){
String[] nextLineArr = x.nextLine().split(", ");
String item = nextLineArr[0];
double price = Double.parseDouble(nextLineArr[1]);
System.out.printf("%s $%.2f %n", item, price);
}//end of whileLoop
}

Reading lines of input from user using SCANNER

I have a program that needs to read lines of input. It needs to be many lines at once. For example:
As I enter my time machine or
maybe not,
I wonder whether free will exists?
I wonder whether free will exists
maybe not
as I enter my time machine or.
That all gets entered at one time by the user. I was trying to use .hasNextLine() method from Scanner class, but it is not returning false.... it waits for input again. Ive been looking around for a solution and it appears that .hasNextLine() waits for input, but i do not know what alternative to use. Any suggestions? The actual code looks like:
while(input.hasNextLine());
{
line += input.nextLine();
}
Thanks for your help
Perhaps you should use some sort of "stop" sequence meaning when the user enters a particular character sequence, it will break out the loop. It might look something like:
public static void main(String args[]){
final String stopSequence = "/stop";
final Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
while(!input.equalsIgnoreCase(stopSequence)){
//process input
input = reader.nextLine();
}
}

Java is skipping a line (Strings in a Scanner ??) [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am learning Java, and I'm not very far into it, and I don't know why but Java seemed to skip a line. I don't think the code from all my pages is really neccesery so I will just put the first page and the result I get when using it. Thanks!
import java.util.Scanner;
public class First {
public static void main(String args[]){
Scanner scanz = new Scanner(System.in);
System.out.println("Hello, please tell me your birthday!");
System.out.print("Day: ");
int dayz = scanz.nextInt();
System.out.print("Month: ");
int monthz = scanz.nextInt();
System.out.print("Year: ");
int yearz = scanz.nextInt();
System.out.println("Now, tell me your name!");
System.out.print("Name: ");
String namez = scanz.nextLine();
Time timeObject = new Time(dayz,monthz,yearz);
Second secondObject = new Second(namez,timeObject);
System.out.println("\n\n\n\n\n" + secondObject);
}
}
It skips the line
String namez = scanz.nextLine();
Console output: (excuse the birthday bit, it is other stuff)
Hello, please tell me your birthday!
Day: 34
Month: 234
Year: 43
Now, tell me your name!
Name:
My name is and my birthday is 00/00/43
It doesn't give you a chance to give a name, it just skips straight past and takes the name as null. Please, if anyone could, tell me why! I want to learn Java, and this little annoyance is standing in my way.
Thanks!
The problem is that the nextLine gets any characters on the line, and the \n (newline character) is left over from the scanner inputs above.
So instead of letting you enter something new, it takes the \n as the input and continues.
To fix, just put two scanners back to back like this:
System.out.print("Name: ");
scanz.nextLine();
String namez = scanz.nextLine();
Just using:
String namez = scanz.next();
will work too, but will limit the names to be one word. (aka first name only)
I believe the intended use of nextLine is correct. The problem however is that nextInt does not create a newline token, and it's instead reading the rest of that line (which is empty). I believe that if another nextLine statement would be added after that, the code would work. Next on the other hand only recognizes the first word so that might not be the correct solution.

How to stop reading multiple lines from stdin using Scanner?

I'm working on an JAVA assignment should process multiple lines of input. The instructions read "Input is read from stdin."
An example of sample input is given:
one 1
two 2
three 3
I don't understand what the above sample input "read from stdin" means.
Here's a test program I wrote that isolates my confusion:
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
while(stdin.hasNextLine())
{
String line = stdin.nextLine();
String[] tokens = line.split(" ");
System.out.println(Integer.parseInt(tokens[1]));
}
}
When I run this program in the console, it waits for my input and each time I input a line it echos it back as I would expect. So I thought perhaps the sample input above would be achieved by entering each of the 3 lines in this fashion. However, there seems to be no way to end the process. After I enter the 3 lines, how do I terminate the input? I tried just pressing enter twice, but that seems to read as a line consisting of only the newline character, which causes an error because the line doesn't fit the 2 token format it expects.
Here's what the console interaction looks like:
javac Test.java
java Test
one 1
1
two 2
2
three 3
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Test.main(Test.java:13)
I'd appreciate any help in pointing out the gap in my understanding.
You could try asking for empty inputs
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
String line;
Scanner stdin = new Scanner(System.in);
while(stdin.hasNextLine() && !( line = stdin.nextLine() ).equals( "" ))
{
String[] tokens = line.split(" ");
System.out.println(Integer.parseInt(tokens[1]));
}
stdin.close();
}
}
Your code is almost completed. All that you have to do is to exit the while loop. In this code sample I added a condition to it that first sets the read input value to line and secondly checks the returned String if it is empty; if so the second condition of the while loop returns false and let it stop.
The array index out of bounds exception you will only get when you're not entering a minimum of two values, delimitted by whitespace. If you wouldn't try to get the second value >token[1]< by a static index you could avoid this error.
When you're using readers, keep in mind to close after using them.
Last but not least - have you tried the usual Ctrl+C hotkey to terminate processes in consoles?
Good luck!
You could also put your values in a file e.g. input.txt and do:
java Test < input.txt
From the shell, hit Ctrl-D and it will close stdin. Alternatively, pipe input in
cat your-input-file | java Test
To stop the input, you could either prompt the user to enter quit to exit, and then test for the presence of that String in the input, exiting the loop when found, or you could use a counter in the loop, exiting the loop when the maximum iterations have been reached. The break statement will get you out of the loop.

Categories