This is for coursework. I've built the whole program, and it does everything right, apart from this one thing.
I have a class called 'Schedule' this method is at the very end of schedule:
public void bookSeatMenu()
{ boolean leaveBookSeatMenu = false;
String seatBookingMenuStr;
int seatBookingMenuInt = 14;
boolean isInteger = false;
Scanner input = new Scanner(System.in);
System.out.println("Press 1 to add an individual booking, 2 to cancel a booked seat or 3 to go back");
seatBookingMenuStr = input.nextLine();
try {
seatBookingMenuInt = Integer.parseInt(seatBookingMenuStr);
isInteger = true;
}
catch (NumberFormatException e) {
}
switch (seatBookingMenuInt) {
case 1:
bookSeat();
break;
case 2:
cancelSeat();
break;
case 3:
leaveBookSeatMenu = true;
break;
default:
System.out.println("Invalid Choice");
} while (leaveBookSeatMenu == false);
}
I know you all know what a switch menu looks like, but I thought I'd throw it in there anyway, in case (pardon the pun) I'm going wrong here.
Moving on, I have the bookSeat method, this is where the user books a seat (which works fine). Then afterwards it displays the bookSeatMenu() just it displays the menu. But then it won't go back to the previous one.
public void bookSeat()
{
Scanner input = new Scanner(System.in);
boolean isSeatBooked = true;
showSeatPlan();
int seatNum = 0;
int rowNum = 90;
int columnNum = 16;
boolean isInt = false;
while (isSeatBooked == true)
{
System.out.println("Please pick column of a seat to book");
columnNum = input.nextInt();
System.out.println("Please pick row of a seat to book");
rowNum = input.nextInt();
seatNum = (columnNum + ((rowNum) * 15));
if (seats[seatNum] == false)
{
isSeatBooked = false;
}
else
{
System.out.println("This seat is already booked");
}
}
seats[seatNum] = true;
System.out.println("");
bookSeatMenu();
}
Now not for love nor money am I able to get it to go back to the previous menu after it's booked a seat.
Basically the process is:
Book a seat --> go to bookSeatMenu --> press 4 to go back --> Arrive at previous menu.
If I don't book a seat, the program will happily go back to the menu before hand, but after, it just keeps on going on to a new line in the command prompt, not doing anything else, no error etc.
I'm pretty tempted to say this might be a problem with BlueJ, although a bad workman blames his tools, and I don't wanna be 'that guy'
I also need to make a 'testing class' - having never used a 'testing class' before, and the assignment asking us to look in the 'textbook' which noone bothered to buy, I actually have no idea!
There's no switch...while so I assume your problem is as soon you do choose 3, you end up in while(true); which is an infinite loop.
correct pseudo-code:
do {
// read System.in
// handle menu options with your switch
} while(...)
By the way, design is bad IMHO, you should try to think about your model (in your case I would see something like Room, Seat, Scheduler, Menu) and make those object interact with each others :
public class Room {
private Seat[][] seats;
public String toString() {
// like showSeatPlan() using toString() of Seat
}
}
public class Seat {
private int row, column;
private boolean isBooked;
public void book() { /* ... */ }
public void cancel() { /* ... */ }
public String toString() { /* "X" or " " */ }
}
public final class Scheduler {
// "main class" with a "main" method
}
public class Menu {
private Room room;
public String toString() {
// print out menu
}
public void bookSeat() { /* ... */ }
public void cancelSeat() { /* ... */ }
}
(something like that)
For the test part, each class have a test class and each method have a test method, as an example, for Seat:
public class Seat {
public void book() {
if (this.isBooled) {
throw new CannotBookException("seats is taken!");
}
this.isBooled = true;
}
}
public class SeatTest {
#Test // when I book a seat, it's markedas booked.
public void testBook() {
final Seat seat = new Seat();
seat.book();
assertTrue(seat.isBooked)
}
#Test(expected = CannotBookException.class) // when I book an already booked seat, I get an exception.
public void testBookAlreadBooked() {
final Seat seat = new Seat();
// book the seat
seat.book();
assertTrue(seat.isBooked)
// try to book again
seat.book();
}
}
Related
I have methods with which I get data from a database.
Depending on the variable that the user entered through the console, I must execute the desired method
while (flag) {
try {
sw = new ScannerWrapper();
menuHeader();
int choice = sw.readInt();
switch (choice) {
case 1:
System.out.println("Input first name: ");
String name = sw.readLine().toUpperCase();
printResults(DataParser.getFilmByName(name));
break;
case 0:
System.out.println("Bye-bye. Come again");
flag = false;
break;
default:
System.out.println("Please enter correct number");
}
} catch (Exception e) {
System.out.println("Enter correct data");
} finally {
DBConnector.getInstance().closeConnection();
}
}
This code is very bad.There are more than 5 cases with methods and the code becomes redundant
You should have a look at the Strategy design pattern. That will allow you to abstract the logic related to an action.
On top of that, you want to replace the switch to find the right strategy according to the input variable. That is the job of the Factory design pattern, which in your case would return one of the different strategies according to the database value.
Basically:
interface UserAction {
public void execute();
}
class ListMovies implements UserAction {
public void execute() {
// List the movies
}
}
class ExitProgram implements UserAction {
public void execute() {
// Kill kenny
}
}
class Noop implements UserAction {
public void execute() {
// Do nothing
}
}
And a factory:
class UserActionFactory {
public UserAction make(int actionId) {
switch (actionId) {
0: return new ListMovies();
1: return new ExitProgram();
default: return new Noop();
}
}
}
Which then allows:
UserActionFactory factory = new UserActionFactory();
ScannerWrapper sw = new ScannerWrapper();
while (true) {
menuHeader();
int choice = sw.readInt();
UserAction action = factory.make(choice);
action.execute();
}
This could also be the Command design pattern, depends on how you name things and instantiate objects for the rest of the classes.
I'm creating a java desktop application that deals with students' absence in a school, so i'm adding and modifying absences that are made by a single or a group of students.
I've created a Student class and within it i have an Arraylist which holds the objects of absences made by that student.
An Absence object represents a day missed by a student, this absence can be either justified or unjustified(here is the modifying part i mentioned earlier)
Student class
public class Student implements Serializable{
private String cef,nom,prenom,filliere;
private int nbHR_Justifie,nbHR_NonJustifie,nbRetards;//count of justified and unjustified days of absence and count of days that a student came late
private ArrayList<Absence> listDesAbsence;
private ArrayList<Retard> listDesRetard;
public boolean addAbsence(Absence abs){
try{
this.listDesAbsence.add(abs);
if(abs.isJustified()){
setNbHR_J(getNbHR_Justifie()+1);
}else
setNbHR_NonJustifie(getNbHR_NonJustifie()+1);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
public boolean addRetard(Retard ret){//add a "student came late" object
try{
this.listDesRetard.add(ret);
this.setNbRetard(this.getNbRetard()+1);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
Absence class is nothing special :constructor and getters and setters
This is the Main JFrame with a JTable (https://i.imgur.com/2OovLCM.png) in which the user should select one or more students to add to them absences or modify the nature of absences from justified to unjustified or the opposite
public class Main extends javax.swing.JFrame {
private DbConnection db;
int[] numRows=jTable1.getSelectedRows();
if(numRows.length==0){
JOptionPane.showMessageDialog(new JPanel(), "you have to select at least one student");
}else{
String [] tabCEF=new String[numRows.length];
for(int i=0;i<numRows.length;i++){
tabCEF[i]=(String) jTable1.getModel().getValueAt(numRows[i], 0);
}
RetardRegulator ar=new RetardRegulator();
ar.setTabCEF(tabCEF);
ar.setVisible(true);
Now this is a class i'm calling AbsenceRegulator which extends a JFrame and should add or modify absence made by a single or a group of students that are selected in a jTable in the Main JFrame
public class AbsenceRegulator extends javax.swing.JDialog {
DbConnection db;
private String[] tabCEF;
public AbsenceRegulator() {
initComponents();
db=new DbConnection();
}
public void setTabCEF(String[] tab){
tabCEF=tab;
}
private void jLabel4MousePressed(java.awt.event.MouseEvent evt) {
boolean justified;
Absence abs;
Student s;
if(jRadioButton_NO.isSelected()){
justified=false;
}else{
justified=true;
}
if(jDateChooser1.getCalendar()!=null){
GregorianCalendar gc=(GregorianCalendar) jDateChooser1.getCalendar();
abs=new Absence(gc,jTextArea1.getText(),justified);
for(int i=0;i<tabCEF.length;i++){
s=db.getStudent(tabCEF[i]);
if(!s.dateAbsenceAlreadyTaken(gc) && !s.dateRetardAlreadyTaken(gc)){
s.addAbsence(abs);
}
else if(!s.dateAbsenceAlreadyTaken(gc) && s.dateRetardAlreadyTaken(gc)){
JOptionPane.showMessageDialog(null, "Date exite deja parmi les retards de cet etudiant");
}
else if(s.dateAbsenceAlreadyTaken(gc) && !s.dateRetardAlreadyTaken(gc)){
if(s.getAbsence(gc).isJustified() && !justified){
s.getAbsence(gc).setJustified(justified);
s.getAbsence(gc).setComment(jTextArea1.getText());
s.setNbHR_J(s.getNbHR_Justifie()-1);
s.setNbHR_NonJustifie(s.getNbHR_NonJustifie()+1);
}
else if(!s.getAbsence(gc).isJustified() && justified){
s.getAbsence(gc).setJustified(justified);
s.getAbsence(gc).setComment(jTextArea1.getText());
s.setNbHR_J(s.getNbHR_Justifie()+1);
s.setNbHR_NonJustifie(s.getNbHR_NonJustifie()-1);
}
}
}
try {
db.saveStudents();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}else{
JOptionPane.showMessageDialog(null,"vous devez entrez une date");
}
}
I have no problem inserting new Absences to one or more students,(https://i.imgur.com/HNSjqxK.png) but when I try to modify an absence by more than one students something weird happens,it seams that in the first iteration of the for loop in the AbsenceRegulator Class i essentially modify all this particular Absence in All students which makes the program skips the last ELSE IF that's meant to modify the values accordingly.
(https://i.imgur.com/iadJg0u.png)
i know that this seems impossible but I'm at my wits end here and can't see what's the problem
I'm trying to make a quiz in Java but I'm having trouble accessing the array list data from the tester class and therefore my question text isn't showing up. I have three classes; tester, quiz interface and quiz set up. I've been playing around with it for a while and I'm pretty sure I'm starting to make things worse so I thought I'd post on here.
The questions are added to the array list in the Tester file but I can't seem to access this in the set up class for this method:
public void setQuestion(int randIndex) {
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}
Expected output was to take a random question from the array list and display the question text but instead nothing appears and it is blank.
I'm fairly new to Java and programming so any detailed answers are welcome! Thanks in advance.
import java.util.ArrayList;
public class QuizTester {
private static ArrayList<Question> questions; //declares arrayList to holds the questions
public static void main(String[] args) {
QuizSetUp theQuiz = new QuizSetUp();
questions = new ArrayList<Question>(); //constructor
questions.add(new FillInBlank("____________ is the ability of an object to take many forms.", "Polymorphism"));
questions.add(new FillInBlank("The process where one object acquires the properties of another is called __________", "inheritance"));
questions.add(new FillInBlank("The ___________ keyword is used by classes to inherit from interfaces", "implements"));
questions.add(new MultipleChoice("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?",
"Polymorphism", "Encapsulation", "Inheritance", "Construction", "Encapsulation"));
theQuiz.pickQuestion();
}
public ArrayList<Question> getQuestionList() {
return this.questions;
}
}
////////////////////////quiz set up file.
public class QuizSetUp {
private QuizInterface qi;
private QuizTester test;
//private ArrayList<Question> questions; //declares arrayList to holds the questions
private int counter = 1;
Random random;
int randIndex;
public QuizSetUp() {
setInterface();
//questions = new ArrayList<Question>(); //constructor
}
private enum QuAnswer { CORRECT,INCORRECT }
public void setInterface() {
qi = new QuizInterface();
test = new QuizTester();
//add action listeners to each of the buttons
ActionListener cl = new ClickListener();
qi.getNextBtn().addActionListener(cl);
qi.getStartQuizBtn().addActionListener(cl);
//allows users to press enter to start quiz rather than having to click quiz button
KeyListener ent = new KeyBoardListener();
qi.getUName().addKeyListener(ent);
qi.getUPassword().addKeyListener(ent);
}
public void pickQuestion() {
randQuestion();
setQuestion(randIndex);
//setAnswer("A", randIndex);
//setAnswer("B", randIndex);
//setAnswer("C", randIndex);
//setAnswer("D", randIndex);
//setCorrectAnswer(randIndex);
//qi.resetTimer();
}
public void setQuestion(int randIndex) {
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}
public void setNextQuestion() {
//qi.getTimer().cancel();
//qi.cancelInterval();
if (counter < 5) { //users must answer five questions to complete quiz
pickQuestion();
} else {
//JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
//switch to end panel to show results of quiz
}
}
public int randQuestion() {
random = new Random();
randIndex = random.nextInt(questions.size());
return randIndex;
}
//inner listener class for buttons
private class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == qi.getStartQuizBtn()) {
qi.setEnteredName(qi.getUName().getText());
qi.setEnteredPass(qi.getUPassword().getPassword());
validateInput();
} else if (evt.getSource() == qi.getNextBtn()) {
counter++;
if (counter == 5) {
qi.getNextBtn().setText("Finish Quiz"); //changes next button text on final question
}
if (counter < 6) {
qi.getQuProgress().setText(counter + " of 5");
} else {
//shuffle to end panel
}
}
}
}
//inner listener class for key presses
private class KeyBoardListener implements KeyListener {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
qi.setEnteredName(qi.getUName().getText());
qi.setEnteredPass(qi.getUPassword().getPassword());
validateInput();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//method to validate input by user to log in
public void validateInput() {
//presence check on username
if (qi.getEnteredName().length() > 0) {
//presence check on password
if (qi.getEnteredPass().length > 0) {
//ensures password is at least 6 char long
if(qi.getEnteredPass().length > 5) {
qi.getCards().next(qi.getPanels()); //getPanels() == cardPanel
} else {
JOptionPane.showMessageDialog(null,
"Your password must be at least six characters long.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Your did not enter a password.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
}
After some alterations, I was able to get your code running. But I have to warn you, there are quite some changes:
QuizTester now only has a main method to start the program. It will initialize and fill the list with questions and then pass it to the QuizSetUp instance
I didn't have your Question class, so I reduced it to an ArrayList<String> (just to make sure, that the questions could be passed)
And I didn't hvae your QuizInterface class so I helped myself with a small implementation that would simply print out the question when a new question gets set
QuizInterface (small helper class)
public class QuizInterface {
private String text;
public QuizInterface() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
System.out.println("question text = "+this.text); // this is just to make sure it worked
}
}
QuizSetUp (heavily reduced)
public class QuizSetUp {
private QuizInterface qi;
private ArrayList<String> questions; // uncommented, it's needed now
private int counter = 1;
Random random;
int randIndex;
// I chose to pass the list with the constructor but the setQuestions() will do as well
public QuizSetUp(ArrayList<String> questions) {
this.questions = questions;
setInterface();
}
// NEW method – but it's not needed
public ArrayList<String> getQuestions() {
return questions;
}
// NEW method – but it's not needed
public void setQuestions(ArrayList<String> questions) {
this.questions = questions;
}
private enum QuAnswer {
CORRECT, INCORRECT
}
public void setInterface() {
qi = new QuizInterface();
// test = new QuizTester(); // this is no longer needed since QuizTester is only used to start the program
}
public void pickQuestion() {
randQuestion();
setQuestion(); // randIndex is already a global variable in this class, no need to pass with the method call
}
public void setQuestion() {
// QuizInterface has a new method now called "setText()"
// so here we access the list "questions" (it is already initialized, because we pass it to this class when constructing it)
// this.randIndex is global, so we can use it directly in this method as an index to the questions list (as you already did it)
qi.setText(this.questions.get(this.randIndex));
}
public void setNextQuestion() {
//qi.getTimer().cancel();
//qi.cancelInterval();
if (counter < 5) { //users must answer five questions to complete quiz
pickQuestion();
} else {
//JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
//switch to end panel to show results of quiz
}
}
public int randQuestion() {
random = new Random();
randIndex = random.nextInt(questions.size());
return randIndex;
}
// .... the rest I left out here because it is not needed for this little test
}
QuizTester (only needs the main method)
public class QuizTester {
public static void main(String[] args) {
ArrayList<String> questions = new ArrayList<>(); //as you can see I replaced the List with a list of Strings (because I didn't have your Question class)
// so these are only strings...
questions.add("____________ is the ability of an object to take many forms.");
questions.add("The process where one object acquires the properties of another is called __________");
questions.add("The ___________ keyword is used by classes to inherit from interfaces");
questions.add("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?");
// here I create the QuizSetUp instance and pass the list right with the constructor
QuizSetUp theQuiz = new QuizSetUp(questions);
// if everything works out, calling this method
// should pick a new question, set it to the QuizInterface
// and the QuizInterface (the helper version I made) will print it out
theQuiz.pickQuestion();
}
}
Those three classes can compile as they are and when I ran the program I got this output
question text = The ___________ keyword is used by classes to inherit from interfaces
I know this is a lot different from what you have, the only big change I did was passing the newly create questions list directly to the QuizSetUp instance – so no accessing any static lists.
Looking at this line:
qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
where is the getQuestionList() implemented? It looks like a method call, except that QuizSetUp doesn't declare a getQuestionList() method. It is in a different class.
Conclusion: the code that you've shown us in the question won't even compile.
I should point that this (in QuezSetup) is very bad style, dnd liable to cause confusion.
private static ArrayList<Question> questions;
public ArrayList<Question> getQuestionList() {
return this.questions;
}
While this.questions looks like it is referring to an instance variable, it is actually referring to a static variable. The this is misleading.
I am using BlueJ and i am trying to call a method from another class. To be more specific i am trying to complete the following.
When the download music button is pressed, if a suitable value has been entered for the display number:
The display number is used to get the gadget, cast as MP3, from the array list.
The method to download music in the MP3 class is called with the
download size entered.
Here is the gadgetshop class that builds the GUI and the place where i want to call the downloadMusic method. the method for the button is called downloadMusic.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class GadgetShop implements ActionListener
{
//Array List
private ArrayList<Gadget>gadgets;
public void actionPerformed(ActionEvent event)
{
if (command.equals("Download Music"))
{
downloadMusic();
}
}
public void addMp3()
{
MP3 mp3 = new MP3(getWeight(), getPrice(), getModel(), getSize(), getMemory());
gadgets.add(mp3);
}
public void displayAll()
{
for(Gadget gadget : gadgets)
{
gadget.print();
System.out.println();
}
}
public void downloadMusic()
{
}
public int getDisplay()
{
int gadgetDisplay = 0;
try
{
gadgetDisplay = Integer.parseInt(displayText.getText());
if (gadgetDisplay<= 0)
{
JOptionPane.showMessageDialog
(frame, "Please enter a positive amount");
}
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog
(frame, "Please enter a positive amount");
}
return gadgetDisplay;
}
public String getDownload()
{
String gadgetDownload;
gadgetDownload = downloadText.getText();
return gadgetDownload;
}
}
This is the MP3 class
public class MP3 extends Gadget
{
private int memory;
public MP3(int theWeight, double thePrice, String theModel, String theSize, int theMemory)
{
super(theWeight,thePrice, theModel, theSize);
memory = theMemory;
}
public void downloadMusic(String music, int MusicSize)
{
if(MusicSize>memory)
//if statement saying if size is greater than memory then display the follwing statemnt saying there is not enough memory
{
System.out.println("Not Enough Memory");
}
else
// else statement opposite to the above statement saying if music size is less than or equal to the memory display the following statement
{
memory = memory - MusicSize;
System.out.println("Download Successfull. "+ "\nMusic Name: "+ music + "\nMemory Left: " + memory);
}
}
The "other class" (with the button) must have an instance of the class with the method you want to call. You could create an instance of MP3 in the constructor of GadgetShop and store it as an instance variable. Then in your button listener call
mp3Instance.downloadMusic("music", 42);
Is is possible in Java to call a method based on a field value? For example, I ask the user what soda they want. They enter their selection and the value of the field that holds their selection is used to call the method.
Obviously the below code doesn't work. But I'm hoping it will illustrate my intent. Is this sort of thing even possible in Java?
The goal is to effectively switch without using IF or SWITCH statements.
import java.util.Scanner;
public class FieldResolutionTest
{
public static void main (String[] args)
{
Scanner inputScanner = new Scanner(System.in);
MethodTester test = new MethodTester();
System.out.println("Please enter ONE or TWO");
String selection = inputScanner.nextLine();
test.(selection)();
}
}
public class MethodTester
{
public void ONE()
{
System.out.println("You ran method ONE");
}
public void TWO()
{
System.out.println("You ran method TWO");
}
}
It is technically possible with reflection, but if you have a finite number of known possible methods, it would be much simpler to use a switch statement (or if/else if you don't have Java 7):
switch (selection) {
case "ONE":
test.ONE();
break;
case "TWO":
test.TWO();
break;
// etc.
default:
System.out.println("Invalid method!");
break;
}
If the methods are dynamic or you are testing lots of classes, and you still want to go the reflection route, it would look something like this:
try {
Method m = MethodTester.class.getMethod(selection);
m.invoke(test);
} catch (NoSuchMethodException nsme) {
System.out.println("Invalid method!");
}
A nice approach is with enum:
public class FieldResolutionTest
{
public static void main (String[] args)
{
Scanner inputScanner = new Scanner(System.in);
System.out.println("Please enter ONE or TWO");
String selection = inputScanner.nextLine();
FieldResolutionTest.valueOf(selection).run();
}
}
public enum MethodTester
{
ONE { public void run()
{
System.out.println("You ran method ONE");
}},
TWO { public void run()
{
System.out.println("You ran method TWO");
}};
public abstract void run();
}
You can use reflection. This is your example with minimal modifications:
import java.lang.reflect.Method;
import java.util.Scanner;
public class FieldResolutionTest {
public static void main (String[] args) throws Exception {
Scanner inputScanner = new Scanner(System.in);
MethodTester test = new MethodTester();
System.out.println("Please enter ONE or TWO");
String selection = inputScanner.nextLine();
Method method = MethodTester.class.getMethod(selection);
method.invoke(test);
}
}
class MethodTester {
public void ONE() {
System.out.println("You ran method ONE");
}
public void TWO() {
System.out.println("You ran method TWO");
}
}
Of course, you need to add some error handling. For example, you should check that the user entered the name of one of the allowed methods, like this:
Map<String, Method> methods = new HashMap<String, Method>();
for (Method m: MethodTester.class.getMethods()) {
methods.put(m.getName(), m);
}
if (methods.containsKey(selection)) {
methods.get(selection).invoke(test);
} else {
System.err.println("No such method: " + selection);
}
You need to test the input value and call the corresponding method:
if(selection.equals("ONE")) test.ONE();
else if (selection.equals("ONE")) test.TWO();
else System.out.println("Unknown input!");
Since Java 7 was released, it is possible to perform the switch-case method on a string type variable
switch(selection) {
case "ONE":
test.ONE();
break;
case "TWO":
test.TWO();
break;
}
Again, only available since Java 7.
As told by mellamokb you can use reflection to invoke the method. Typically the code will look like test.getClass().getMethod("ONE", null).invoke(..)