Basically i want to enter the names as long as i don't cancel the InputMessageDialog, then i want to asign my names to variable created before and print them out at the end in the MessageDialog. I was trying some stuff outside the loop but got the notificacion that "value 'names' is always 'null'"
String names;
while (true) {
names = JOptionPane.showInputDialog(null, "ENTER THE NAMES");
if (names == null) {
JOptionPane.showMessageDialog(null, "ENTRY CANCELED!");
break;
} else {
}
}
JOptionPane.showMessageDialog(null, "YOUR NAMES: " + names);
Your code is pretty close to what you describe as your goal – the primary thing missing is that you need to keep track of the various values along the way, and print them at the end.
The code you posted will loop again and again asking for a single value (which you are storing into String names - a little confusing choice for variable name, since it contains only one name input). As you found, when the user hits the cancel button (to end the loop), it sets names to null. The final step shows a dialog box with the last value for names (which is always null).
Here's a program that:
loops until the user hits the "cancel" button (which would set input to be null), or if they enter a blank value – this allows the user to exit by simply hitting return without typing anything
adds all non-empty input values to a java.util.Set – this is an arbitrary choice, use whatever data structure is appropriate for your program
shows a final dialog with the contents of the set
import javax.swing.*;
import java.util.HashSet;
import java.util.Set;
public class t {
public static void main(String[] args) {
Set<String> values = new HashSet<>();
while (true) {
String input = JOptionPane.showInputDialog(null, "enter something");
if (input != null && !input.isEmpty()) {
values.add(input);
} else {
break;
}
}
JOptionPane.showMessageDialog(null, "all values: " + values);
}
}
If I run with the following input:
one
two two
three three three
<blank>
Then the final dialog message is:
all values: [one, two two, three three three]
Note that a java.util.Set doesn't necessarily return items in any specific order, it just happens to have worked out that way in this example.
Related
I'm wondering if anyone can give me some pointers on what the next steps in a basic program I have.
I have the following example java code:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
ArrayList<Transport> transportList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void addToList() {
transportList.add(new Transport("Blue", "Large", "Plane"));
transportList.add(new Transport("Red", "Small", "Car"));
transportList.add(new Transport("Brown", "Large", "Train"));
transportList.add(new Transport("Yellow", "Small", "Boat"));
transportList.add(new Transport("Yellow", "Small", "Plane"));
transportList.add(new Transport("Brown", "Large", "Car"));
transportList.add(new Transport("Red", "Large", "Train"));
transportList.add(new Transport("Blue", "Small", "Boat"));
searchColour();
}
public void searchColour() {
System.out.println("Enter a colour to search:\n");
String colourSearch = input.next();
for (Transport transport : transportList) {
if (transport.getColour().toLowerCase().equals(colourSearch.toLowerCase())) {
System.out.printf(
"There is a %s %s that is %s \n",
transport.getSize(),
transport.getType(),
transport.getColour()
);
}
}
searchColour();
}
public static void main(String[] args) {
new Main().addToList();
}
}
public class Transport {
private String colour;
private String size;
private String type;
// All-args constructor, getters and setters omitted for brevity
}
This runs and prompts the user to enter a colour. It then searches the ArrayList and outputs the matches.
What I now need to do is to take the results I get from a colour search and reuse them in a menu for selection.
For example if I search for "red", I get:
There is a Small Car that is Red
There is a Large Train that is Red
What I want is to have a number placed in front of them and another prompt to choose which one the person whats. So it should say something like:
There is a Small Car that is Red
There is a Large Train that is Red
"Choose which transport you want"
Outputting the next question and prompting for an input with Scanner I can do, I'm not sure how I can add numbers to the start of the results, knowing that as my ArrayList grows the number of items will, and how I do a selection choice from it so a user can press 1 or 2.
Can anyone offer a suggestion? I'm thinking I need to use another ArrayList but I'm not sure how this should be structured.
I think you should make use of the fact, that an ArrayList keeps the elements in insertion order. You could e.g. use the "indexOf(Object o)" method to get the number you want to be printed. (You have to add 1 to get your example, because it starts with 0.)
And to select the item you can use "get(int index)" and let the user type the index. (here you have to substract 1, like above.)
What you want is a counter. Create an int variable to keep track of the question number.
When the user inputs a number, use the List’s get method to retrieve the choice:
public void searchColour() {
System.out.println("Enter a colour to search:\n");
String colourSearch = input.next();
List<Transport> matches = new ArrayList<>();
int questionNumber = 1;
for (Transport transport : transportList) {
if (transport.getColour().toLowerCase().equals(colourSearch.toLowerCase())) {
matches.add(transport);
System.out.printf(
"%d. There is a %s %s that is %s \n",
questionNumber++,
transport.getSize(),
transport.getType(),
transport.getColour()
);
}
}
int choice;
do {
System.out.println();
System.out.println("Choose which transport you want:");
choice = input.nextInt();
} while (choice < 1 || choice > matches.size());
// List indices start at zero, not one.
Transport transport = matches.get(choice - 1);
System.out.printf("You chose a %s %s that is %s%n",
transport.getSize(),
transport.getType(),
transport.getColour()
}
The println method prints a newline after printing the argument you pass it. Therefore, you don’t need to pass a String ending with \n, unless you really want to print a blank line after the text (and that may not work in Windows, where a newline sequence is actually the two characters \r\n).
In the printf method, you can use the special Formatter sequence %n instead of a literal \n to make sure the system’s newline sequence is always used.
I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}
We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();
I am trying to make a game, at the start, the first part is fine, however, I cannot get the second question working, I would like it to display: rules_yes if Yes is entered (case insensitive), and rules_no to be displayed if anything else is written. At the moment, no matter what I input for the rules, it only runs the rules_yes. Can I get some feed back on how to make this work?
{
String user_name;
String name_answer;
String yes_no;
String rules_yes;
String rules_no;
char input;
private char yes;
private char Yes;
{
user_name = JOptionPane.showInputDialog("Enter Your Name");
name_answer = ("Hello " + user_name + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog( null, name_answer );
}
{
yes_no = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
if (input == Yes || input == yes)
{
rules_yes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rules_yes );
}
else
{
rules_no = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rules_no );
}
}
You have many issues with your code, and many things you can do to simplify it.
yes and Yes are not initialized, this caused your program to fail.
You can declare yes_no as a String, then use if (yes_no.equalsIgnoreCase("y");(rather than using char yes and char Yes)
This does not affect your program, but you have a lot of spacing between lines, which makes it seem like a lot more than it is.
input is unnecessary, so you can just delete it.
So your final code can look like this:
import javax.swing.JOptionPane;
public class ScratchPaper {
public static void main(String[]args) {
String userName;
String nameAnswer;
String rulesYes;
String rulesNo;
String yesNo;
userName = JOptionPane.showInputDialog("Enter Your Name");
nameAnswer = ("Hello " + userName + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog( null, nameAnswer );
yesNo = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
if (yesNo.equalsIgnoreCase("y"))
{
rulesYes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rulesYes );
}
else {
rulesNo = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rulesNo );
}
}
}
If you have any questions, please comment below, and I will answer them as soon as I can. Thank you!
Because you adding (Y/N) question value to "yes_no" param, but your 'if-else' condition working with 'input' so the input not initialized thats mean it's equals to 0.That's why your question always returning YES.
Change your code like this :
public static void main(String[] args) {
String user_name;
String name_answer;
String yes_no;
String rules_yes;
String rules_no;
char[] input;
char Yes = 0;
{
user_name = JOptionPane.showInputDialog("Enter Your Name");
name_answer = ("Hello " + user_name + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog(null, name_answer);
}
{
yes_no = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
input = yes_no.toCharArray();
if (input[0] == Yes) {
rules_yes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog(null, rules_yes);
} else {
rules_no = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog(null, rules_no);
}
}
}
Why are you using an "input" dialog?
An easier solution would be to just use a "message" dialog with "Yes", "No" buttons for the user to click on.
Read the section from the Swing tutorial on How to Make Dialogs for more information and examples.
I'm very new to programming, especially Java. I need to create a program that counts how many orders each entry at a restaurant gets ordered. The restaurant carries 3 entries, hamburgers, salad, and special.
I need to set up my program so that the user inputs, say, "hamburger 3", it would keep track of the number and add it up at the end. If the user inputs "quit", the program would quit.
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
I'm thinking about using a while loop, setting it so if the user input != to "quit", then it would run.
What's difficult for me is I don't know how to make my program take into account the two different parts of the user input, "hamburger 3" and sum up the number part at the end.
At the end, I want it to say something like "You sold X hamburgers, Y salads, and Z specials today."
Help would be appreciated.
You'll probably want three int variables to use as a running tally of the number of orders been made:
public class Restaurant {
private int specials = 0;
private int salads = 0;
private int hamburger = 0;
You could then use a do-while loop to request information from the user...
String input = null;
do {
//...
} while ("quite".equalsIgnoreCase(input));
Now, you need some way to ask the user for input. You can use a java.util.Scanner easily enough for this. See the Scanning tutorial
Scanner scanner = new Scanner(System.in);
//...
do {
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
input = scanner.nextLine();
Now you have the input from the user, you need to make some decisions. You need to know if they entered valid input (an entree and an amount) as well as if they entered an available option...
// Break the input apart at the spaces...
String[] parts = input.split(" ");
// We only care if there are two parts...
if (parts.length == 2) {
// Process the parts...
} else if (parts.length == 0 || !"quite".equalsIgnoreCase(parts[0])) {
System.out.println("Your selection is invalid");
}
Okay, so we can now determine if the user input meets or first requirement or not ([text][space][text]), now we need to determine if the values are actually valid...
First, lets check the quantity...
if (parts.length == 2) {
// We user another Scanner, as this can determine if the String
// is an `int` value (or at least starts with one)
Scanner test = new Scanner(parts[1]);
if (test.hasInt()) {
int quantity = test.nextInt();
// continue processing...
} else {
System.out.println(parts[1] + " is not a valid quantity");
}
Now we want to check if the actually entered a valid entree...
if (test.hasInt()) {
int quantity = test.nextInt();
// We could use a case statement here, but for simplicity...
if ("special".equalsIgnoreCase(parts[0])) {
specials += quantity;
} else if ("salad".equalsIgnoreCase(parts[0])) {
salads += quantity;
} else if ("hamburger".equalsIgnoreCase(parts[0])) {
hamburger += quantity;
} else {
System.out.println(parts[0] + " is not a valid entree");
}
Take a look at The if-then and if-then-else Statements and The while and do-while Statements for more details.
You may also find Learning the Java Language of some help. Also, keep a copy of the JavaDocs at hand, it will make it eaiser to find references to the classes within the API
These two methods should be what you're looking for.
For splitting: String.split(String regex)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
For parsing String into an Interger: Integer.parseInt(String s)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
You can split your strings using input.split(" "). This method gives you two strings - two parts of the main string. The character you splitted with (" ") won't be found in the string anymore.
To then get an integer out of your string, you can use the static method Integer.parseInt(inputPartWithCount).
I hope this helps!