This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm not so good at programming and can't tell why this isn't working. Whatever I input, it always go straight to the else statement.
public void pizzaIntro()
{
Scanner user_input = new Scanner(System.in);
String user_command = "null";
String apology = "I'm sorry it appears there has been some kind of mistake in your order.";
System.out.println("Welcome to " + cM + " here we strive to deliver excellent services to all our customers!");
System.out.println("The current prize for pizza is $" + bP + " and an extra $" + tP + " per topping.");
System.out.println(); System.out.println();
while(user_command != "exit")
{
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if(user_command.toLowerCase() == "yes")
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.toLowerCase() == "no")
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
pic1.show();
}
Use equals method to compare strings. To know the difference between == and equals, read https://stackoverflow.com/questions/7311451/difference-between-equals-and-instanceof
You will get a clear idea of what to use when.
while(!(user_command.equals("exit")) {
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if(user_command.toLowerCase().equals("yes"))
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.toLowerCase().equals("no"))
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
Use equals method instead of ==
user_command.toLowerCase().equals("yes")
In Java, == always just compares two references. Its OK to use it for primitive data types. String is not primitive datatype. String is a object. You should use equals method.
In your case you can consider using equalsIgnoreCase method to ignore the Case.
Use equalsIgnoreCase. It is more safe
public void pizzaIntro()
{
Scanner user_input = new Scanner(System.in);
String user_command = "null";
String apology = "I'm sorry it appears there has been some kind of mistake in your order.";
System.out.println("Welcome to " + cM
+ " here we strive to deliver excellent services to all our customers!");
System.out.println("The current prize for pizza is $" + bP
+ " and an extra $" + tP + " per topping.");
System.out.println();
System.out.println();
while (!user_command.equalsIgnoreCase("exit"))
{
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if (user_command.equalsIgnoreCase("yes"))
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.equalsIgnoreCase("no"))
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
pic1.show();
}
Never compare any Java objects with "==" (only primitives like int, long, double, etc.). It should read:
if(user_command.toLowerCase().equals("yes")) {
...
}
otherwise you check if the location of the object is the same, not the content.
In this particular example you might just want to use String.equalsIgnoreCase(...) instead.
Related
import java.util.Scanner;
public class JavaClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println("Welcome to Baugette Store! ");
System.out.println("*****Bakery Inventory*****");
System.out.print("Enter amount of Baugette:");
int amount1=scan.nextInt();
if(amount1<0) {
System.out.println("Error.");
return;
}
System.out.print("Enter Price of Baugette:");
double price1=scan.nextDouble();
*if(price1<0) {
System.out.println("Error.");
return;
}
System.out.println("**Customer Interface**");
System.out.println("Welcome to our baugette store. ");
System.out.println("We have "+price1+ " baugette(s) available.");
System.out.println("How Many Baugette(s) Do You Want to Buy?");
int amount2=scan.nextInt();
if(amount2<=0) {
System.out.println("Error.");
return;
}
if(amount2>amount1) {
System.out.println("Error.");
return;
}
else {
System.out.println("You want to buy "+amount2+ " baugette(s).");
double totalcost,r;
totalcost=amount2*price1;
r=amount1-amount2;
System.out.println("Yours cost is "+(int)totalcost+" Turkish lira(s)");
System.out.println("Now, We have "+(int)r+" baugette(s) remaining.");
System.out.println("Thank you for shopping from Kolantro Baugette Shop today.");
System.out.println("Good bye :)");
}
}
}
I want to learn how do i stop this algorithm without using return; for each if block. When I delete all return;s complier keeps reading codes. I want to execute when i type -3 for first if block Algorithm must be stopped without using return;.
As the comments below your question suggest, you can use a if-else-statement:
if (amount1 == -3) {
return;
} else {
// ...
}
Or short:
if (amount1 == -3) {
return;
}
// ...
But this way you have a return, which you don't want if I understand you correctly. You can invert the logic and run your code only if the amount1 is not -3. This way there is no return-statement:
public static void main(String args[]) {
// ...
if (amount1 != -3) {
// ...
}
}
If you asked for -3 as an example, here is the code if you want to skip if the amount is below or equals 0:
if (amount1 > 0) { // One ore more baugettes available, shop is open
// ...
}
Take your time to think about how if-statements work and how the condition(s) are evaluated. You can also nest if-statements:
if (1>0) {
if (a==b) {
}
}
This way you can structure your algorithms in a neat way.
Btw, you have a bug:
"We have " + price1 + " baugette(s) available."
must be
"We have " + amount1 + " baugette(s) available."
Consider using meaningful names for your variables, e.g. amountBaugettesInStore. This way you don't mix them up so easily.
So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am looking for a little help. I am sitting at home trying to learn java programming from programmingbydoing.com. I need to make a program called TwentyQuestions. The code is missing something to make it work completely.
I have tried to find help other places on the web. That is why the code looks much like other peoples code.
import java.util.Scanner;
public class TwentyQuestions
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String type, size, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println("");
System.out.println("Question 1) Is it animal, vegetable or mineral?");
System.out.print("> ");
type = keyboard.next();
System.out.println("");
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print("> ");
size = keyboard.next();
System.out.println("");
if (type.equalsIgnoreCase("animal"))
{
if (size == "no")
{
guess = "squirrel";
}
else
{
guess = "moose";
}
}
else if (type.equalsIgnoreCase("vegetable"))
{
if (size == "no")
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (type.equalsIgnoreCase("mineral"))
{
if (size == "no")
{
guess = "paper clip";
}
else
{
guess = "Camero";
}
}
if (guess == "")
{
System.out.println("The answers provided are not valid. Please try again.");
}
else
{
System.out.println("My guess is that you are thinking of a " + guess + ".");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
}
The problem is that the program does not care about the comparisons that are in the nested if-statements. Control always goes to the else and prints that one.
when you want to compare Strings you need to use the method .equals() or in the case to ignore case .equalsIgnoreCase()
Try the code below and you'll see it works just fine.
import java.util.Scanner;
public class TwentyQuestions {
public static void main ( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String type, size, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println("");
System.out.println("Question 1) Is it animal, vegetable or mineral?");
System.out.print("> ");
type = keyboard.next();
System.out.println("");
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print("> ");
size = keyboard.next();
System.out.println("");
if (type.equalsIgnoreCase("animal"))
{
if (size.trim().equalsIgnoreCase("no"))
{
guess = "squirrel";
}
else
{
guess = "moose";
}
}
else if (type.equalsIgnoreCase("vegetable"))
{
if (size.trim().equalsIgnoreCase("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (type.equalsIgnoreCase("mineral"))
{
if (size.trim().equalsIgnoreCase("no"))
{
guess = "paper clip";
}
else
{
guess = "Camero";
}
}
if (guess == "")
{
System.out.println("The answers provided are not valid. Please try again.");
}
else
{
System.out.println("My guess is that you are thinking of a " + guess + ".");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to figure out why my function isn't working as it should. The code is fairly basic and self explanatory. Here is the function:
public static void Greet(){
System.out.println("Hello, what is your name? ");
name = scan.nextLine();
do{
System.out.println("Would you like to order some coffee, " + name + "? (y/n) ");
input = scan.nextLine();
if(input == "y"){
System.out.println("Great! Let's get started.");
break;
}
else if(input == "n"){
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
else{
System.out.println("Invalid response. Try again.");
}
}
while(true);
}
Basically, regardless of what I enter as "input" on line 5, the function will treat it as if I hadn't entered a 'y' or 'n', it just constantly loops the while(true) and printing "Invalid response. Try again." I have no idea why my if/else statements aren't working correctly. Any help would be appreciated, thanks!
Compare String by equals not by ==
if((input.trim()).equals("y")){
equals compares the value
== comapres the reference
Compare with equals.
if(input.equals("y")){
System.out.println("Great! Let's get started.");
break;
}
else if(input.equals("n")){
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
What I want to do is simply read a input (Char/String , preferably char), its a single char and then print some outputs based on the inputs. My problems faced is that, if i convert my input 'choice' into a char, my error messages are:
Type mismatch: cannot convert from String to char
Incompatible operand types char and String
any idea whats wrong? Thanks!
*If I leave it like this it just gives me "Invalid Choice"
import java.util.*;
public class P1 {
public static void main(String[] args) {
// Create a scanner
Scanner userInputScanner = new Scanner(System.in);
String choice = userInputScanner.nextLine();
System.out.println("Your choice is " + choice);
if ((choice == "A") || (choice == "a"))
System.out.println( " Action Movie Fan");
else if ((choice == "C") || (choice == "c"))
System.out.println( " Comedy movie fan ");
else if ((choice == "D") || (choice == "d"))
System.out.println(" Drama movie fan ");
else
System.out.println( "Invalid choice" );
}
}
You compare strings in Java using equals:
if ("A".equals(choice) || "a".equals(choice)) {
...
}
or equalsIgnoreCase:
if ("A".equalsIgnoreCase(choice)) { // "a".equalsIgnoreCase(choice) works too
...
}
However, in your case you need to compare a single character, so you can do this:
if (choice.length() == 1) {
// Convert to upper case for case insensitivity
char selection = Character.toUpperCase(choice.charAt(0));
switch (selection) {
case 'A':
...
break;
case 'C':
...
break;
case 'D':
...
break;
}
...
}
For your case, try to use String.equalsIgnoreCase.
You might want to explore usage of Enum as well.
import java.util.*;
public class P1 {
public static void main(String[] args) {
// Create a scanner
Scanner userInputScanner = new Scanner(System.in);
String choice = userInputScanner.nextLine();
System.out.println("Your choice is " + choice);
if (choice.trim().equalsIgnorecase("A"))
System.out.println( " Action Movie Fan");
else if (choice.trim().equalsIgnorecase("B"))
System.out.println( " Comedy movie fan ");
else if (choice.trim().equalsIgnorecase("D"))
System.out.println(" Drama movie fan ");
else
System.out.println( "Invalid choice" );
}
}
otherwise compare only first character of string like choice.charAt(0) == 'A'
What you should know is that "A" and "a" are not chars, they are Strings. What you should do is call String's equals() (and not the == operator) method to compare. Just like that:
if(stringOne.equalsIgnoreCase("A")) {
//methods
}