InputMismatchException: String not recognized - java

I wrote the piece of Java code below. When running it and typing in any value (either one defined, e.g. latte, or any other, e.g. az integer), I get an InputMismatchException.
As far as I could find answers, this exception means that the input type does not match the expected type. What am I missing, why isn't the code recognizing a String input? Thanks for the supprort.
Cheers, Gabor
package Lesson1;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
String order = new String();
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (order.equals(choice.next(espresso))) {
System.out.println("Your order: " + espresso);
} else if (order.equals(choice.next(americano))) {
System.out.println("Your order: " + americano);
} else if (order.equals(choice.next(cappuccino))) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(choice.next(latte))) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Lesson1.Coffee.main(Coffee.java:22)

You write once in default input, but you're trying to read multiple times using choice.next(..).
One solution is assign your choice in a String before the if-else statement and then check it using equalsIgnoreCase.
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
String picked = choice.next();
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (picked.equalsIgnoreCase(espresso)) {
System.out.println("Your order: " + espresso);
} else if (picked.equalsIgnoreCase(americano)) {
System.out.println("Your order: " + americano);
} else if (picked.equalsIgnoreCase(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (picked.equalsIgnoreCase(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}

I think you are using the Scanner wrong. Trying using the next() method with no parameters to get the user input, and only call it once (instead of inside each if else branch). Like this:
package com.company;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
String order = choice.next();
if (order.equals(espresso)) {
System.out.println("Your order: " + espresso);
} else if (order.equals(americano)) {
System.out.println("Your order: " + americano);
} else if (order.equals(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}

Related

Else if not working correctly when scanning file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Coursework2 {
public static void main(String[] args)
throws FileNotFoundException { {
Scanner reader = new Scanner(new FileReader("seats.txt"));
Scanner scan = new Scanner (System.in);
double defaultdiscount = 17.5, discount = 16.97;
boolean random = true;
while (random) {
System.out.println("Please enter your Surname:");
String name = scan.nextLine();
System.out.println("Good morning, Manager " + name + " Would you like to apply a specific discount rate?");
String decision = scan.nextLine();
if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) {
System.out.println("That's great, Mananger " + name + ".");
System.out.println("How much discount would you like? (1-100)");
break;
} else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) {
System.out.println("Alright, " + name + " Here's all the seats without discounts:");
//break;
}
System.out.println("Invalid Input, please try again. Restarting.");
}
discount = scan.nextDouble();
defaultdiscount = discount;
while (reader.hasNext()) {
String table = reader.next();
double price = reader.nextDouble();
int bookings = reader.nextInt();
double newdiscount = (((price/100.00*discount)*bookings));
double newincome = (price*bookings-(((price/100.00*discount)*bookings)));
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
System.out.printf("Discount: £%.2f, Income: £%.2f %n", newdiscount, newincome);
String decision;
do {
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
//decision = scan.nextLine();
decision = scan.next();
}
while (decision.equalsIgnoreCase("No"));
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
}
reader.close();
scan.close();
}
}
}
I understand that the code runs sequentially, but when it comes to trying to run the read files through the else if (No), it can't go above the while reader or inside the else if or it won't see the info from the text file, and when outside, it can't see the variables. I'm just a bit confused. It feels like something might be in the wrong place and I can't wrap my head around it.
I've given this a go, using the correct comparisons, and declaring the string inside of the while. But I'm still getting some errors. I'm thinking maybe setting the string to "null" isn't the correct way of resetting, since I've already declared it has a scan.nextLine previously?
Try doing the if statement like this
while(random){
if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) {
System.out.println("That's great, Mananger " + name + ".");
System.out.println("How much discount would you like? (1-100)");
random = false;
}
else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) {
System.out.println("Alright, " + name + " Here's all the seats without discounts:");
random = false;
}
else
System.out.println("Invalid Input, please try again. Restarting.");
}
You will not loop it if you never change "random" boolean to false. Also, try not using break in this case.
Also, try creating the variable "name" and "decision" outside the loop, as good practice. You should also rename "random" to something like "isBadAnswer"

How to check for and use input from a different methood

I am making a game and a the end of the game I want it to call the user by the name that they put in,, this is the code I have.
private static final Scanner console = new Scanner(System.in);
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation();
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation() {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt();
}
}
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
public static boolean Mascot() {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println("You, have sucsefully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
I want for it to at the end print * user's name*, you have successfully passed the third riddle.
but it needs to be able to weather the first name was kept, or if this sequence was used.
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
and if it has been activated it needs to use the new name.
Change return type of calledIt() to String and return realName from this method
Change return type of confirmation() to String. Initialize a String (String name = null). In the else part, assign the value returned from calledIt() to this string (String name = calledIt()). Return name.
In main, if the value returned from confirmation() is not null, update Name with this new value.
Pass the Name as input to Mascot method. For this, you have to update the Mascot method to accept a String as input.
You can pass the variable into confirmation() and calledIt() like this
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation(Name);
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation(String name) {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt(name);
}
}
public static void calledIt(String realName){
System.out.println("I knew it!");
System.out.print("whats your real name? ");
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
You could do the following change:
public static void main(String[] args) { // follow the prompts.//
System.out.println("Hello user! What is your name? ");
String name = console.nextLine();
System.out.println("Really? " + name + " is too weird to be a real name.");
System.out.print("Is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still don't believe you, so you will have to answer 3 riddles before you can continue to the game");
} else {
System.out.println("I knew it!");
System.out.print("Whats your real name? ");
name = console.nextLine();
System.out.println(
"" + name + " sounds like a real one, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
mascot(name);
System.out.println("Thank you for playing the demo");
console.close();
}
public static boolean mascot(String name) {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println(name + ", you have successfully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}

My while loop in java doesn't work and only completes it one time

It will only go through one time so it will end with "Would you like to make another request?(y/n)"
and when I input "y" it stops there and won't do the loop.
package Chaterp5PPReynaGuerra;
import java.util.*;
public class MeetingRequest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
final int CAPACITY=30;
String name;
int people;
int morePeople;
String answer="y";
int fewerPeople;
System.out.println("--------Meeting Request System"+
"--------");
System.out.println("\nWelcome to the Meeting Request System."+
" May I know your name?");
name=scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
System.out.println("Hello, "+name+", how many people"+
" will be attending the meeting?");
people=scan.nextInt();
morePeople = CAPACITY - people;
if(people < CAPACITY)
System.out.println("You can invite "+morePeople+
" more people to the meeting.");
else if(people > CAPACITY) {
fewerPeople= people - CAPACITY;
System.out.println("Sorry, the room is not "+
"big enough to seat that many people. You have to "+
"exclude "+fewerPeople+" from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another"+
" request?(y /n)");
// gets rid of \n in the input stream
scan.next();
answer=scan.nextLine();
}
}
}
Replace
people=scan.nextInt();
with
people = Integer.parseInt(scan.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Given below is the corrected program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int CAPACITY = 30;
String name;
int people = 0;
int morePeople;
String answer = "y";
int fewerPeople;
boolean valid;
System.out.println("--------Meeting Request System" + "--------");
System.out.println("\nWelcome to the Meeting Request System." + " May I know your name?");
name = scan.nextLine();
do {
do {
valid = true;
System.out.println("Hello, " + name + ", how many people" + " will be attending the meeting?");
try {
people = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid entry. Pleaase try again.");
valid = false;
}
} while (!valid);
morePeople = CAPACITY - people;
if (people < CAPACITY)
System.out.println("You can invite " + morePeople + " more people to the meeting.");
else if (people > CAPACITY) {
fewerPeople = people - CAPACITY;
System.out.println("Sorry, the room is not " + "big enough to seat that many people. You have to "
+ "exclude " + fewerPeople + " from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another" + " request?(y /n)");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
--------Meeting Request System--------
Welcome to the Meeting Request System. May I know your name?
abc
Hello, abc, how many people will be attending the meeting?
x
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
10.4
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
4
You can invite 26 more people to the meeting.
Would you like to make another request?(y /n)
y
Hello, abc, how many people will be attending the meeting?
5
You can invite 25 more people to the meeting.
Would you like to make another request?(y /n)
n
Some other important points:
As you can see, a do...while loop is more appropriate instead of while loop in this case.
You should always check for the NumberFormatException whenever you parse a text (e.g. Scanner::nextLine()) to integer.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
To get rid of the \n use scan.nextLine
// gets rid of \n in the input stream
scan.nextLine();
answer=scan.nextLine();
Hope this help.

Java Lab Project

So I am currently working on a lab for class. I'll attach the lab below:
For this lab, you will use a series of nested if-else or if-else-if statements in order to convert a Roman Numeral number into its String word form. The numerals we are concerned with are I, II, III, IV, V, VI, VII, VIII, which coincide with One, Two, Three, Four, Five, Six, Seven, Eight. Numbers outside of this range are denied – you must tell the user that they are denied as input.
Your code must not fall for inputs like ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’ Those inputs should be denied just like an input outside of I to VIII would be
What are possible ways to avoid falling for fake inputs?
Also, I currently have 8 different if statements, is there a faster way to do this?
import java.util.Scanner;
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
romanNum = keyboard.next();
if (romanNum.equalsIgnoreCase("I")){
System.out.println(romanNum + " represents the number \"One\"");
}
else if (romanNum.equalsIgnoreCase("II")){
System.out.println(romanNum + " represents the number \"Two\"");
}
else if (romanNum.equalsIgnoreCase("III")){
System.out.println(romanNum + " represents the number \"Three\"");
}
else if (romanNum.equalsIgnoreCase("IV")){
System.out.println(romanNum + " represents the number \"Four\"");
}
else if (romanNum.equalsIgnoreCase("V")){
System.out.println(romanNum + " represents the number \"Five\"");
}
else if (romanNum.equalsIgnoreCase("VI")){
System.out.println(romanNum + " represents the number \"Six\"");
}
else if (romanNum.equalsIgnoreCase("VII")){
System.out.println(romanNum + " represents the number \"Seven\"");
}
else if (romanNum.equalsIgnoreCase("VIII")){
System.out.println(romanNum + " represents the number \"Eight\"");
}
else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}
Your code is fine for what you need it to do. There are ways to check for valid entry other than what you have implemented but they may be a bit more involved. Professors tend to become upset (Maybe mines was just a jerk) when student do more than what is required for a coding lab.
In the code shown by #nakano531, there's no way that a "trick input" will work. If it what they input, literally does not match the HashMap, it will prompt them that they have entered an invalid answer. ( Don't have the necessary reputation points to say this under his answer, but I wanted to let you know)
Your code is using
romanNum = keyboard.next();
This will return first word from the given input.But you should use .
romanNum = keyboard.nextLine();
Which will read the entire String provided by the use like the ones( ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’) you mentioned.
i Hope this will help you.
https://stackoverflow.com/help/someone-answers
public class answer {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String a0 = sc.nextLine();
String[]a1 = {"I","II","III","IV","V","VI","VII","VIII"};
String[]a2 = {"One","Two","Three","Four","Five","Six","Seven","Eight"};
for(int i=0;i<a1.length;i++) {
if(a0.equals(a1[i])) {
System.out.println(a0+" represent "+a2[i]);
}
else {
System.out.println("You Type smth wrong");
}
}
}
}
Okay, this is where we are now. The issue is I can't get the JOption windows to pop up after taking the users input.
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
JOptionPane.showInputDialog(null,"Please enter a Roman Numeral between the values 1 and 8: ");
romanNum = keyboard.nextLine();
if (romanNum.charAt(0) == 'I') {
if (romanNum.equalsIgnoreCase("I"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"One\"");
if (romanNum.equalsIgnoreCase("II"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Two\"");
if (romanNum.equalsIgnoreCase("III"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Three\"");
if (romanNum.equalsIgnoreCase("IV"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Four\"");
}
else if (romanNum.charAt(0) == 'V') {
if (romanNum.equalsIgnoreCase("V"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Five\"");
if (romanNum.equalsIgnoreCase("VI"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Six\"");
if (romanNum.equalsIgnoreCase("VII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Seven\"");
if (romanNum.equalsIgnoreCase("VIII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Eight\"");
}
else {
JOptionPane.showMessageDialog(null,"Not in valid range.");
}
}
}
You can reduce the number of if statement by using Map.
import java.util.Scanner;
import java.util.*;
public class RomanNumeralChecker {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String, String>();
m.put("I", "One");
m.put("II", "Two");
m.put("III", "Three");
m.put("IV", "Four");
m.put("V", "Five");
m.put("VI", "Six");
m.put("VII", "Seven");
m.put("VIII", "Eight");
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
Scanner keyboard = new Scanner(System.in);
String romanNum = keyboard.next();
String num = m.get(romanNum);
if (num != null) {
System.out.println(romanNum + " represents the number \"" + num + "\"");
} else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}

First, last and sometime middle name detection Java

I am trying to write a code to give off the user's name in different formats after they enter it. However, if a user does not have a middle name, the system should print that there was an error. I have it so it works perfectly if the user enters three names but does not work if the user enters two names. Here is my code:
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
String fullName;
Scanner in = new Scanner(System.in);
System.out.print ("What are your first, middle, and last names? ");
fullName = in.nextLine();
System.out.println(fullName);
if (fullName.contains(" "))
{
String[] nameParts = fullName.split(" ");
String firstInitial = nameParts[0].substring(0,1).toUpperCase();
String secondInitial = nameParts[1].substring(0,1).toUpperCase();
String thirdInitial = nameParts[2].substring(0,1).toUpperCase();
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
else
{
System.out.println ("Your initials are: " + firstInitial + secondInitial + thirdInitial);
String lastVariationOne = nameParts[2].substring(0, nameParts[2].length());
lastVariationOne = lastVariationOne.toUpperCase();
String firstVariationOne = nameParts[0].substring(0, nameParts[0].length());
firstVariationOne = firstVariationOne.substring(0,1).toUpperCase() + firstVariationOne.substring(1, nameParts[0].length());
System.out.println("Variation One: " + lastVariationOne + ", " + firstVariationOne + " " + secondInitial + ".");
String lastVariationTwo = nameParts[2].substring(0, nameParts[2].length());
lastVariationTwo = lastVariationTwo.substring(0,1).toUpperCase() + lastVariationTwo.substring(1, nameParts[2].length());
System.out.println("Variation Two: " + lastVariationTwo + ", " + firstVariationOne);
}
}
else
{
System.out.println("Wrong. Please enter your name properly.");
}
}
}
Instead of this:
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
something like
if(nameParts.length != 3)
{
System.out.println("Invalid entry");
}
might be preferrable.
Basically, in the case that there are only two names entered, split() will return an array of length 2, whose elements are accessible by indices 0 and 1.
But in your if condition you attempt to access index 2, which could be out of bounds (it would be OOB for the case where you entered only two names).
To resolve this, you could either (a) try it like you do, but catch the ArrayIndexOutOfBoundsException or (b) check first that split produced a properly sized array, then go from there (this was the approach I took with the change I listed).
I'd suggest (b), but both approaches seem fine.
If you don't input middlename, would the array size be 2?
So there is NO namespart[2].
Just check size of namespart.
#jedwards jedwards's solution is there.

Categories

Resources