I'm doing a train ticket program. I want to convert certain text in the string array to a certain price using JOptionPane.
ex.
String[] option_1 = {"location1","location2", "location3","location4","location5"};
where location1 = $10, location2 = $23, etc.
all I know is I could use Interger.parseInt or double, but I don't know where to go next. Should I go with a loop or make a whole new array and make it equal to the string array. I'm wondering if there is a more easier method to execute this.
code :
public static void main (String [] args) {
String name;
String[] option_1 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
String[] option_2 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
name = JOptionPane.showInputDialog("Welcome to DME Ticketing System!\n\nEnter your name:");
String leave = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_1, option_1[0]);
String going = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_2, option_2[0]);
// int pay = (Integer)JOptionPane.showInputDialog(null, "From: "+leave+"\nTo: "+going+"\nFare Price: "+"\n\nEnter your payment amount:",
// null, JOptionPane.PLAIN_MESSAGE, null, null,null);
// int op1 = Integer.parseInt(going);
// int op2 = Integer.parseInt(leave);
JOptionPane.showMessageDialog(null, "DME Ticketing System\nMalolos, Bulacan\n\n"
+ "Name: "+name
+"\nLocation: "+leave
+"\nDestination: "+going
+"\nFare: "
+"\nPayment: "//+pay
+"\nChange: "
, "RECEIPT",JOptionPane.INFORMATION_MESSAGE);
}
-The codes I turned into comments are giving me errors
showInputDialog always returns the input of the user as a String object, except from a variation where it returns the selected Object from the supplied ones. I am talking for Java version 8 for the sake of example.
Based on your question and comments, you basically want to:
Match String objects (their name) to integers (their value), so that you can calculate how much they will have to pay, plus the change afterwards.
Receive as input from the user the amount they will give, in order to calculate the change.
If so, then:
For the first case you can use some data structure(s) from which you will be able to match the locations with their value. For example a HashMap<String, Integer> can match the locations with their value, like so:
//Set up the origin options, along with their value:
HashMap<String, Integer> leavingOptions = new HashMap<>();
leavingOptions.put("North Avenue", 10);
leavingOptions.put("Quezon Avenue", 11);
leavingOptions.put("Kamuning", 12);
leavingOptions.put("Cubao", 13);
leavingOptions.put("Santolan", 14);
leavingOptions.put("Ortigas", 15);
leavingOptions.put("Shaw", 16);
leavingOptions.put("Boni", 17);
leavingOptions.put("Guadalupe", 18);
leavingOptions.put("Buendia", 19);
leavingOptions.put("Ayala", 20);
leavingOptions.put("Magallanes", 21);
leavingOptions.put("Taft", 22);
//Get user input for origin:
Object[] leavingOptionsArray = leavingOptions.keySet().toArray();
String leaving = (String) JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptionsArray, leavingOptionsArray[0]);
//Show output depending on user's input or cancel:
if (leaving != null)
JOptionPane.showMessageDialog(null, "You shall pay: " + leavingOptions.get(leaving));
else
JOptionPane.showMessageDialog(null, "Quiting...");
(note here that the casting of the returned value of the showInputDialog to a String reference is safe, just because the way we set up the options' array to contain only String objects)
Or you can use a String array with the locations along with an int array with the corresponding values, like so:
//Set up the origin options, along with their price:
String[] leavingOptions2 = new String[]{"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
int[] price = new int[]{10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
//Get user input for origin:
Object leaving2 = JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptions2, leavingOptions2[0]);
//Show output depending on user's input or cancel:
if (leaving2 != null) {
//Find the price of the selected location:
int p = -1;
for (int i = 0; i < price.length; ++i)
if (leaving2.equals(leavingOptions2[i])) {
p = price[i];
break;
}
JOptionPane.showMessageDialog(null, "You shall pay: " + p);
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Or even better, you can use another object type other than String for the options array, for example a class named Location which will have the name and the price as properties, the toString method of which will return the name.
For the second part, obtain the user's input as a String from a JOptionPane and use Integer.parseInt(...) method on the user's input so as to be able to calculate the change afterwards, like so:
String paymentString = JOptionPane.showInputDialog(null, "Enter payment amount:", "Payment", JOptionPane.QUESTION_MESSAGE);
if (paymentString != null) {
try {
int payment = Integer.parseInt(paymentString);
JOptionPane.showMessageDialog(null, "You chose to pay: " + payment);
//Calculate change here...
}
catch (final NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "The input was invalid (not an 'int').");
}
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Remember that parseInt will throw a NumberFormatException (which is a RuntimeException) if its input String is not an int, so you will have to check for that using a try-catch block.
Related
Im creating a project where the area or volume of certain shapes are calculated using dropdown menus in java. I don't have any errors when compiling however I'm getting the message that "Unlikely argument type for equals(): String seems to be unrelated to String[]". As stated, it complies fine, but when running it allows area/volume to be selected, but it does not reach the next option pane to select the shapes.
The message appears on: if (choices.equals("Area"))
and : if (choices.equals("Volume"))
`
import javax.swing.JOptionPane;
public class Shapes
{
public static void main(String[] args)
{
//Dropdown menu for area and volume
String[] choices = {"Area", "Volume"};
String question = (String) JOptionPane.showInputDialog(null, "What would you like to calculate?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices,
choices[0]);
System.out.println(question);
if (choices.equals("Area"))
{
//user chooses area
String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
String question2D = (String) JOptionPane.showInputDialog(null, "What shape will you choose?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices2D,
choices2D[0]);
System.out.println(question2D);
}
//user chooses volume
if (choices.equals("Volume"))
{
String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
String question3D = (String) JOptionPane.showInputDialog(null, "What figure will you choose?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices3D,
choices3D[0]);
System.out.println(question3D);
}
}
}
`
I originally had the options linked to a switch but would keep running into errors, after changing it to an if statement it will compile but not run properly.
Your comparisons are choices.equals(…), but you meant to compare the selection from the dropbox, and this is stored in question. So the comparisons should be question.equals(…).
Alternatively, try this:
import javax.swing.JOptionPane;
public class Shapes
{
public static void main(String... args)
{
//Dropdown menu for area and volume
String[] choices = {"Area", "Volume"};
String question = (String) JOptionPane.showInputDialog( null,
"What would you like to calculate?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices,
choices[0]) ;
System.out.println(question);
switch( question )
{
case "Area":
{
//user chooses area
String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
String question2D = (String) JOptionPane.showInputDialog( null,
"What shape will you choose?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices2D,
choices2D[0] );
System.out.println( question2D );
break;
}
case "Volume":
{
//user chooses volume
String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
String question3D = (String) JOptionPane.showInputDialog( null,
"What figure will you choose?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices3D,
choices3D[0] );
System.out.println( question3D );
break;
}
}
}
}
You can also use the new switch-case syntax and optimise further, by using enums for the various choices.
You are comparing the whole array with a single string. Use choices[0].equals("Area"). Now this will compare choices array with string at index 0 with Area.
Background
Building an Assembler in Java:
I'm trying to read user's input into an ArrayList named v.
If the user enters an instruction that matches one of the String-array table, then the corresponding opcode will be calculated and output into a textfile.
Problem
However, after inputting the nop instruction and trying to add another instruction, I got an index out of bounds exception.
Source Code
//Array of instructions
String table[] = {"LI", " MALSI", "MAHSI", "MSLSI", "MSHSI", "MALSL", "MAHSL",
"MSLSL", "MSHSL", "NOP", "A", "AH", "AHS", "AND", "BCW", "CLZ", "MAX", "MIN",
"MSGN", "MPYU", "OR", "POPCNTH", "ROT", "ROTW", "SHLHI", "SFH", "SFW", "SFHS", "XOR "};
//Array of binary values of the instructions
String table2[] = {"0", "10000", "10001", "10010", "10011", "10100", "10101",
"10110", "10111", "1100000000000000000000000", "1100000001", "1100000010", "1100000011",
"1100000100", "1100000101", "1100000110", "1100000111", "1100001000", "1100001001",
"1100001010", "1100001011", "1100001100", "1100001101", "1100001110", "1100001111",
"1100010000", "1100010001", "1100010010", "1100010011"};
// TODO code application logic here
Scanner s = new Scanner(System.in);
String ins = "";
String fileName = "outfile.txt";
System.out.println("Please enter MISP function, enter Q to Quit: ");
boolean q = true;
String op = "";
int c = 0;
String array[] = new String[64];
//Loop to keep accepting userinput
while (q) {
//accepts the user input
ins = s.nextLine();
//arraylist to hold user input
List<String> v = new ArrayList<String>();
//adds the user input to the arraylist
v.add(ins);//user input to nop opcode
if (v.get(0).toUpperCase().equals("NOP")) {
op = "1100000000000000000000000";
} else if (v.get(1).toUpperCase().equals("LI"))//li opcode
{
String p[] = v[1].split(",", 1);
op = "0";
op += toBinary(p[0], 3);
op += toBinary(p[1], 16);
op += toBinary(p[2], 5);
Error Stacktrace I got
Exception in thread "main" java.lang.IndexOutOfBoundsException:
If you guys could help it would be appreciated.
This loop will never end.
while (q)
public class SimpleDialogueBox {
public static void main(String[] args){
String name = JOptionPane.showInputDialog("Name");
String age = JOptionPane.showInputDialog("age");
String address = JOptionPane.showInputDialog("Address");
String contact = JOptionPane.showInputDialog("Contact Number");
JOptionPane.showMessageDialog(null, "User information is", name);
}
}
I want to have a display like this:
Explanation
The method JOptionPane#showMessageDialog takes a regular object to display, a String for example, nothing fancy. From its documentation:
public static void showMessageDialog(Component parentComponent, Object message) throws HeadlessException
Brings up an information-message dialog titled "Message".
Parameters:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
message - the Object to display
So you just have to build the String you want to display and then you pass it to the method. You can concatenate Strings using the + operator:
String lineSep = System.lineSeparator();
String message = "User information is: " + name + lineSep;
And so on. You can also use a StringBuilder for this purpose, it is also more efficient to use it for various reasons.
Code
Here is the full code:
String name = JOptionPane.showInputDialog("Name");
String age = JOptionPane.showInputDialog("age");
String address = JOptionPane.showInputDialog("Address");
String contact = JOptionPane.showInputDialog("Contact Number");
String lineSep = System.lineSeparator();
StringBuilder result = new StringBuilder();
result.append("User information is: ").append(lineSep).append(lineSep);
result.append("Name: ").append(name).append(lineSep);
result.append("Age: ").append(age).append(lineSep);
result.append("Address: ").append(address).append(lineSep);
result.append("Contact Number: ").append(contact);
JOptionPane.showMessageDialog(null, result.toString());
And that is the resulting dialog:
I am supposed to create an output similar to this:
I have organized my data into an array. To put it simply, I have organized it to
with 8 different POIBook with its individual data.
POIBook[i] = new POI(Type, Place, Rating)
I have no problems calling the right array according to the user input into a JOptionpane display.
However, I have problems trying to determine the total number of search and the search result the user is currently at. Eg. Search 1 of 3
How do I get the total number of the search result and the number the user is currently at?
Edit: To add in the context of the question.
The user will enter a search query in JOptionpane and it will search and return the array containing the search result. For example, searching for "Excitement" will return POIBook[4] , [5] and [6] as a JOptionpane display and as per the output expected in the picture above.
Need help on the following:
How do I show that that 'Search Result - 1/3' when POIBook [4] is returned? and 'Search Result - 2/3' when POIBook[5] is returned etc.?
At the point of display, we will need to know there are 3 results of "excitement" type and it is currently showing the 1st result out of 3.
public static void dataPOI() {
POIBook[0] = new POI("Sightseeing", "River Safari","Wildlife, Panda Bear, Cruise",4.0);
POIBook[1] = new POI("Sightseeing", "Singapore Flyer","Fly!",3.5);
POIBook[2] = new POI("Sightseeing", "Gardens by The Bay","Flower Dome, Cloud Forest",3.5);
POIBook[3] = new POI("Shopping", "Orchard Road","Ion, Mandarin Gallery",4.0);
POIBook[4] = new POI("Excitement", "Universal Studios","Battlestar Galactica, Puss in Boots",4.5);
POIBook[5] = new POI("Excitement", "Marina Bay Sands","Casino, Sky Park Observation Deck",4.0);
POIBook[6] = new POI("Excitement", "Resorts World Sentosa","Trick Eye Museum, Adventure Cove",4.5);
POIBook[7] = new POI("Night Life", "Night Safari","Wildlife, Tram Ride",4.5);
}
My code is as follows.
public static void search() {
String search = JOptionPane.showInputDialog(null, "Please enter your type of attraction", "Place of Interest",
JOptionPane.QUESTION_MESSAGE);
for (int i = 0; i<POIBook.length; i++) {
if(search.equalsIgnoreCase(POIBook[i].type)) {
Object[] options = { "Next >", "Return to Menu" };
int select = JOptionPane.showOptionDialog(null, "Place of interest " + (i+1) + " of 8\n" + POIBook[i].display() +
"\nPress Next for next Place of Interest \n" + "To return, press Return to Menu \n", "Display Places of Interest in Sequence",
JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE, POIBook[i].icon, options, options[1]);
if (select == 1) {
return;
}
}
}
}
I want to retrieve user values from a JOptionPane, I then want to use those values as parameters for the creation of a new instance of another class.
This is my code:
protected void addCar()
{
String[] size = {"Large","Small"};
String[] value = {"Valuable","Not Valuable"};
JTextField regNum = new JTextField();
JList carSize = new JList(size);
JList carValue = new JList(value);
carValue.getSelectedValue();
System.out.println(carSize.getSelectedValue());
Object[] fields =
{
"Registration Number", regNum,
"Car Size", carSize,
"Car Value", carValue
};
JOptionPane.showOptionDialog(rootPane, fields, "Wish To Continue?",
JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION,
null, null, regNum);
}//end addCar
You can simply get the user input from the components you passed to showOptionDialog() after it has returned.
One thing to note: the 4th parameter of showOptionDialog() is the option type so it should be YES_NO_OPTION and not DEFAULT_OPTION. And the 5th parameter is the message type to which you can pass INFORMATION_MESSAGE for example. The other parameters are not relevant in your case.
See this example:
// Your code here to create components
JOptionPane.showOptionDialog(null, fields, "Wish To Continue?",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
System.out.println(fields[0] + ": " + regNum.getText());
System.out.println(fields[2] + ": " + carSize.getSelectedValue());
System.out.println(fields[4] + ": " + carValue.getSelectedValue());
Output:
Registration Number: 1234
Car Size: Large
Car Value: Not Valuable
If you want to use these values to create an instance of another class, you can simply pass them like this:
OtherClass oc = new OtherClass(regNum.getText(), carSize.getSelectedValue(),
carValue.getSelectedValue());
This assumed that your OtherClass has a constructor like this:
public OtherClass(String regNum, String carSize, String carValue) {
}