java return to specific point in program - java

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");
}
}

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)

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.

What is the format of calling a method from another class?

If I would like to call a method from another class to input it into the current class that I am working on, how do I format it to call the method? How is the code written to call for the method. Currently I have my floats array that is a method? written in another class and I would like to call for the function to be inputed into the class that I am working on. I honestly don't mean to sound ignorant but I am having hard tie trying to grasp how java works. Thanks.
This is what i put. The float array and the name = the name of the class? I am pretty sure it is incorrect because I am getting an error that myPickNumbers cannot be resolved.
float[] myFloats = myPickNumbers.pickNumbers();
I am trying to take this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class pickNumbers {
Scanner readInput = new Scanner(System.in);
float [] pickNumbers(int choice){
float []myFloats = new float[2];
do { //do loop will continue until user enters correct response
System.out.print("Please enter 2 numbers separated by a space in the formats of floats: "); //will prompt user to enter 2 floats
try {
myFloats[0] = readInput.nextFloat(); //will read first float entered
myFloats[1] = readInput.nextFloat(); //will read second float entered
if (choice == 4 && myFloats[1] == 0.0f) {
System.out.println("Cannot complete calculation. Cannot divide by 0, please try again.");
myFloats[0] = myFloats[1] = 0.0f;
continue;
}
break;
} catch (final InputMismatchException e) {
System.out.println("You have entered an invalid input. Try again.");
readInput.nextLine(); // discard input that is not a float
continue; // loop will continue until the correct answer is found
}
} while (true);
return myFloats;
}
}
And put it into this:
public class Calculator {
public static void main(String[] args) {
String inputOperation;
String operatingWord[] = { "adding", "subtracting",
"multiplying", "dividing" };
//array of operations to display to user
Selection mySelection = new Selection();
String menu = "Welcome to John Doe's Calculator" //next line print out line for welcome
+ "\n 1. Addition"//next line option 1 for addition
+ "\n 2. Subtraction" //next line option 2 for subtraction
+ "\n 3. Multiplication" //next line option 3 for multiplication
+ "\n 4. Division" //next line option 4 for division
+ "\n 5. Exit\n"
+ "====================================\n\n"; //next line option 5 for exit then leave a blank line
Symbol.newSymbol(menu);
Symbol.displaySymbol();
while (!(inputOperation = mySelection.selectionOne()).equals("5"))
Symbol.newSymbol("\n");
Symbol.displaySymbol();
float[] myFloats = myPickNumbers.pickNumbers();
You are trying to use a variable, myPickNumbers that you neither declare nor initialize. You must first declare it and initialize it before you can use it:
pickNumbers myPickNumbers = new pickNumbers();
You should first declare a new pickNumbers object
pickNumbers myPickNumbers = new pickNumbers();
Then you can call the pickNumbers() method but you have to include a parameter of type int e.g
float[] myFloats = myPickNumbers.pickNumbers(5)

Printing different sentences depending on user input

I am wondering how to print a particular sentence depending on user input.
In the scenario below, if the user enters "B" I would like to print the words "You have selected B" however if the user selects C I would like to print the word "You have selected C".
import java.util.Scanner;
public class Trial extends Register
{
//I want to load the register which will be option B
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter A to make a purchase & receive your change");
System.out.println("Enter B to load the Register");
System.out.println("Enter C to write the contents of the Register to a
web Page");
System.out.println("Enter D to exit the program");
}
How about:
String input = // read input from scanner;
if(input.length() == 1) {
switch(input.charAt(0)) {
case 'A':
// make purchase
break;
case 'B':
// load register
break;
// Similarly case C and D
default:
// possibly invalid input as well
}
} else {
System.out.println("Invalid input");
}
If you are using Java 7+, you can use a switch statement.
If you use an earlier vrsion, you need to use several if statements.
As for the Scanner, you can read this tutorial to get started and have a look at this example.

Categories