Issue with user input and .equals() in Java - java

I'm fairly new to java coding but the error is that if I type in the correct answer or the incorrect answer, it still says both Correct and Incorrect.
import java.util.Scanner;
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals(20));
System.out.println("Correct!");
if (!"20".equals(question));
System.out.println("Incorrect!");
}
}

Remove the semi-colons from the end of your if statements. It's treated as an empty line.
Or even use explicit curly braces, like if(foo) { bar(); }.

Your conditional if's are a little wrong, this should do it: (untested)
import java.util.Scanner;
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20"))
System.out.println("Correct!");
if (!"20".equals(question))
System.out.println("Incorrect!");
}
}
In your original code, you had ; at the end of the if's. Which informs the compiler that it's the end of the line. Hence why both "Correct!" and "Incorrect!" were being displayed. AS they weren't part of the conditional statement.
Hope this helps! :)

Find your solutions Brother.......
Tip: for String use "20" instead of 20
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20")){
System.out.println("Correct!");
}else{
System.out.println("Incorrect!");
}
}
}

Semicolon ends the if statement, so the statements below each if will always execute. In addition this: if (question.equals(20)) should be if (question.equals("20")) as the user input is String and you want to compare Strings.
The code should read as follows:
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20")) {
System.out.println("Correct!");
}
if (!"20".equals(question)) {
System.out.println("Incorrect!");
}
}
}
It is worth mentioning that the Scanner has other methods to read user input, e.g. you can read Integer instead of String like this: Integer answer = answer = user_input.nextInt(); And then you just compare Integers like:
if (answer == 20) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}

That is because you have a semicolon after the if. Remove it, and preferably put curly braces around the println statements to show which statements belong to the if. Right now, you have written
if (...); a;
Which is equivalent to
if (...)
{
}
a;
While what you meant is
if (...)
{
a;
}

Make it simple
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
System.out.println(user_input.next().equals("20") ? "Correct" : "Incorrect");

Related

Very Simple if else statements doesn't working. what im doing wrong?

I'm new to Java. I'm learning by myself without guide. Can anyone help me with this little piece of code? What am I doing wrong??
package Lessons;
import java.util.Scanner;
public class lesson1
{
public static void main (String []Args)
{
Scanner input = new Scanner (System.in);
int age;
System.out.println("How old are you?");
age = input.nextInt();
if (age >= 20);
System.out.print("You Passed!");
else
( age <= 20)
System.out.println("You Failed!");
}
}
The issue is in else. I'm working on Eclipse and I don't get any help solution from it on what to do.
First, you have ";" after if. Why?
Also you shouldn't write "else (...)", at least "else if(...)"
So, the correct code, if I understand right what you want is:
package Lessons;
import java.util.Scanner;
public class lesson1 {
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
int age;
System.out.println("How old are you?");
age = input.nextInt();
if (age >= 20) {
System.out.print("You Passed!");
}
else {
System.out.println("You Failed!");
}
}
}
It is recommended to add curly braces too see what if-else statements cover.
What you need however is to remove semicolon and remove boolean expression from else statement
Scanner input = new Scanner(System.in);
int age;
System.out.println("How old are you?");
age = input.nextInt();
// Added {} and removed ;
if (age >= 20) {
System.out.print("You Passed!");
// Added curly brackets and removed boolean expression
} else {
System.out.println("You Failed!");
}

Why deos my "While" loop keep going on?

My loop never stops, I can't seem to understand what is wrong. I'm doing
a project for my class and I'm new to loops so kind of confused. Please tell me how
to resolve this issue.
import java.util.Scanner;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); {
boolean Quit = true;
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them");
String answer = scan.nextLine();
while (Quit = true) {
if (answer.equals("Quit")){
System.out.println("Thanks forr running FracCalc!");
break;
} else {
System.out.println("I can only process 'Quit' for now");
}
}
}
}
}
Quit = true will assign true to Quit, and return true. Thus, you're doing while (true), a canonical infinite loop. And even if you were testing Quit == true (note double equality sign), you never assign it to false, as Izcd remarks. You could break out with your if, but answer is only assigned once, outside the loop.
Put String answer = scan.nextLine(); inside the loop.
Try the following:
import java.util.Scanner;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them");
String answer = scan.nextLine();
do {
if (answer.equals("Quit")) {
System.out.println("Thanks forr running FracCalc!");
break;
} else {
System.out.println("I can only process 'Quit' for now");
}
answer = scan.nextLine();
} while (true);
}
}

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

How to take input for 'char' array in Java?

I am developing a small application to grade Multiple Choice Questions submitted by the user. Each question has obviously 4 choices. A,B,C,D. Since these answers will be stored in a two dimensional array, I want to ask how can I take input from user for char variable. I have not learnt any method to take input for char arrays on console. i.e I have just worked with nextInt(), nextDouble(), nextLine() etc. These methods are for Strings and Integers not for char. How to take input for char arrays? I am going to post code snippet of taking input so that you people can better understand.
public class MCQChecker{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
char[][] students=new char[8][10];
for (int i=0;i<8;i++)
{
System.out.println("Please enter the answer of "+students[i+1]);
for(int j=0;j<10;j++)
{
students[i][j]=?;//Im stuck here
}
}
}
}
Once you get the .next() value as a String, check if its .length() == 1, then use yourString.charAt(0).
students[i][j]=input.next().charAt(0);
What you need is more than char to handle your requirement. Create a question class which will have question and correct answer, user entered answer.
public static class Question {
private Choice correctChoice = Choice.NONE;
private Choice userChoice = Choice.NONE;
private String question = "";
public Question(String questionString, Choice choice) {
this.question = questionString;
this.correctChoice = choice;
}
public void setUserChoice(String str) {
userChoice = Choice.valueOf(str);
}
public boolean isQuestionAnswered() {
return correctChoice == userChoice;
}
public String question() {
return question;
}
}
enum Choice {
A, B, C, D, NONE
}
Now you can create a List of questions and for each question you can check whether it was answered correctly or not.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Question> questions = new ArrayList<Question>();
questions.add(new Question("question1", Choice.A));
questions.add(new Question("question2", Choice.A));
questions.add(new Question("question3", Choice.A));
for (Question q : questions) {
System.out.println("Please enter the answer of " + q.question());
String str = input.next();
q.setUserChoice(str);
System.out.println("You have answered question "
+ (q.isQuestionAnswered() == true ? "Correctly"
: "Incorrectly"));
}
}
Above program now allows you to ask questions and reply to user accordingly.
When question is asked if choice entered other than correct answer then question will be marked incorrectly.
In above example if other character is entered than A then it will tell user that you are incorrect.
You can't take input directly in charArray as because there is no nextChar() in Java.
You first have to take input in String then fetch character one by one.
import java.util.*;
class CharArray{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
char ch[]=new char[11];
String s = scan.nextLine();
for(int i=0;i<=10;i++)
ch[i]=s.charAt(i); //Input in CharArray
System.out.println("Output of CharArray: ");
for(int i=0;i<=10;i++)
System.out.print(ch[i]); //Output of CharArray
}
}

Java: Using scanner to read in boolean values failing.

import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}

Categories

Resources