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

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)) {

Related

.class Expected error in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
I get only two errors of .class expected I am getting this error in my program
String[] email= {"Sarangmemon8","Alimutaba626","Kali_denali"};
String[] pass= {"Sarang","Mujtaba","Kali"};
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("Hello! "+name +"Would you like to Login? y/n");
String ans = input.nextLine();
if(ans=="y"){
System.out.println("Enter your Email: ");
String username = input.nextLine(email[0][1][2]);
System.out.println("Enter your Password: ");
String password = input.nextLine(pass[0][1][2]);
if(username == email[]) {
if (password == pass[]) {
System.out.println("Hello Mr. " +name);
}
else
System.out.println("Wrong password");
First of all i would highly recommend you to go through your concept of
Arrays and Objects
1st Error:
Your index should be specified while trying to retrieve a value from a array.
You need to mention the index of the array if you want to compare.
Second Error: String is treated as a object in java, and while comparing with object equals() method is used, that's why while equating string use .equals() instead of == .
If you have anymore problem you can comment.
(username == email[] - incorrect syntax. You should specify index value for email array. E.g. email[0].
The same applies to password == pass[]

java easy ifs worng output [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I am new to java, and currently Im playing around with simple if statments. I have two questions.
x
First one: if answer yes, the last statment "You need to answer yes or no" is printed anyway. I only want it to print if the answer is something other than yes or no.
Second question. If I answer "maybe" (or something that is not yes/no the system print "You have to answer yes or no" and quits. How can a jump back to the first line and ask "are you doing good) once more?
import java.util.Scanner;
public class ovingto {
public static void main (String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.printf("Are you doing good?");
String ord = keyboard.nextLine();
if (ord.equalsIgnoreCase("yes")) {
System.out.println ("nice to hear!");
}
if (ord.equalsIgnoreCase("no")) {
System.out.println ("that makes me sad!");
} else {
System.out.println ("you need to answer yes or no");
}
}
}
The answer to both the questions ..
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.printf("Are you doing good?");
String ord = keyboard.nextLine();
if (ord.equalsIgnoreCase("yes")) {
System.out.println ("nice to hear!");
break;
}
else if (ord.equalsIgnoreCase("no")) {
System.out.println ("that makes me sad!");
break;
}
else {
System.out.println("you need to answer yes or no");
}
}
}
to redirect use the above code.. also there are many other ways to do it
You need to chain your if/else statements to achieve the effect you want.
Change the code to look like this:
import java.util.Scanner;
public class ovingto {
public static void main (String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.printf("Are you doing good?");
String ord = keyboard.nextLine();
if (ord.equalsIgnoreCase("yes")) {
System.out.println ("nice to hear!");
}
else if (ord.equalsIgnoreCase("no")) {
System.out.println ("that makes me sad!");
}
else {
System.out.println ("you need to answer yes or no");
}
}
}
You are missing an else.
try,
if (ord.equalsIgnoreCase("yes")) {
System.out.println ("nice to hear!");
}
else if (ord.equalsIgnoreCase("no")) {
System.out.println ("that makes me sad!");
}
else {
System.out.println ("you need to answer yes or no");
}
For the 2nd question the best choice is a do-While loop.

My boolean always comes up correct [closed]

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

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