This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I've just started java couple of days ago. Im currently following this 'course' http://programmingbydoing.com . Havent had encountered any problems yet but now im stuck at task 32.
heres my code so far (always getting Squirrel instead of moose as output):
import java.util.Scanner;
public class TwoQuestion32 {
public static void main(String[] args) {
boolean animal, vegetable, mineral, smallerthan;
String whatIsIt, biggerThan;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello and welcome, i've got 2 questions for you!");
System.out.println("Think of an object and i'll try to guess it");
System.out.println();
System.out.println("Question 1) Is it an animal, vegetable or mineral?");
System.out.print(">");
whatIsIt = keyboard.nextLine();
if (whatIsIt == "animal")
animal = true;
if (whatIsIt == "vegetable")
vegetable = true;
if (whatIsIt == "mineral")
mineral = true;
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print(">");
biggerThan = keyboard.nextLine();
if (biggerThan == "yes")
smallerthan = false;
if (biggerThan == "no"){
smallerthan = true;}
System.out.print("My guess is that you are thinking of a ");
if (animal = true){
if (smallerthan = true)
System.out.println("squirrel");
}else {
System.out.println("moose");}
}
}
Thanks in advance! Would also love to hear tips how to put up the code in smarter ways. Be friendly, keep in mind i've just started!
Edit: Okay I took another approach. My first attempt was really strange. Thanks for the help!
Heres the working code:
import java.util.Scanner;
public class Questions32 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String whatIsIt, whatIsIt2;
String animal = "animal";
String mineral = "mineral";
String vegetable = "vegetable";
String bigger = "yes";
String smaller = "no";
System.out.println("Hello and welcome, i've got 2 questions for you!");
System.out.println("Think of an object and i'll try to guess it");
System.out.println();
System.out.println("Question 1) Is it an animal, vegetable or mineral?");
System.out.print(">");
whatIsIt = keyboard.nextLine();
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print(">");
whatIsIt2 = keyboard.nextLine();
if (whatIsIt.equalsIgnoreCase(animal)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a moose");
}else{ System.out.println("My guess is that you are thinking of a squirrel");
}
}
if (whatIsIt.equalsIgnoreCase(vegetable)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a melon");
}else{ System.out.println("My guess is that you are thinking of a carrot");
}
}
if (whatIsIt.equalsIgnoreCase(mineral)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a Camaro");
}else{ System.out.println("My guess is that you are thinking of a paper clip");
}
}
System.out.println("I would ask you if I'm right, but I dont actually care.");
}
}
in your if-statement you are setting animal to true every time if (animal = true){, instead of checking it (==) .
Also, for Strings you must use .equals() instead of ==.
Related
The code is for multiple choice question. If the answer is incorrect, the user should try until they find the right answer. When the answer is correct, there is no problem, but if it is wrong then it gets stuck, and it is keep saying "Your answer is incorrect!". What should I do?
import java.util.*;
public class Question {
public static void main(String[] args) {
System.out.println();
System.out.println("Question 1");
System.out.println();
System.out.println("What is 2+2?");
System.out.println("A. 2");
System.out.println("B. 4");
System.out.println("C. 6");
System.out.println("D. 8");
Scanner input = new Scanner(System.in);
char getAnswerFromUser = input.next().charAt(0);
char answer = 'B';
boolean isAnswerTrue = false;
while(!isAnswerTrue) {
if(getAnswerFromUser == answer ) {
System.out.println("Your answer is correct!");
isAnswerTrue = true;
} else{
System.out.println("Your answer is incorrect!");
isAnswerTrue = false;
}
}
}
}
You are not actually getting a new answer from the user inside your loop. You are only getting it once, in the line where you define the variable getAnswerFromUser. You need to actually get a new answer. I suggest putting it into a separate method to keep that step clean from the step where you use that answer.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This a simple program that asks the user for two questions. Based on the user's input, we will display a guess of what the object is. Similar to the game "20 Questions". No matter what input I give the program, it always returns the value of myGuess as "paper clip"
I have tried commenting out the inside of each if/else statement and having the output set to 1,2,3 but it still gets to 3 ( the block of the paper clip). This leaves me to think that my comparison of strings has a bug either in the assignment of the user input or conditional logic... Here is the code:
import java.util.Scanner;
public class JavaTraining {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input1,input2;
String myGuess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.\r\n");
System.out.println("Question 1) Is it an animal, vegetable, or mineral?");
input1 = keyboard.nextLine();
System.out.println("\r\nQuestion 2) Is it bigger than a breadbox?");
input2 = keyboard.nextLine();
if (input1 == "animal"){
if (input2 == "yes"){
myGuess = "moose";
}
else{
myGuess = "squirrel";
}
}
else if (input1 == "vegetable"){
if (input2 == "yes"){
myGuess = "watermelon";
}
else{
myGuess = "carrot";
}
}
else{
if (input2 == "yes"){
myGuess = "Camaro";
}
else{
myGuess = "paper clip";
}
}
System.out.println("\r\nMy guess is that you are think of a "+myGuess+".\r\nI would"
+" ask you if I'm right, but I don't actually care."+input1+input2);
}
}
Use .equals() for strings instead of == . Java strings are objects not primitive data types.
change this
if (input1 == "animal")
to
if(input1.equals("animal"))
Take a look at this link
I'm trying to make a BAC (blood alcohol content) calculator that takes inputs from the user and lets them know if they qualify to win... a grand DUI prize! I'm trying to use the Scanner to determine if the person is a male or female and then use an if-then statement down the line based on what the user input...but I don't really know how. It should be a very simple fix, but here's what I have and kinda what I want to do with the if-then statement commented out.
import java.util.*;
public class Proj2_Mazzone
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String gender;
int D, W, H, age;
...
System.out.print("Enter M if you're a male, or F if you're a female: ");
gender = scan.nextLine();
/*if(gender = M)
{
System.out.println("You're a man!");
}
else if(gender = F)
{
System.out.println("You're a woman!");
}
*/
When comparing String you use .equals() or .equalsIgnoreCase(). Like,
gender = scan.nextLine();
if (gender.equalsIgnoreCase("m")) {
System.out.println("You're a man!");
} else if (gender.equalsIgnoreCase("f")) {
System.out.println("You're a woman!");
}
But, you could also compare the first character with something like
if (Character.toUpperCase(gender.charAt(0)) == 'M') {
System.out.println("You're a man!");
} else if (Character.toUpperCase(gender.charAt(0)) == 'F') {
System.out.println("You're a woman!");
}
note, that's == (not = which is for assignment).
Use like this:
if(gender.equals("M"))
{
System.out.println("You're a man!");
}
else if(gender.equals("F"))
{
System.out.println("You're a woman!");
}
Note: = is assign operator not conditional operator.
You can see how equal condition is work in java at below link.
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
What's the difference between ".equals" and "=="?
Background: Beginner in programming, very new to this whole "Java" thing.
I love the help, but I do not want a direct answer, more like a point in the right direction, or any which way where I can learn instead of blindly copy/paste. Instead of "heres the right code" more of "hears how you can get the right code"
Thank you :)
Ok so my question is, what is wrong with the prompt ad the IF/THEN statement. When I run it with the prompt, it says cannot find symbol - method prompt(java.lang.String)
Without the prompt, when I run it, after I input my choice, whether right or wrong, it always returns "Sorry, that is'nt a choice. Choose rock, paper or scissors!" even if it is right!
If you need any more info on my problem, let me know :)
Anyway here is the class:
//Player class
import java.util.Scanner;
import java.lang.String;
public class Player
{
private String name;
private String choice;
public Player(String nm)
{
name = nm;
}
public Player(String nm, String ch)
{
name = nm;
choice = ch;
}
public void setName( String nm)
{
name = nm;
}
public void setChoice( String ch )
{
}
public String getChoice()
{
Scanner scan = new Scanner (System.in);
System.out.println("Choose rock, paper or scissors:");
String player = scan.next(); player.toLowerCase();
if ((player != ("rock"))
|| (player != ("paper"))
|| (player != ("scissors")))
{
System.out.println("Sorry, that is'nt a choice. Choose rock, paper or scissors!");
player = prompt("Choose rock, paper or scissors:");
}
else
{
System.out.println("Good choice!");
}
System.out.println("You chose " + player);
return "";
}
public String getName()
{
Scanner scan = new Scanner (System.in);
System.out.println("Whats your name?");
String name = scan.next();
return "";
}
public String toString()
{
return "";
}
}
And the runner:
public class PlayerRunner
{
public static void main(String[] args)
{
Player s = new Player("Michael Jackson", "rock");
System.out.println(s.getChoice());
System.out.println(s.getName());
//outs rock
//call the getName() method
System.out.println(s); //outs Michael Jackson rock
//set the choice to paper
System.out.println(s); //outs Michael Jackson paper
//instantiate a new Player named jb named Jim Bob that chose scissors
//print out Jim Bob
}
}
The goal of this portion was titled to: "Use the Player.java file to create the player. Complete the Player constructors, set
methods, get methods, and the toString. Use PlayerRunner.java to test your Player class."
Let me know if you see that I did anything else wrong :) Again I'm a beginner, but I'm here to learn, not just paste the right answer and move on.
Thank you!!
How about:
public String getChoice() {
Scanner scan = new Scanner(System.in);
System.out.println("Choose rock, paper or scissors:");
String player = scan.next();
while ((!player.equalsIgnoreCase("rock"))
&& !player.equalsIgnoreCase("paper")
&& !player.equalsIgnoreCase("scissors")) {
System.out.println("Sorry, that is'nt a choice. Choose rock, paper or scissors!");
System.out.println("Choose rock, paper or scissors:");
player = scan.next();
}
System.out.println("Good choice!");
System.out.println("You chose " + player);
return "";
}
When you use the == operator, you're comparing whether or not two objects are the same, or whether two primitive type's values are the same.
Since a string is actually an object in Java,
String a = "string";
String b = "string";
System.out.println(a == b);
will return false, but
String a = "string";
String b = a;
System.out.println(a == b);
will return true.
Instead, if you call the equals method of the String class, you can compare whether or not the two values are the same.
String a = "string";
String b = "string";
System.out.println(a.equals(b));
In your case, player != ("rock") will always evaluate as true, which looks to be causing some problems.
You can read more here: Java String.equals versus ==
So I just started learning Java, its literally like my 1st day and I wanted to try to make a coinflip game. I already know a decent amount of Javascript and so i was trying to apply that knowledge to java. So everything has been working so far except one thing: Prompting a user for a choice. So read online that i have to import a scanner so i did that as you can see from my code. I also tried some code where you can have the user import a string but you can see a bit later in my program i change the variable userChoice into a number. So basically i just need help with this. If there is some way to have a variable type that can store both numbers or strings that would be best. But im tottaly open to other ways of doing this! Thanks in advanced! Here is the code:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi");
int bob;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
System.out.println("You entered "+ userChoice);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(userChoice == "Heads") {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!")
}
}
}
Use a scanner, as you said:
Scanner in = new Scanner(System.in);
Then, prompt the user to enter something in:
String userChoice = in.nextLine();
Also, when you compared strings:
if(userChoice == "Heads") {...
that's bad to do for none-primitive objects. It's best to only use the == to compare values that are ints or enums. If you compare a String like this, it won't work, because it's checking if the objects are the same. Instead, compare like this:
if(userChoice.equals("Heads")) {...
Also, to convert to an int (NOTE: You can't convert one type of object to another that aren't related in any way! You'll have to create a new object if you're wanting to do that), do this:
int myInt = Integer.parseInt(myString); // NOTE: Can throw NumberFormatException if non-number character is found.
So your program should look somewhat like:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
//System.out.println("hi");
Scanner in = new Scanner(System.in);
int bob;
int userChoice;
String input;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
input = in.nextLine(); // waits for user to press enter.
System.out.println("You entered "+ input);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(input.equals("Heads")) {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!");
}
in.close(); // IMPORTANT to prevent memory leaks
}
}
You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.
Scanner in = new Scanner();
userChoice = in.nextLine();
nextLine() can be used to input a character or a string from the user.
To convert the string into a integer, You can assign the integer value to the string in the following way.
if(userChoice == "Heads") {
userChoice = "" + 0;
}
else {
userChoice = "" + 1;
}
"String" datatype in Java can hold both numbers and strings (as you asked). You can get user input using Scanner utility as below:
Scanner input = new Scanner();
userChoice = input.nextLine(); // if it is a string
//userChoice = input.nextInt(); // if it's integer choice
If your string is an integer then you can also parse it to get its integer value. For parsing:
int value = Integer.parseInt(userChoice);
Also for comparing String values you should use "equals" function rather than "==".
if(userChoice.equals("Heads")){...} //rather than if(userChoice == "Heads"){...}
Having imported java.util.Scanner, to get input from the user as a String, create a Scanner object that parameterizes System.in and assign userChoice the value of nextLine() invoked by the Scanner object:
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
A few things about your code. The relational operator, ==, is used for comparing primitive data - not objects. Use string1.equals(string2) to see if two strings are equal.
Also, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2);
because casting a double as an integer truncates the double to the highest integer less than or equal to it.
It might help you to get the ideas.
public static void main(String[] args) {
Random rd = new Random();
//Enter 1 0R 0
int bob = rd.nextInt(2);
String userChoice;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number");
userChoice = sc.nextLine();
System.out.println("You entered " + userChoice + " and bob is " + bob);
int uc = Integer.parseInt(userChoice);
if (uc == bob) {
System.out.println("Hehe");
} else {
System.out.println("Sorry");
}
}