I need to be able to read 3 separate blocks of text from a file and display them including the calculations to the console using a while loop. At the moment I can only get one block of text to display.
I couldn't figure out how to format it on here exactly like it is in the text file so excuse the image.
Text File:
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
FileReader input = new FileReader ("rooms.txt");
Scanner console = new Scanner(System.in);
Scanner read = new Scanner (input);
final double defaultTax = .20;
System.out.println("Do you wish to specify a custom tax rate? (yes/no): ");
if (console.next().equals("yes")) {
System.out.println("What would you like the tax rate to be?");
}
//use while loop
else
{
while (read.hasNextLine()) {
String roomType = read.nextLine();
int rooms = read.nextInt();
double price = read.nextDouble();
double totalIncome = (double) (rooms*price);
double tax = (double) (price*rooms*defaultTax);
System.out.println("Room type: " + roomType + " | No. of rooms: " + rooms + " | Room price: " + price + " | income: " + totalIncome + " | tax: " + tax);
}
}
}
CURRENT OUTPUT: Room type: Single | No. of rooms: 5 | Room price: 23.5 | income: 117.5 | tax: 23.5
The desired output would include all of the data, including the calculations.
Current error message:
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.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at cwk/cwk.test1.main(test1.java:31)
I am literally just a uni student looking for a bit of help on a bit of one module. I'm not a programmer, I'm not doing a programming course. please don't delete my question.
The issue is related to whitespace. When you call nextLine it will read a whole line, until it encounters \n or the end of the file. When you call nextInt and nextDouble it will skip any preceding whitespace, however it will not consume any whitespace after.
So the first iteration of your while loop is working fine. However the next iteration when nextLine is called, then an empty string is returned. After that when nextInt is called, then it encounters "Double" and thus you get an InputMismatchException.
The easiest way to fix this, is that at the end of your while loop, you can skip all subsequent whitespace:
while (read.hasNextLine()) {
// Keep everything you already have
read.skip("\\s+");
}
Related
I want to be able to write in between characters in the console using Scanner. The code Im using:
Scanner sc = new Scanner(System.in);
System.out.print("[customer ID: \t]");
int id = sc.nextInt();
the current output would be:
[customer ID: ]
and if i tried typing in between the brackets this would happen:
[customer ID: ]123
is there any way to make the text appear in between the brackets?
intended output:
[customer ID: 123]
The answer is no. You need to hit the enter key for sc.nextInt() to read the input. Any output would be in the next line and not on the line where you enter the input.
System.out.print("[Customer ID: " + sc.nextInt() + "]";
24
[Customer ID: 524]
The closest I can think of this is something like this:
System.out.print("Customer ID: ");
int id = sc.nextInt();
which produce the output below:
Customer ID: 1234
The answer to the question is no. Once the output is sent to the console (or some other output device) it's a done deal. You cannot retroactively modify the output that has already been consumed and modify it. You have to create a new output and send it to the output device. It is the same as printing a piece of paper and then make a correction directly to the paper from your program once it is printed out.
Alternatively, you can do something like this
Scanner sc = new Scanner(System.in);
System.out.print("Enter your customer ID: ")
int id = sc.nextInt();
System.out.print("[customer ID: " + id + "]");
Unfortunately, it is impossible to do what you asked.
This question already has answers here:
How to keep my user input on the same line after an output?
(4 answers)
Closed 1 year ago.
I am making a console game on codiva.io.. and I would like to put some characters in front of the text of a user's input. Basically, I want to know how to force the user to type in some characters right before they hit enter.
Example code:
import java.util.Scanner;
class test {
public static void main(String[] args) {
System.out.println(" | Welcome to the [...] Game!\n");
Scanner useri = new Scanner(System.in);
String userin = useri.nextLine();
if (userin.equals("devcom")){
System.out.println("\nCommands| Communication with developer channel [ACTIVATED]\n");
Scanner useris = new Scanner(System.in);
String userins = useris.nextLine();
if (userins.matches("^~sg\\h+(\\S+(?:\\h+\\S+)*)$")){
System.out.println("\n>>>>>>>>|");
System.out.println("Commands| Test command successful. Communication to developer channel [DEACTIVATED]");
System.out.println(">>>>>>>>|\n");
}
}
}
}
Output:
For normal console output, I use:
" | "
And for commands I use:
">>>>>>>>| "
"Commands| "
">>>>>>>>| "
My question is, how do I input the normal console output:
" | "
before the text inputted by the user?
For example; where it says "devcom", I inputted devcom, (in photo 1), I want it to say:
" | devcom"
even though the user only types the "devcom" part.
In order to achieve your desired results, you have to put:
System.out.print(" | ");
in front of the line:
String userins = useris.nextLine();
This way, before the console can check for the nextLine, you printed the text you want to be before the userInput. Therefore inputting text before the userInput.
I'm trying to separate the input from the console using the split method, and then putting each of these values into separate containers, and I keep on getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1. I assume the issue is that it ignores the input after the first space, but I am clueless as to why and how to solve that.
Could someone tell me what I'm doing wrong and advise what I should do so that the text after the space is stored in my container? Thank you in advance.
Scanner s = new Scanner(System.in);
System.out.println("Input the name and phone no: ");
String text = s.next();
String[] temp = text.split(" ");
String name = temp[0];
String phoneNoTemp = temp[1];
System.out.println(name + ": name");
System.out.println(phoneNoTemp + ": phoneNoTemp");
The input I tried it with was:
Input the name and phone no:
kate 99912222
Sidenote: Yes, I did import the scanner
Try to use s.nextLine() instead of s.next() because the next() method only consumes until the next delimiter, which defaults to any whitespace.
I want the user to only enter his age. So I did this program :
Scanner keyb = new Scanner(System.in);
int age;
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("How old are you ?");
}
age = keyb.nextInt();
System.out.println("you are" + age + "years old");
I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?
For example I want to prevent this kind of typing "12 m" or "12 12"
Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :
while(keyb.hasNext())
keyb.next();
You want to get the whole line. Use nextLine and check that for digits e.g.
String possibleAge = "";
do {
System.out.println("How old are you ?");
possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))
Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt.
I've also added an initial question, because in your example the first input was taken before asking any questions.
Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;
System.out.println("How old are you?");
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("No really. How old are you?");
}
age = keyb.nextInt();
System.out.println("You are " + age + " years old");
String age = "11";
if (age.matches(".*[^0-9].*")) {
System.out.println("Invalid age");
} else {
System.out.println("valid age");
}
If age contains other then digits then it will print invalid age.
I'm trying to read separate names and instruments up until the total number of bandmembers(asked earlier in the program) is reached. The program reads the amount, and reads the first name. However after that it fails in that it only reads the first name, it does not print any name or instrument after.
The while loop below is the most likely source of the problem:
i = counter
while(i <= bandMembers)
{
System.out.println("What is band member " + i + "'s name?");
kb.nextLine();
String bName = kb.nextLine();
System.out.println("What instrument does " + bName + " play?");
kb.nextLine();
String bNamePlay = kb1.nextLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
This is what it prints if I entered the first name as bName1:
Band Members
--------------
1: bName1 -
2: -
3: -
Any help appreciated, thanks.
Use BufferedReader instead.This will fix your problem.:-
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=counter;
while(i<=bandMembers){
System.out.println("Enter band member "+i+" name:-");
String bName=br.readLine();
System.out.println("What instrument does "+bName+" play?");
String bNamePlay=br.readLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
You should be using
String bName = kb.next();
Under the assumption that you are using a Scanner.
When you call nextLine() it reads the remainder of the same line and does not wait for input.
I don't have enough rep to comment on the issue you're having:
I was using kb.next at first but it read each word separated by a space as the next name. For example I would input "Jimmy loose hands" and it would prompt for Jimmy's instrument correctly, but it would then ask for band member 2's name and "what instrument does loose play?" simultaneously. So it took the second word as the next name.
What you may want to do is remove the "kb.nextLine();" before "String bName = kb.nextLine();"
I don't have an IDE open to confirm it, but that may be the reason that it is taking the second word/string entered as the name.