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
}
Related
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.");
}
}
}
I'm trying to create a program where it switches the variables depending on, in this case, as an example, what animal you've chosen. Without having to use the print command twice.
For example. I created two strings:
String thingsForDogs = "bone";
String thingsForCats = "yarn";
And those strings would switch with each other, when printing out the result, depending on what the user chose as an animal. I don't know how I would code this, but if the user chose Cat as their animal, they would get a different output than if they've chosen Dog.
I know I could do something like this:
System.out.println("What animal do you want to be? Dog or cat?");
Scanner kb = new Scanner(System.in);
char choice = kb.nextLine().charAt(0);
if(choice == 'c' || choice == 'C')
System.out.println("You have " + thingsForCats);
else if(choice == 'd' || choice == 'D')
System.out.println("You have " + thingsForDogs);
But I still don't know how I could do it, without having to repeat the print command. I'm trying to print it all in one print command, but the variable along with it being printed, is switched, depending on what the user chose as their animal.
There is nothing wrong with your code.
You may change it wo a swich:
System.out.print("You have ");
switch(choice){
case "c":
case "C":
System.out.println(thingsForCats);
break;
case "d":
case "D":
System.out.println(thingsForDogs);
break;
default:
// some errorhandling or Stuff
}
You could use a HashMap to store that data and avoid the if-statement all together.
HashMap<char, String> map = new HashMap();
map.add('c', "yarn");
map.add('d', "bone");
...
// convert the input to lower case so you don't have to check both lower
// and upper cases
char choice = Character.toLowerCase(kb.nextLine().charAt(0));
System.out.println("You have " + map.get(choice));
There you have, one line printing
String thingsForPet = "";
System.out.println("What animal do you want to be? Dog or cat?");
Scanner kb = new Scanner(System.in);
char choice = kb.nextLine().charAt(0);
thingsForPet = Character.toLowerCase(choice) == 'c' ? "yarn" : "bone";
System.out.println("You have " + thingsForPet);
Considering your comment you can change last 2 lines as:
if(choice == 'c' || choice == 'C') {
thingsForPet = "yarn";
}
else {
thingsForPet = "bone";
}
System.out.println("You have " + thingsForPet);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am making a basic guessing game for my first java test and i have same by an interesting problem. My if statement isn't doing what it is told but when i trace it, the outputs are the same. My Code is... ;
import java.util.Scanner;
public class Game {
public static void main(String[] arg) {
Scanner GetInput = new Scanner(System.in);
try {
String Word;
String Guess;
int attempts = 0;
boolean win = false;
System.out
.println("Hello, and welcome to the guessing game! This game is very simple; one player will enter a word when");
System.out
.println("asked, then the next player will need to guess the word Be warned player two, you only have three guesses");
System.out
.println("Let's get started. Player ONE, please enter you're word: ");
Word = GetInput.next();
System.out
.println("Okay the word has been entered, now player TWO must guess");
do {
Guess = null;
System.out.println("Guess the word: ");
Guess = GetInput.next();
System.out.println(Guess + "/" + Word);
if (Word == Guess) {
System.out.println("You won!");
break;
} else if (Guess != Word) {
attempts ++;
}
if (win == false && attempts == 3) {
System.out.println("You lose!");
break;
}
} while (attempts <= 3);
} finally {
GetInput.close();
}
}
}
you can't use == to compare strings. use equals method
this code Word == Guess will not compare Word and Guess objects for equality
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.