Input ignores IF statement if default in switch - java

I am doing a project (based on a tutorial). I have a switch statement and for each case, there's a default in case the user input is invalid, and I write on the console "Sorry, I do not understand your request". However, if the user instead of writing whatever, writes "exit", the program should end without that "I don't understand request" sentence showing up.
This is stated in my IF statement in the beginning. What my current project does at the moment when I type "exit" is showing that line and then stopping. I don't understand how the program completely ignores that IF statement in the beginning.
public class MainGame {
public static GameSave gameSave = new GameSave();
public static String user = "";
public static Scanner scanner = new Scanner(System.in);
public static String question;
public static int relationshipPoints;
public static void main(String[] args) {
Random random = new Random();
question = gameSave.loadGame();
// relationshipPoints = gameSave.loadPoints();
RelationshipPoints points = new RelationshipPoints();
System.out.println("\n\t*** TEXT_GAME: FIRSTDATE ***\n");
System.out.println("-You can exit the game at any time by typing 'exit'.-\n\n");
while (true) {
if (user.equalsIgnoreCase("exit")) {
System.exit(1);
break;
} else {
switch (question) {
[...]
case "2":
switch (user = scanner.next()) {
case "1":
System.out.println("\n\nThe guy you met last night was nice. You want to "
+ "get back into contact with him. Why don't you check your phone for a number?");
question = "2A";
gameSave.saveGame("2A");
break;
case "2":
System.out.println("\n\n");
question = "0";
break;
default:
System.out.println("\nI do not understand your request.\n");
question = "2";
break;
}
break;
case "2A": [...]

Try replacing your while(true) {...} with while ((user = scanner.next() != null) { ... }
It looks like you are trying to access the "user" data without first setting it.

user = scanner.nextLine(); insert this line just after entering in while loop. your problem occurs as you are checking user equal to exit but user has nothing so control goes to else portion.

Related

How to come back to menu?

I am trying to create an issue tracking System, but I am having a bit of a problem, every time I run the code, it does not come back to the menu, it just loops. I want my code to come back to the menu whenever i describe my issue.
package com.company.TrackingSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
private void menu() {
boolean is = true;
System.out.println("---Menu---");
System.out.println(
"1.Create new Issue\n" +
"2.Mark Issue as solved\n" +
"3.View unsolved Issues\n" +
"4.View solved Issues\n" +
"5.Exit\n"
);
}
}
My tracking class
package com.company.TrackingSystem;
public class TrackingSystem {
private String createIssue;
private boolean issueSolved;
public TrackingSystem(String createIssue, boolean issueSolved) {
this.createIssue = createIssue;
this.issueSolved = issueSolved;
}
public String getCreateIssue() {
return createIssue;
}
public void setCreateIssue(String createIssue) {
this.createIssue = createIssue;
}
public boolean isIssueSolved() {
return issueSolved;
}
public void setIssueSolved(boolean issueSolved) {
this.issueSolved = issueSolved;
}
}
Example output:
---Menu---
1.Create new Issue
2.Mark Issue as solved
3.View unsolved Issues
4.View solved Issues
5.Exit
Select option >> 1
*** Create an Issue***
Describe your Issue:
*** Create an Issue***
Describe your Issue:
as
*** Create an Issue***
Describe your Issue:
sa
*** Create an Issue***
Describe your Issue:
as
Let's look at this function:
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
Pay special attention to the loop condition: while(is). You declare bool is = true; but you never change it to false inside the loop. This means the loop will continue forever.
To fix this, you have to make some decisions. First, do you really want to continue looping here? Is your intention to allow the user to enter as many issues as they want? Or do you want to create only a single issue then return to the menu. If the former, then you need to figure out how the user will tell the program that they are finished entering issues. You can use this to stop the loop. If the later, then just remove the loop.
Now let's look at main():
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
Even after you solve the problem with your code to create an issue, you will run the program and it will exit after one action. This is because you do not loop in main(). You need to add a loop here that repeats the following steps:
Print the menu.
Get the user's choice.
Perform the action for that choice
Repeat to step 1.
Each of these steps can be a method so that you can keep main() very short. Note how the first 3 steps are inside a loop. I think this is what you were trying to do with the loop for creating a new item, but somehow put the loop in the wrong place. As you can see here, by writing out the steps in words, we get a clear idea of how to organize the code. Doing this is a great tool when writing a computer program.

No Such Element Exception while scanning multiple inputs

I am new to java programming , and i am trying to learn the usage of classes and objects in java programming , while writing the following code i got an exception
java.util.NoSuchElementException
for sample input
5
1 2 3 4 5
here first line contains number of elements (in this case its 5),and next line contains elements.
while taking input inside the for loop in the class Election ,i am getting exception.
I tried searching on stack Overflow, and other resources too,but still can't figure out how to remove this exception.
import java.io.*;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
input.nextLine();
Election obj = new Election(n);
obj.getVotes();
}
}
class Election {
int n,v1,v2,v3,v4,v5,d;
public Election(int n) {
this.n = n;
v1=v2=v3=v4=v5=d=0;
}
public void getVotes() {
Scanner sc = new Scanner(System.in);
for(int i = 0 ; i < 1 ; i++) {
int var = sc.nextInt();
switch(var) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
}
Looks like I'm a bit late, but since your accepted answer is more of comment rather than a solution, I'll post this anyway.
Here is a simple deviation of the code you provided, but reaches the desired result!
I'll walk you through this:
public class MyTest {
public static void main(String[] args) {
//First of all, we need an instance of an Election-type object, so
//that we can call its methods and get votes from users.
Election e = new Election();
//Now we can easily call the method getVotes(), as defined in Election class.
//What happens here, is that the program will 'jump' to the getVotes() method
//and it will execute every line of code in that method. Then it will
//'return' to where it 'left off' in the main() method. Since getVotes()
//is of type 'void', it will not return anything. It will just 'jump' back.
e.getVotes();
//Now, you can use testResult() method, to see the values of the variables.
e.testResult();
}
}
Now, let's take a look at the class Election and how it works.
public class Election {
private final int VOTES_NUM = 1;
private int v1,v2,v3,v4,v5,d;
public Election() {
v1=v2=v3=v4=v5=d=0;
//print now, just to show that all variables = 0
testResult();
}
//Simple method that prints value of each variable. We use this for testing
public void testResult(){
System.out.println("v1 = "+v1);
System.out.println("v2 = "+v2);
System.out.println("v3 = "+v3);
System.out.println("v4 = "+v4);
System.out.println("v5 = "+v5);
System.out.println("d = "+d);
}
private int getInput(){
//First of all, we need a Scanner to take user input.
//You do that in your own code too. We simply move it in this method instead.
Scanner input = new Scanner(System.in);
//You also need variable to hold the user input.
//(Always give meaningful names to all entities)
int userInput;
System.out.print("Please enter vote number here: ");
//the next part has to be in a try-catch block,
//to avoid exceptions like InputMismatchException, etc..
try{
//Get user input
userInput = input.nextInt();
}
//If user enters letter, or symbol, or something else that isn't an integer,
//then inform them of the mistake they made and recursively call this method,
//until they get it right!
catch (InputMismatchException ime){
System.out.println("Please enter only a single number");
return getInput();
}
//If all goes well, return the user input
return userInput;
}
public void getVotes() {
//'VOTES_NUM' is a constant that defines the times the
//loop will iterate (like Macros in 'C')
for(int x=0; x<VOTES_NUM; x++)
int n = getInput();
//then let the switch statement increment one of the variables
switch(userInput) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
I think the code that you posted is missing. The code you posted is working properly and I achieved to get exception only when I wrote input.close() before the obj.getVotes(). When you want to close scanners you should do this after code finishes. Thus, if you close input after the obj.getVotes() you shouldn't get any error.
I tried running your code in a short main class, and I am not getting any exception. This is how I ran your method:
public static void main(String...args){
Election election = new Election(10);
election.getVotes();
System.out.println(election.v1);
System.out.println(election.v2);
System.out.println(election.v3);
System.out.println(election.v4);
System.out.println(election.v5);
System.out.println(election.d);
}
My input was 1 2 3 4 5 6 7 1 2 2 and the console output was:
2 // v1
3 // v2
1 // v3
1 // v4
1 // v5
2 // d
I did make a small change to your program. In the for loop inside the getVotes() method, I changed the condition to i<n (instead of i<1 in your posted code)

How to use String variables as a condition for looping purpose

I was trying to prepare a flow chart of program for my practice where i encounter that following situation is required for me where a user would enter a string value as input either "Yes"or "Y" and "No" or "N" and based on its input the application would either terminate or restart from a certain point till now i have this as an example in my mind
public class ApplicationName {
public static void main(String args[]) {
String restartOperation;
do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equals("No"));
//Rest of code
}
public static void Some_Operation() {
//Executed when called before closing application
}
public static String Confirm_Before_Exit() {
Scanner inputData = new Scanner(System.in);
String answer;
System.out.println("Do you want to perform another operation ?" + " " + "Y" + " " + "N");
answer = inputData.nextLine();
switch (answer) {
case "Y":
case "Yes":
Some_Operation();
break;
default:
System.out.println("Good Bye !");
}
return answer;
}
}
This works till the user has not given input as "No" but obviously it wont work if entered "N" or perhaps small "n" or even "no" but for timing i am only trying for "No" and "N" as input value.
change your do while to the following :
do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equalsIgnoreCase("No") && !restartOperation.equalsIgnoreCase("n"));
I would do something like this. You make your answer lowercase to take into account cases like YEs, NO, etc. You then specify the n and no.The default should be a catch all.
answer = inputData.nextLine().toLowerCase();
switch (answer) {
case "y":
case "yes":
Some_Operation();
break;
case "n":
case "no":
System.out.println("Good Bye !");
break;
default:
System.out.println("Not a valid reponse");
}
You may want to use Regex for text matching (it is contained in the default Java-JDK, not an external library). It is extremely powerful.
You define a needle to search for in Regex-syntax, for example this:
^no?$
It matches text that starts (^) with n and then eventually (?) followed by o (but it does not need to be there), after that the text ends ($). There's also a flag for case insensitive matching /i. You can try Regex at regex101.com. Try this: regex101.com/r/edrehj
Okay, how to use this stuff in Java? Fairly easy:
String input = ...
Pattern pattern = Pattern.compile("^no?$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
// User want's to cancel
...
} else {
// User want's to continue
...
}
More info at Wikipedia#Regex, Java-API#Pattern and Java-API#Matcher.
You can also put this inside an own method, makes the usage more easy and user friendly to read:
private boolean doesUserWantToCancel(final String textInput) {
Pattern pattern = Pattern.compile("^no?$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(textInput);
return matcher.find();
}
You then just call the method for your input:
...
} while (!doesUserWantToCancel(restartOperation));
...
If I am understanding your question correctly you want to run Confirm_Before_Exit() when you are restarting an operation?
Here is what I would do. Instead of having string restartOperation you should have boolean restartOperation. This way you either deal with true or false.
In the Confirm_Before_Exit() function I would still add the .toLowerCase() to your inputData to take into account weird cases. I added two booleans answer and inValidAnswer.
You want your answer to be true if you want to perform another operation. If it is false it will exit.
If the user mistypes, inValideAnswer will be set to true and they will get an error saying invalid answer and will get reprompted.
public class ApplicationName {
public static void main(String args[]) {
boolean restartOperation;
do {
restartOperation = Confirm_Before_Exit();
} while (restartOperation);
//Rest of code
}
public static void Some_Operation() {
//Executed when called before closing application
}
public static boolean Confirm_Before_Exit() {
Scanner inputData = new Scanner(System.in);
boolean answer;
boolean validAnswer;
while(inValideAnswer){
System.out.println("Do you want to perform another operation ?" + " " + "Y" + " " + "N");
string userInput = inputData.nextLine().toLowerCase();
switch (userInput) {
case "y":
case "yes":
Some_Operation();
answer = true;
inValideAnswer = false;
break;
case "n":
case "no":
answer = false;
inValideAnswer = false;
System.out.println("Good Bye !");
break;
default:
System.out.println("Not a valid reponse");
inValideAnswer = true;
}
}
return answer;
}
}

java using NetBeans IDE 8.0.2

I am having trouble clearing the following error '(' or '[' expected on the second line of case 2 and case 3. The code I have written is newAnimal.displayInfo();
I am not sure why I get this error on case 2 and 3 but not case 1. Not sure what I am doing wrong. Any assistance/guidance will be appreciated.
Here is what the code looks like:
package animalinfo;
import java.util.Scanner;
public class AnimalInfo
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner input = new Scanner (System.in);
Animal newAnimal;
int quit = 4;
while(-4 != quit);
{
System.out.println("\n1) Camel" +
"\n2)Penguin" +
"\n3) Tortoise" +
"\n4) Exit Program.");
System.out.print("Please select an amimalfrom the list.");
int choice = input.nextInt();
switch (choice)
{
case 1:
newAnimal = new Camel();
newAnimal.displayInfo();
break;
case 2:
newAnimal = new Penguin
newAnimal.displayInfo();
break;
case 3:
newAnimal = new Tortoise
newAnimal.displayInfo();
break;
case 4:
System.out.println ("Thank you for making your selections.");
break;
}
}
}
}
It seems like you're missing parentheses after creating the new objects. So this:
newAnimal = new Penguin
should become this:
newAnimal = new Penguin();
This is because you're setting newAnimal to a new instance of a Penguin object, and to create that new instance you must call the constructor of the Penguin class to create the object.
Also, as Jurko stated, your while loop is set up incorrectly.
while(-4 != quit);
You must remove the semicolon, otherwise the loop will indefinitely run without executing the code you have underneath it. The correct syntax for a while loop is
while (-4 != quit) {
// Code to repeat here
}
while(-4 != quit);
Get rid of the semicolon, should just be
while (-4 != quit)
{
/*Code here*/
}
and yes, when you have new Penguin and new Tortoise, you are missing the parentheses and semicolon

Issue with multiple uses of Scanner.nextLine();

So, I have some code which, when simplified, is this:
import java.util.scanner
private Scanner input;
int enterInteger()
{
System.out.println("Enter the quantity");
return input.nextInt();
}
String enterString()
{
return input.nextLine();
}
void main()
{
System.out.println("Enter option: 1) Add Quantity\n2)Edit Item");
String input = enterString();
switch (input)
{
case "1":
enterInteger();
break;
case "2":
//Do whatever
break;
default:
System.out.println("Invalid!");
main();
break;
}
}
So, whenever the user enters the option as 1, it loads enterInteger() that asked the user, and returns, an integer.
However, when this happens, and the user enters the integer and presses enter, the code then begins executing the default: case. When I add a breakpoint the value of option is "", so that's obviously why the default: executes, but I can't see how to prevent it.
I know it's something dumb, so thank you.
I don't know the reason yet, But in the past I had to work with only nextLine() and parse with Integer.parseInt() when necessary.
By the way, You haven't initialized the Scanner.
Scanner input = new Scanner(System.in);

Categories