My boolean always comes up correct [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
In my following piece of code I am looking to compare a piece of a text file.
However, for some reason, no matter what the user types in the value comes up
correct.
I'm trying to compare the value without worrying about its case or about any
leading or trailing white space.
// Display the question to the user
System.out.println("Question: " + myList.get(random1));
// Accept user input
System.out.print("Please type your answer: ");
// Store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
// Display the officially correct answer from the arraylist
System.out.println("Answer: " + myList.get(random1 +1));
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(myList.get(random1 + 1).contains(answer) == false) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You suckkkkkkk");
}
// Display total accumulated points
System.out.println("Your total points are: " + totalScore);
// Wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
scanner.nextLine();

Try this.
// Display the officially correct answer from the arraylist
String correctAnswer = myList.get(random1 +1);
System.out.println("Answer: " + correctAnswer); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer.equalIgnoreCase(answer)) { // efficient than contains() method
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You suckkkkkkk");
}

Related

Java: if statement with not equals breaking the program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I can't figure out why my code isn't working.
It appears to be breaking around the if not equal to yes or no area.
Here's my code:
public static void main(String[] args) {
// TODO code application logic here
Scanner user_input = new Scanner(System.in);
String name;
System.out.println("Hello, what is your name?");
name = user_input.next();
System.out.println("");
String name_answer;
System.out.println("Your name is " + name + ". Is this correct? (yes/no)");
name_answer = user_input.next();
System.out.println("");
if (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next();
while (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next(); } }
if (name_answer.equals("yes")) {
System.out.println("Thank you, " + name + ". Please proceed to the next question.");
} else if (name_answer.equals("no")) {
System.out.println("Please reinput your name correctly.");
while (name_answer.equals("no")) {
String name_again;
System.out.println("");
System.out.println("What is your correct name?");
name_again = user_input.next();
System.out.println("");
System.out.println("Your name is " + name_again + ". Is this correct? (yes/no)");
name_answer = user_input.next(); }
If i comment out the not-equals block of code (displayed below), the program works. However, with the block of code in, the program breaks.
if (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next();
while (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next(); } }
My goal is to have any answer not equal to "yes" or "no" be reinputted while a "yes" or "no" brings the program to another step. Thanks for the help.
The technical problem with your code is that you're using concatenation instead of logical operators. "yes" + "no" evaluates to "yesno", which will probably never match your input string.
More fundamentally, the problem is that you're trying to bundle two boolean evaluations into one. Logically, you want to proceed if the answer is not "yes" and the answer is not "no". In Java syntax:
if (!name_answer.equals("yes") && !name_answer.equals("no")) {
If you want to test multiple values at a time, you can use this shortcut:
if (!Arrays.asList("yes", "no", "foo", "bar").contains(name_answer)) {

Need to exit a loop once the correct input is entered

Please see my code below for a quiz game. I have been trying to figure out for 2 days now how to correctly code the loop at the option menu. Once I know how to code it correctly I would be able to code in the rest of the loops I need for the other questions.
The way I have it coded right now it gets stuck on "Invalid selection, please try again." infinitely.
Someone please help me with the correct code. :(
Everything I've been able to find related to this utilizes Scanner input instead of the JOptionPane.
package team1;
//this is required for JOptionPane to work
import javax.swing.JOptionPane;
//this allows for exception throwing
import java.io.*;
public class GameV2 {
public static void main(String[] args) throws IOException {
/**
* Version 2 Updates:
* - added 2 more sets of questions and answers
* - created a decision structure to determine the path of the game based on +
the user's menu choice
* - created a decision structure to indicate whether to the user whether an +
answer is correct or incorrect.
* - added point values to each question and a totalScore accumulator which +
displays at the end of the game.
*/
// display an introduction to the game.
JOptionPane.showMessageDialog(null, "Welcome to Team 1's Game Version 2!");
// prompt the user for his/her first name
String firstname;
firstname = JOptionPane.showInputDialog("What is your first name?");
// prompt the user for his/her last name
String lastname;
lastname = JOptionPane.showInputDialog("What is your last name?");
// display a customized hello message to the user
JOptionPane.showMessageDialog(null, "Hi, " + firstname + " " + lastname + "!");
**// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules and Play the Game\n"
+ "2) Play the Game\n"
+ "3) Exit\n"
+ "Please enter your choice: (1 or 2 or 3) ";
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
// display the rules
String rules = "Rules:\n"
+ "The game will display total 3 multiple choice questions," +
" with 4 possible answers per question.\n"
+ "Once you answer the question, the correct answer will be displayed" +
" and the game will advance to the next question.\n"
+ "If you answer the question correctly, you will gain a point.\n"
+ "Each point is added to a total score that will be displayed at the" +
"end of the game.\n";
// declare an integer that reads the user input
int numericChoice = Integer.parseInt(userChoice);
boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);
if (numericChoice == 1){
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
}
else if (numericChoice == 2){
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
}
else if (numericChoice == 3){
// exit the game
System.exit(0);
}
while (!valid){
JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
JOptionPane.showInputDialog(menu);
continue;
}
To make your implementation work like you intend to you should rewrite your loop, e.g. like the following:
boolean valid = false;
do {
final String userChoice = JOptionPane.showInputDialog(menu);
final int numericChoice = Integer.parseInt(userChoice);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
if (numericChoice == 1) {
valid = true;
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
} else if (numericChoice == 2) {
valid = true;
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
} else if (numericChoice == 3) {
valid = true;
// exit the game
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
}
} while (!valid);
You should also remove the lines
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
before the loop because they will be executed inside of it.
If you do it like that than your loop has the following cycle:
Get and store user input (userChoice and numericChoice*)
Show user their input
Handle input
if 1 or 2 or 3 set valid to true and continue according to choice
or
Show an error and repeat from step 1
* You should think about handling the case when userChoice can not be parsed into a number

trying to add more ints to one main one [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 9 years ago.
Improve this question
hi i'm trying to make a questions game to try my knowledge and abilities
anyway i'm trying to use an integer to be the points and every question the user
answer gets a special amount of points anyway i was trying to do like this
switch (Ques){ case 1 : //first question about India and where it is in the map
System.out.println("in what continent India is?");
Scanner IndiaAns = new Scanner(System.in); //Scanner to receive user answer
String IndiaAns2 , IndiaAnswer ; //strings to be used to receive user input and matching with the correct ones
IndiaAns2 = IndiaAns.nextLine(); //Scanner will work here and receive...
IndiaAnswer = "asia"; //the correct answer here and will be matched with user ones
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
case 2:
System.out.println("the Appstore founds in any phone model?");
Scanner Appstore =new Scanner(System.in);
String AppstoreAns1 ,AppstoreAns2; //strings saving
AppstoreAns1 = Appstore.nextLine(); //Scanner
AppstoreAns2 = "iphone"; //matching with user answer
if (AppstoreAns1 == AppstoreAns2)
{ int Threepoints = 3; Points = +Threepoints;} else { Points = +0;}
.. there's two other case and the points integer is in not in the code sample area is in upper line any ways if the full codes its necessary i'll put it
About your code ,
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
Should be something like
if(indiaAns2.equals(indiaAnswer)){
points += QUESTION_1_POINTS;
}
Where QUESTION_1_POINTS is defined as a constant like `
public static final int QUESTION_1_POINTS =2;
There you are assigning to points variable , points + QUESTION_1_POINTS.
points += someInteger --> points = points + someInteger
Some advices,
1) Follow Java Code Conventions , variable names start with lower-case
2) For object comparision always use equals() instead of ==
Example:
Change
if (IndiaAns2 == IndiaAnswer)
to:
if (indiaAns2.equals(indiaAnswer))
3) You need to make switch statement
switch(condition){
case 1:
//code
break;
case 2:
//code
break;
default:// some code;
}

I need to figure out the logical bug in my Code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
when I call the method "getUnknownsAccel" with the problem1 object, for some reason the 'if' statement in the method is not executed to retrieve the value of the variable:
PhysicsProblem problem1 = new PhysicsProblem(accel, vI, vF, t, deltaX);
System.out.println("Which variable are you solving for? ");
String solveFor = scan.next();
// after receiving solveFor input, assesses data accordingly
if (solveFor.equalsIgnoreCase("acceleration"))
{
System.out.println("Solving for Acceleration!");
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.next();
problem1.setMissingVar(missingVar);
do
{
problem1.getUnknownsAccel();
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.next(); //// change all these in the program to scan.next, not scan.nextLine
}
while (!missingVar.equalsIgnoreCase("none") || !missingVar.equalsIgnoreCase("acceleration"));
if (missingVar.equals("none"))
{
// Write code for finding solutions
System.out.println("Assuming you have given correct values, the solution is: ");
}
}
After the do/while loop used to retrieve the name of the other variables that are unknown, I call the getUnknownsAccel method from this class file:
public void getUnknownsAccel()
{
//-----------
// checks for another unknown value that is not accel
//-----------
if (missingVar.equalsIgnoreCase("time"))
{
System.out.println("Please enter the value for time: ");
t = scan.nextDouble();
while (t <= 0 || !scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
t = scan.nextDouble();
}
}
}
Let's assume for the sake of this problem, that the user WILL enter "time" as the unknown when prompted. Any idea why my code isn't executing the scan function to retrieve the time variable value? Instead, the program just repeats the system.out function "Are there any other unknowns..."
After scanning, you set missingVar to scan.next(), but you do not do anything. The loop continues.
After
missingVar = scan.next();
add the line
getUnknownsAccel();
Note, another issue is that you will need to handle later is that missingVar is local - to access it in getUnknownsAccel(), you should change the declaration to
public void getUnknownsAccel(String missingVar){
}
and instead use
getUnknownsAccel(missingVar);

how to create a counter in a dr Java program

/*This is a quiz program that will ask the user 10 questions. the user will answer
* these questions and will be scored out of 10.*/
class Quiz {
public static void main(String args[]) {
// Instructions
System.out.println("instructions");
System.out.println(" ");
System.out
.println("1. You wll be asked ten questions through out the quiz.");
System.out
.println("2. The first question will appear, you will have to answer that question for the next question to appear.");
System.out
.println("3. When you answer the last question you will be told your score.");
System.out.println(" ");
System.out.println("welcome to the basketball quiz.");
// question 1
System.out.println(" ");
System.out.println("Question 1. ");
System.out.println("How tall is a basketball hoop? ");
System.out.println("Type in Answer here:");
String Question1 = In.getString();
if (Question1.equalsIgnoreCase("10 Feet")) {
System.out.println("Correct!");
} else {
System.out.println("you got this questions wrong");
}
// question 2
System.out.println(" ");
System.out.println("Question 2. ");
System.out.println("Who invented basketball? ");
System.out.println("Type in Answer here:");
String Question2 = In.getString();
if (Question2.equalsIgnoreCase("James Naismith ")) {
System.out.println("Correct!");
} else {
System.out.println("you got this questions wrong");
}
}
}
This is my program that I am writing. I want to make a counter that will keep score of every question that is answered right and then display it to the user after the questions are finished. I tried using this:
int score=0;
score=score+1;
It doesn't not work for the 2nd question, but works for the 3rd... it gives me an error.
Is there another way I can do this or am I doing something wrong?
It looks like you are on the right track. You need to declare a socre variable at the begiunning of the program.
int score = 0;
Then in each question where you print out "correct" you can increment the score like this:
score++;
At the end of the program after the last question you can print the score.
Maybe you should post the error you got when you tried it.
UPDATE:
The syntax is score++ NOT score=++. That is, take out the = sign.
What you did is correct. Heed the comment on your post; you need semi-colons at the end of your posted solution. Also, per the Java Language Specification, it's best to name your variable with all lower case characters:
int score = 0;
// question code
score += 1;
or
score = score + 1;
or
score++;
You need to place the variable declaration (int score = 0;) outside of any loops (your if/else loops). It would be best to place it at the first line of the main method.
Your problem is possible because you have a whitespace character after the name "James Naismith" in the comparison for their given answer. For it to be evaluated to true the user must answer with the exact string "James Naismith " instead of "James Naismith"
Edit: Nevermind, This should not cause an error but it is something to bring your attention to still because it could affect the result of the program.

Categories

Resources