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.
Related
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.
I am building a hangman game but I need help trying to check whether the user input was used before (like they guess a then b and than a again):
String input = console.next();
if(input.length()>1){
System.out.println("One letter at a time");
}
//to insert data into arrays
letter[a]=input;
if (!input.equalsIgnoreCase(input)) {
System.out.println("You have aready enter " + input);
} else {
continue;
}
This will add the method you want to use to the String class:
String.prototype.equalsIgnoreCase = function(other_string) {
return this.toLowerCase() === other_string.toLowerCase();
}
Make sure you're not trying to compare a String to itself, though, like you're doing with input in your question. Also, use JavaScript syntax for web-served files instead of C++ syntax.
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!
So everything is working fine for this calculator besides for the askCalcChoice1. Since askCalcChoice1 is a string, I am calling it wrong (obviously). The error says it cannot convert string to int, as well as convert int to boolean. However, when i make the inputOperation as a string, it breaks the other 2 calls below askCalcChoice1. (it breaks displayRedults and askTwoValues because those are not strings). I do not know how to format askCalcChoice in order to call for this method that is written in another class wihtout breaking anything. askCalcChoice is written as a string which i pasted below the oopCalculator code. Is there any way and can someone please show me how to write that portion of that code in oopCalculator?
int inputOperation; // user to choose the function
askCalcChoice1 myAskCalcChoice1 = new askCalcChoice1();
//menu becomes a complete string below
String menu = "Welcome to Hilda Wu's Calculator\t\t"
+ "\n1. Addition\n"
+ "2. Subtraction\n"
+ "3. Multiplication\n"
+ "4. Division\n"
+ "5. Exit\n\n";
calculatorCommands.pickNewSymbol(menu); //complete menu will be picked up as a string and display
calculatorCommands.putDownSymbol();
while (inputOperation = myAskCalcChoice1.calcChoice()) { //this will call for myAskCalcChoice1 class
calculatorCommands.pickNewSymbol("\n"); //pick up the class
calculatorCommands.putDownSymbol(); //display the class
askTwoValues myAskTwoValues = new askTwoValues();
float[] myFloats = myAskTwoValues.inputFloats(inputOperation);
displayResults myDisplayResults = new displayResults();
float result = myDisplayResults.showResults(inputOperation, myFloats);
String strFormat = "The answer is: " + result + "\n\n"; //print out The answer is as a string
calculatorCommands.pickNewSymbol(strFormat); //pick up string from above
calculatorCommands.putDownSymbol(); //display string
calculatorCommands.pickNewSymbol(menu); // pick up menu from the beginning of code, loop to calculator menu
calculatorCommands.putDownSymbol(); //display menu as loop
}
calculatorCommands.pickNewSymbol("\nThank you for using Hilda Wu's Calculator\n"); //when user choose to exit calculator
calculatorCommands.putDownSymbol();
}
String calcChoice() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for Subtraction, M for Multiplication, or D for Division, or X for Exit: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D") || input.equals("X")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have entered an invalid choice, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
}
To start with, you are calling showResults with two arguments:
int choice
and
float [] f
Choice is never used.
You use input variable instead in your switch but on default you return the error showing choice.
Better pass choice as an argument in the function and be sure it is char and not other type.
Also this is not the form of a good stated question. I will not rate it down but please remake it so the whole code is correctly shown. I can not make sense of it easily. I might misunderstood it already. Please do not add comments between, be sure you have correct indentation and you got all the code in.
If you need to comment do it afterwards. It's not very complicated, just show us the code and ask what is wrong later ;)
If choice was meant to pass in the switch... then do it, but not as int but as char.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing a java program that is like a physics lesson:
import javax.swing.JOptionPane;
public class PhysicsClass {
public static void main(String[] args) {
int g = -1;
while (g<0){
String input = JOptionPane.showInputDialog("Welcome! What's your name? ");
if(input.length() > 0){
g++;
System.out.println("Great! Lets begin.");
}
else{
System.out.println(" ok then.");
System.exit(0);
}
}
String[] firstChoice = {"Kinematics", "Dynamics", "Impulse/Momentum", "Energy/Power"};
JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
int i = 0;
while (i<0){
String Choice = "";
if (Choice == firstChoice[0]){
Kinematics.IntroToKinematics();
i++;
}
else if (Choice == firstChoice[1]){
Dynamics.DynamicsIntro();
i++;
}
else if (Choice == firstChoice[2]){
ImpulseAndMomentum.ImpulseAndMomentumIntro();
i++;
}
else if (Choice == firstChoice[3]){
EnergyAndPower.EnergyAndPowerIntro();
i++;
}
else{
System.out.println("Please pick one.");
}
}
I want whatever choice you pick in the first choice array to then go to the respected class. So if I choose kinematics, it will call on the kinematics class, for which the first few lines are:
import javax.swing.JOptionPane;
public class Kinematics {
public static void IntroToKinematics() {
JOptionPane.showInternalMessageDialog(null, "Kinematics is one of the most basic"
+ " ideas of Newtonian Physics. It encompasses: speed, distance, time"
+ " displacement, acceleration and many key base concepts that form the the "
+ " foundation for most physic subjects. It will poke its head in everything"
+ "we cover.", "intro", JOptionPane.INFORMATION_MESSAGE);
}
}
It doesn't give me any errors but when I choose one of the strings from the array, it doesn't do anything. I think it might have something to do with the if else statements I used. Thanks for any and all help, I'm still relatively new to Java so any tips would be appreciated.
Use equals to compare strings like-
if(Choice.equals(firstChoice[0])){...}
First off you want to store the result of the input box somewhere:
String choice = JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
Then use .equals to do your string compares instead of ==
if (choice.equals(firstChoice[0])){
Kinematics.IntroToKinematics();
}
The loop shouldn't be necessary.
You're not binding Choice to selected value, it always compares it to ""
First at the showInputDialog you should do something like this
String Choice = "";
Choice= (String) JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
Declaring first the variable Choice, and then asigning the inputDialog value to choice, afther that your while should be like this
int i = 0;
while (i<=0){
//do something
}
because the first time it runs i<0 , since 0 is not lower than 0 (since you are declaring int i =0;) is not going to run.
And you could keep using "", but something like this should be more efficient
if (Choice.equals(firstChoice[0])){
Kinematics.IntroToKinematics();
i++;
}
Finally try to use lowercase first at your variables eg: tableSize