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
Related
I'm essentially making a small, simply "twenty questions" style program, using nested if-statements to try to guess what object the user is thinking based on clarifying questions.
I'm using the if statements to eventually give the user a "result" at the end, using a String variable called "result".
My ultimate confusion lies in which the compiler is stating that "variable response may have not been initialized". To which, based on the code, I would think it is after the if statements.
import java.util.Scanner;
public class TwoQuestions {
public static void main (String args[] ) {
Scanner kb = new Scanner(System.in);
String answer1, answer2, response;
System.out.println("\n[Two Questions]\nThink of an object, and I'll try to guess it.");
System.out.println("Is it an \"animal\", a \"vegetable\", or a \"mineral\"? (Type an answer exactly as quoted)");
answer1 = kb.nextLine();
System.out.println("Is it bigger than a breadbox? (yes/no)");
answer2 = kb.nextLine();
// example "response" based on user decisions
if (answer1 == "animal" || answer1 == "Animal") {
response = "yes";
if (answer2 == "yes" || answer2 == "Yes") {
response = "squirrel";
}
}
// more if statements...
// final machine "response" to user"
// TODO: Figure out why *this* "response" requires initialization before if statements.
System.out.println("My guess is that you are thinking of a " + response + ".\nI would ask you if I'm right, but I don't actually care.");
}
}
Like mad programmer said use String equals function to compare string.
Yes it will need to be initialize before compilation can take place. If Im not wrong you can initialize with Null, or " ", empty string.
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.
Hello and thank you in advance for your time. I'm working on a homework assignment that require an input from the user in command line. If the user input the "Exit" or "Quit" My program should quit. I'm able to do one one work but not sure how to do two. ALso the my loop is not looping all time. Can someone shine some light please.
import java.io.Console;
public class Echo2{
public static void main(String [] args){
String userText = System.console().readLine("Enter some text:");
//System.out.println("*** " + userText + " ***" );
if (userText.equals("Exit")){
return;
}
else{
System.out.println("*** " + userText + " ***" );
}
}
}
As of the loop you can simply do this:
while(true) {
if (userText.equals("Exit") || userText.equals("Quit")) {
break;
}
}
Or if you want to go a little fancy here you can do this
while(true) {
if ("exit".equals(userText.toLowerString()) || "quit".equals(userText.toLowerString()) {
break;
}
}
the 2nd approach is a little more flexi here, as regardless of the what the user types (this being quit, qUit, EXIT, exIT) the program will convert this to lower case and match within the condition specified
Just use the || operator if you want to do more than one check in an if statement:
if (userText.equals("Exit") || userText.equals("Quit")) { ... }
As far as your loop "not looping all the time"; I don't see any loop. Have you failed to include it in your post?
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.