Twenty Questions - Programming by Doing [duplicate] - java

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.");
}
}
}

Related

How can I create an if statement with 3 conditions? (Java)

I just started learning java a week ago. I am taking a class at my school. I am trying to create a quiz and I can't figure out how to print out the score. The quiz has three possibilities 3/3, 2/3, 1/3. The problem I am having is with the if statements near the end of the program.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class t1_lesson03_template{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("1. What do you type at the begining of a comment?");
String answer1 = "//";
String userinput1 = scan.nextLine();
if (userinput1.equals(answer1)) {
System.out.println(" Correct!");
}
if (!userinput1.equals(answer1)) {
System.out.println(" Wrong!");
}
String answer2 = ("(int)");
System.out.println("2. What do you type before a double to convert to an int?");
String userinput2 = scan.nextLine();
if (userinput2.equals(answer2)) {
System.out.println(" Correct!");
}
if (!userinput2.equals(answer2)) {
System.out.println(" Wrong!");
}
String answer3 = ("int number = 5;");
System.out.println("3. Create an int called \"number\", and make it equal 5.");
String userinput3 = scan.nextLine();
if (userinput3.equals(answer3)) {
System.out.println(" Correct!");
}
if (!userinput3.equals(answer3)) {
System.out.println(" Wrong!");
}
if (userinput1.equals(answer1) && userinput2.equals(answer2) && userinput3.equals(answer3)) {
System.out.println("3/3 Awesome!");
}
else if (userinput1.equals(answer1) || userinput2.equals(answer2) || userinput3.equals(answer3)) {
System.out.println("2/3 Good job.");
}
else {
System.out.println("1/3 Try again.");
}
}
}
This,
else if (userinput1.equals(answer1) || userinput2.equals(answer2)
|| userinput3.equals(answer3)) {
should be something like
else if ((userinput1.equals(answer1) && userinput2.equals(answer2)) ||
(userinput1.equals(answer1) && userinput3.equals(answer3)) ||
(userinput2.equals(answer2) && userinput3.equals(answer3))) {
but I would prefer a count. And an array to display your different messages. Something like
int count = 0;
if (userinput1.equals(answer1)) {
count++;
}
if (userinput2.equals(answer2)) {
count++;
}
if (userinput3.equals(answer3)) {
count++;
}
String[] result = { "0/3 None", "1/3 Try Again.", "2/3 Good Job.", "3/3 Awesome!" };
System.out.println(result[count]);
Just add braces before each condition in if class and else if such as
if ((userinput1.equals(answer1)) && (userinput2.equals(answer2)) && (userinput3.equals(answer3))) {
System.out.println("3/3 Awesome!");
}
else if ((userinput1.equals(answer1)) || (userinput2.equals(answer2)) || (userinput3.equals(answer3))) {
System.out.println("2/3 Good job.");
}

java: method correctOutOf in class littleQuiz cannot be applied to given types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My goal is to store the amount of correct answers into the 'correctOutOf' method, which will then return the value of corrAns when called int the /*Wrapping Up*/ section of the example code below:
import java.util.Scanner;
public class littleQuiz {
public static void main(String[] args){
Scanner key = new Scanner(System.in);
char yesno;
int answer;
/*Welcome/Splash Screen*/
/*Ask if ready and accept yes or no with appropriate return response*/
System.out.print("Are you ready for a quiz? Y or N ");
yesno = key.next().charAt(0);
if (yesno == 'Y'){
/*affirmative response*/
System.out.println("Okay, here it comes!");
}
else{
/*negative response*/
System.out.println("What a wimp...");
System.exit(0);
}
/*Quiz Section*/
/*Question 1*/
System.out.println("Q1) What is the capital of Alaska?");
System.out.println(" 1) Melbourne\n" +
" 2) Anchorage\n" +
" 3) Juneau");
answer = key.nextInt();
if (answer == 3){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 2*/
System.out.println("Q2) Can you store the value 'cat' in a variable of type int?");
System.out.println(" 1) yes\n" +
" 2) no");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 3*/
System.out.println("Q3) What is the result of 9+6/3?");
System.out.println(" 1) 5\n" +
" 2) 11\n" +
" 3) 15/3");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Wrapping Up*/
System.out.println("Overall, you got " + correctOutOf() + " out of 3 correct.");
System.out.println("Thanks for playing!");
}
/*not sure of which access modifier to use, but none have fixed it*/
private static int correctOutOf(int answer) {
return corrAns;
}
}
I'm feeling pretty positive that my if statement is going to feed the 'correctOutOf' method simply because it is the only part of the statement that can check for a correct answer with the code as-is. (just so everyone knows my train of thought.)
Edit - if this is something more than a beginner should be messing with, thanks for pointing it out. (Biting off more than I can chew?)
Don't do that, do this at the start of main:
byte correct = 0;
Or this if you ever need to use it outside of main:
private static byte correct = 0;
Then add this to each correct answer if statement:
correct++;
And print the variable "correct".
...also, you may wish to add this function to your program, to replace "key.nextInt()", to prevent the user from crashing your program:
import java.util.regex.*;
private static final int integer() {
boolean invalid = true;
int number = 0;
while (invalid) {
String input = key.next();
if (input.matches("\\d+")){
invalid = false;
try {
number = Int.parseInt(input);
} catch (java.lang.NumberFormatException e) {
invalid = true;
System.out.print("Are you trying to break the program? Try again: ");
}
} else {
System.out.println("That's not a whole number! ");
System.out.print("Try again: ");
}
}
return number;
}

Keep receiving the same two errors: illegal and parsing error

I'm not entirely sure what I'm doing wrong at this point. I've been getting the same two errors:
CoffeeBot.java:79: illegal start of expression
}
CoffeeBot.java:82: reached end of file while parsing
} //public class
2 errors
Someone correct me thanks?
import java.util.Scanner ;
public class CoffeeBot {
public static void main(String[] args) {
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
for (int i = 0;i<args.length;i++) // REMEMBER TO PUT IN ARGS LENGTH
if (!(n1 > 0) && !(n2 > 0)) { // This is for both negative inputs n1 and n2
System.out.println("Negative supply chain. System terminating.");
return;
}
if (n1 < 0) { // This is for negative input n1
System.out.println("Negative supply of coffee cups. System terminating.");
return;
}
if (n2 < 0) { // This is for negative input n2
System.out.println("Negative supply of coffee shots. System terminating.");
return;
}
else {// If inputs comply with rules then proceed to here
System.out.println("Hello, what's your name?");
String name;
Scanner keyboard = new Scanner(System.in);
name = keyboard.next();
System.out.println("Would you like to order some coffee, " + name + "? (y/n)");
String yesno;
yesno = keyboard.next();
if (yesno.equalsIgnoreCase("y")) {
System.out.println("Great! Let's get started.");
System.out.println(" ");
System.out.println("Order selection");
System.out.println("---------------");
System.out.println(" ");
}
if (yesno.equalsIgnoreCase("n")) {
System.out.println("Come back next time, " + name +".");
return;
}
else {
System.out.println("Invalid response. Try again.");
while (yesno.toIgnoreCase("n"))
while (yesno.toIgnoreCase("y"))
}
}//else
} //main args
} //public class
yesno is of type String.
while (yesno.toIgnoreCase("n"))
while (yesno.toIgnoreCase("y"))
there is no toIgnoreCase() method , i guess you meant equalsIgnoreCase().also put ; after the 2nd while loop better yet use {} all the time.

MasterMind-Resource Leak?

My code is running fine, but every line where I use a scanner it warns me that there is a "Resource leak; 'userGuess' is never closed" I don't understand what it means and could use some help solving it. Also if there is anything else in my code worth fixing I could use the help. Be warned I have a limited knowledge of Java programming. I also cannot get my TryCounter++ to work...
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
Thank you for the Help!
The error message is telling you that you never call the close() method on your Scanner object. A worse problem is that you create multiple Scanners when you only need one.
As for tryCounter not working...
while(tryCounter<9 || !guessedAll)
This will keep looping if either part of the condition is true. My guess is that !guessedAll is evaluating to true beyond 9 guesses, so your loop keeps running. You'll need to change the || to an && to get it stop looping after 9 tries. (Also, print out the values of your variables or use a debugger so you can verify that they are changing when you expect them to.)

My Java Program is not working [duplicate]

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.

Categories