Mohammad Fadin
Mohammad Fadin

Reputation: 579

Loop,Repeat Program in Java (Java Beginner question)

I want when the user enter any choice (1,2,3,4) it will show the user (Still under constriction) then he gets back to the program again. how can I do that using if statment or a way other then SWTICH method??

import java.util.Scanner;
public class Tt {

    public static void main(String [] args) {
        Scanner kb= new Scanner (System.in);
        int choice;
        do{
            System.out.println("Please enter your choice from the following menu:");
            System.out.println("1. Enter student tanscript");
            System.out.println("2. Display transcript summary");
            System.out.println("3. Read student transcript from a file");
            System.out.println("4. Write 1transcript summary to a file");
            System.out.println("5. Exit");

            choice = kb.nextInt();

            switch (choice) {

                case 1:
                case 2:
                case 3:
                case 4:
                    System.out.println("Under construction");
                    System.out.println();
                    break;
                case 5:
                    break;

            }
        }while (choice > 0 && choice < 5);

    }


}

Upvotes: 0

Views: 15439

Answers (5)

Tom Wadley
Tom Wadley

Reputation: 121863

if (choice == 1 || choice == 2 || choice == 3 || choice == 4) {
  System.out.println("Under construction");
  System.out.println();
}

or

if (choice >= 1 || choice <= 4) {
  System.out.println("Under construction");
  System.out.println();
}

EDIT: If you want space to implement each option (similar to what your switch statement gives you now), you could write it like this:

if (choice == 1) {
  System.out.println("Under construction");
  System.out.println();
} else if (choice == 2) {
  System.out.println("Under construction");
  System.out.println();
} else if (choice == 3) {
  System.out.println("Under construction");
  System.out.println();
} else if (choice == 4) {
  System.out.println("Under construction");
  System.out.println();
} else {
  System.out.println("Unrecognised selection");
  System.out.println();
}

Upvotes: 2

ICR
ICR

Reputation: 14162

I'm not too sure exactly what you mean by the question. Do you want to allow the user to choose again if they choose an 'under construction' option? In that case I would break it out into a method that can be re-called to show the menu again.

public static void main(String [] args) {
    showMenu();
}

public static void showMenu() {
    Scanner kb = new Scanner (System.in);
    int choice;
    System.out.println("Please enter your choice from the following menu:");
    System.out.println("1. Enter student tanscript");
    System.out.println("2. Display transcript summary");
    System.out.println("3. Read student transcript from a file");
    System.out.println("4. Write 1transcript summary to a file");
    System.out.println("5. Exit");

    choice = kb.nextInt();

    switch (choice) {
        case 1:
        case 2:
        case 3:
        case 4:
            System.out.println("Under construction");
            System.out.println();
            showMenu();
            return;
        case 5:
            return;
        default:
            showMenu();
            return;
    }
}

If you want to remove the lengthy switch statement, you could possibly create a Map<int, MenuAction>, where MenuAction is an interface that has a method DoAction that performs the behavior.

public interface MenuAction {
    void doAction();
}

public UnderConstructionAction implements MenuAction {
    public void doAction() {
        System.out.println("Under construction");
        System.out.println();
    }
}

public ExitAction implements MenuAction {
    public void doAction() {
    }
}

public class MainClass {
    static {
        Map<Integer, MenuAction> menuActions = new HashMap<Integer, MenuAction>();
        menuActions.put(1, new UnderConstructionAction());
        menuActions.put(2, new UnderConstructionAction());
        menuActions.put(3, new UnderConstructionAction());
        menuActions.put(4, new UnderConstructionAction());
        menuActions.put(5, new ExitAction());
    }

    public static void main(String [] args) {
        showMenu();
    }

    public static void showMenu() {
        Scanner kb = new Scanner (System.in);
        int choice;
        System.out.println("Please enter your choice from the following menu:");
        System.out.println("1. Enter student tanscript");
        System.out.println("2. Display transcript summary");
        System.out.println("3. Read student transcript from a file");
        System.out.println("4. Write 1transcript summary to a file");
        System.out.println("5. Exit");

        choice = kb.nextInt();

        if (!menuActions.containsKey(choice)) {
            showMenu();
            return;
        }

        menuActions.get(choice).doAction();
    }
}

You could even go further and create a StudentTranscriptAction, TranscriptSummaryAction etc. that inherits from UnderConstructionAction, but has a Description field and use those to build up the menu output.

Note: I've done little Java, and haven't tested this code at all.

Upvotes: 1

extraneon
extraneon

Reputation: 23950

An alternative to ICR's answer is using the Observer pattern. If a selection is made an event is generated (like when a JButton is pushed), and other objects can subscribe to that event.

You can choose to locally handle the event, like the Java Swing architecture does, or go for a central Event Bus like architecture.

On the one hand, the observer pattern is more easily extensible because you would not have to change the MainClass code at all, on the other hand it might make the code less transparent as all depends on the runtime configuration - which listeners have registered themselves.

Also have a look at the examples at the ultimate site of knowledge, wikipedia :)

An example:

public class Foo extends Observable {

    // The Observers would normally be in their own file
    static class OneHandler implements Observer {
        public void update(Observable o, Object val) {
            if (val != null && val.equals(1)) {
                System.out.println("One pressed");
            }
        }
    }

    static class TwoHandler implements Observer {
        public void update(Observable o, Object val) {
            if (val != null && val.equals(2)) {
                System.out.println("Two pressed");
            }
        }
    }

    static class EverythingHandler implements Observer {
        public void update(Observable o, Object val) {
            if (val != null) {
                System.out.println(val + " pressed");
            } else {
                System.out.println("Null pressed");
            }
        }
    }

    public void askQuestion() {
        // ask the question
        System.out.println("Ask Question");
        setChanged(); // otherwise observers are not notified
        notifyObservers(1); // in this example 1 is pressed (will be autoboxed to Integer)
    }

    public static void main(String[] args) {
        // main and Foo would usually not be in the same class
        Foo foo = new Foo();
        // Register observers.
        // Note that you do not bind OneHandler to 1 here, but that OneHandler
        // itself knows when to react. It could be that more Observables would react 
        // to the same event
        // You would not know the order in which they are called.
        foo.addObserver(new OneHandler());
        foo.addObserver(new TwoHandler());
        foo.addObserver(new EverythingHandler());

        foo.askQuestion();
    }
}

Upvotes: 0

Suroot
Suroot

Reputation: 4423

Instead of switch you could have an array of option executors. When the user hits a number (i.e. 1) it relates to the array element 0 which then gets executed. This allows for more extensibility as you can just create new Executors.

private interface Executor {
  public void run();
}

...
public static void main(String[] str) {
  Executor temp = new Executor() {
    public void run() {
      System.out.println("Under Construction");
    }
  }

  Executor[] ex = {temp, temp, temp, temp};

  while(true) {
    System.out.println("Please enter your choice from the following menu:");
    System.out.println("1. Enter student transcript");
    System.out.println("2. Display transcript summary");
    System.out.println("3. Read student transcript from a file");
    System.out.println("4. Write 1transcript summary to a file");
    System.out.println("5. Exit");

    choice = kb.nextInt();

    if(choice > 0 && choice < ex.length) {
      ex[choice - 1].run();
    } else {
      break;
    }
  }
}

Upvotes: 2

Jason
Jason

Reputation: 674

Maybe pattern matching?

String pattern = "[1234]";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                
input = br.readLine();
    if(input.matches(pattern)) {
   // construction
}

Upvotes: 0

Related Questions