How to come back to menu? - java

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.

Related

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)

Input ignores IF statement if default in switch

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.

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

java return to specific point in program

I have the next question. I have the program which has the structure:
loadContext();
showCategories(input);
showProjects(input);
showdetails();
On each step me as a user has the ability to jump to previous step. For example I press 0 and program returns to previos step. Press 1 - program starts from the very beginning. Is there any instruments in Java to come to specific point?
EDIT:
I have here the console application. Main method looks like:
loadContext();//Loads categories
showCategories(input);//shows available categories and ask for which category to show
showProjects(input);// shows all projects inside selested category and select which project to show in details
showdetails();//show selected project
Now I want to set option. For example, in showProjects(input) put 0 and see again categories, select it and see category. In showdetails() select 0 and get back to show categories, select one and so on.
You can do something like this:
Wrap all your four methods in another method:
private void programStart(){
loadContext();
showCategories(input);
showProjects(input);
showdetails();
}
Then have a method like this:
private void processUserInput(int selOption) {
if(selOption == 0){
showCategories();
}
else if(selOption == 1){
programStart();
}
else{
System.out.println("Unsupported option");
}
}
At end of each of your methods where you want to have this option available:
a. Read option from users
b. Call processUserInput(input) with input
What about a switch statement inside a while-loop? Gives the user the ability to select the step to jump to. This is the instrument for any language, and not just Java, to get to any specific point.
I have used java.util.Scanner since you want it to be a console application, although in 2015 we tend to rather use graphical user interfaces or Web pages in order to do the job:
import java.util.Scanner;
public class BackNForth {
private static int input;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("select: ");
int sel = Integer.parseInt(s.nextLine());
while (sel >= 1 && sel <= 4) {
switch (sel) {
case 1:
loadContext();
break;
case 2:
System.out.print("Cat input: ");
input = Integer.parseInt(s.nextLine());
showCategories(input);
break;
case 3:
System.out.print("Pro input: ");
input = Integer.parseInt(s.nextLine());
showProjects(input);
break;
case 4:
showdetails();
break;
}
System.out.print("select: ");
sel = Integer.parseInt(s.nextLine());
}
}
private static void loadContext() {
System.out.println("loadContext");
}
private static void showCategories(int input) {
System.out.println("showCategories " + input);
}
private static void showProjects(int input) {
System.out.println("showProjects " + input);
}
private static void showdetails() {
System.out.println("showdetails");
}
}

Strange Bug with User Input and Switch Statement

public class VoteTUIView {
VoteMachine voteMachine;
public VoteTUIView(VoteMachine voteMachine) {
this.voteMachine = voteMachine;
this.start();
}
public static String errorMissingVariable = "This command needs an variable";
public static String errorPartyNoneExistant = "This party does not exist";
public static String errorAddImpossible = "You can't add something to that";
public static String help = "Seriously? You need help? You look like a smart boy/girl, you can figure this out yourself. I believe in you! ";
public void start(){
System.out.println("Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP) ");
Scanner inputScanner = new Scanner(System.in);
while(inputScanner.hasNextLine()){
String inputCommand = inputScanner.next();
switch (inputCommand){
case "VOTE": {
if(inputScanner.hasNext()){
String inputCommand2 = inputScanner.next();
if(voteMachine.getParties().getParties().contains(inputCommand2)){
voteMachine.vote(inputCommand2);
}
else{
System.out.println(errorPartyNoneExistant);
}
}
else{
System.out.println(errorMissingVariable);
}
}
case "ADD": {
if(inputScanner.next().equals("PARTY")) {
if(inputScanner.hasNext()) {
voteMachine.addParty(inputScanner.next());
}
else{
System.out.println(errorMissingVariable);
}
}
else {
showError(errorAddImpossible);
}
}
case "VOTES": {
showVotes(voteMachine.getVotes().getVoteList());
}
case "PARTIES": {
showParties(voteMachine.getParties().getParties());
}
case "EXIT": {
break;
}
case "HELP": {
System.out.println(help);
}
default: {
}
}
System.out.println("\nPlease insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP) ");
}
}
public void showVotes(Map<String, Integer> voteList) {
int i = 1;
for(String partyName : voteList.keySet()){
System.out.println(i+": "+partyName+" has obtained "+voteList.get(partyName)+" votes.");
i++;
}
}
private void showParties(List<String> partyList) {
int i = 1;
for(String partyName : partyList){
System.out.println(i+": "+partyName);
i++;
}
}
private void showError(String error) {
System.out.println("Error: " + error);
}
}
I am fighting with a strange bug. The program reads the user input and determines which action to take with a switch but often, multiple cases in the switch are triggered when they clearly shouldn't be. It's driving me mad. Does anybody know why it does that?
Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP)
ADD PARTY DemoCant's
1: DemoCant's
Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP)
ADD PARTY RepublicRats
1: DemoCant's
2: RepublicRats
Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP)
VOTE DemoCant's
VOTE DemoCant's
Error: You can't add something to that
1: DemoCant's has obtained 1 votes.
1: DemoCant's
2: RepublicRats
You're missing break statements on almost all switch cases so the code just falls though to the next case. See the section on fall though in the docs
case "VOTE": {
....
break;
}
.....
The cases in a switch statement fall through, and continue executing the next case. If you don't want your case to fall through, add a break; statement and the end of the case. E.g.:
switch (inputCommand){
case "VOTE":
// code for voting
break;
case "ADD": {
// code for adding
break;
// etc...
I am fighting with a strange bug.
Which is why you would have used your debugger before asking a question.
The program reads the user input and determines which action to take with a switch but often, multiple cases in the switch are triggered when they clearly shouldn't be.
since there is no break; or return; there is no reason to break out of the switch.
Note: Java, C, C++, C# all do this.
It's driving me mad. Does anybody know why it does that?
Because that is what it is supposed to do.
You are missing break statement. Without a break statement it is an expected behavior.
You can do more reading about this here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
add the break statement after each Case
If you don't add a break statement the code flow will go into the next case until all the case ends or till a break is encountered

Categories