Weird bug in trial code - java

This is some code I have been working on for a simple pub style quiz to learn Java. For some reason it will ask the question the first time and then will just skip past it from then on. It also declares the strings null even though I initialize them.
Here is the code
public class PubQuizWMethod
{
private static Scanner keyboard = new Scanner (System.in);
static String a1,a2,a3,a4;
static String b1,b2,b3,b4;
static String c1,c2,c3,c4;
static String d1,d2,d3,d4;
static String ans1,ans2,ans3,ans4;
static String q1,q2,q3,q4;
static String question;
static boolean newQuiz = true;
static boolean notStop = true;
static char correctAnswer;
static char answer1,answer2,answer3,answer4;
static char answer;
static int score = 0;
public static void mainMenu()
{
{
{
do{
gettingQuestion();
question = q1;
gettingAnswers();
ans1 = a1;
ans2 = b1;
ans3 = c1;
ans4 = d1;
gettingCorrectAnswer();
answer1 = correctAnswer;
gettingQuestion();
question = q2;
gettingAnswers();
ans1 = a2;
ans2 = b2;
ans3 = c2;
ans4 = d2;
gettingCorrectAnswer();
answer2 = correctAnswer;
gettingQuestion();
question = q3;
gettingAnswers();
ans1 = a3;
ans2 = b3;
ans3 = c3;
ans4 = d3;
gettingCorrectAnswer();
answer3 = correctAnswer;
gettingQuestion();
question = q4;
ans1 = a4;
ans2 = b4;
ans3 = c4;
ans4 = d4;
gettingCorrectAnswer();
answer4 = correctAnswer;
if(notStop == true)
{
score = 0;
System.out.println(q1);
System.out.println("a: " +a1);
System.out.println("b: " +b1);
System.out.println("c: " +c1);
System.out.println("d: " +d1);
answer = keyboard.next().charAt(0);
if(answer == answer1)
{
System.out.println("That was correct");
score ++;
}
else
{
System.out.println("That was incorrect");
}
System.out.println(q2);
System.out.println("a: " +a2);
System.out.println("b: " +b2);
System.out.println("c: " +c2);
System.out.println("d: " +d2);
answer = keyboard.next().charAt(0);
if(answer == answer2)
{
System.out.println("That was correct");
score ++;
}
else
{
System.out.println("That was incorrect");
}
System.out.println(q3);
System.out.println("a: " +a3);
System.out.println("b: " +b3);
System.out.println("c: " +c3);
System.out.println("d: " +d3);
answer = keyboard.next().charAt(0);
if(answer == answer3)
{
System.out.println("That was correct");
score ++;
}
else
{
System.out.println("That was incorrect");
}
System.out.println(q4);
System.out.println("a: " +a4);
System.out.println("b: " +b4);
System.out.println("c: " +c4);
System.out.println("d: " +d4);
answer = keyboard.next().charAt(0);
if(answer == answer4)
{
System.out.println("That was correct");
score ++;
}
else
{
System.out.println("That was incorrect");
}
System.out.println("You achieved a score of " +score +" out of 4");
System.out.println("Would you like to play again? y/n ");
char yn = keyboard.next().charAt(0);
if(yn == 'y')
{
notStop = true;
}
else
{
notStop = false;
}
}
System.out.println("Would you like to make a new quiz? y/n");
char yn = keyboard.next().charAt(0);
if(yn == 'y')
{
newQuiz = true;
}
else
{
newQuiz = false;
}
}while(newQuiz = true);
}
}
}
public static void gettingQuestion()
{
System.out.println("Please enter the question");
question = keyboard.nextLine();
}//getting the questions
public static void gettingAnswers()
{
System.out.println("Please enter in the four answers each on its own line.");
ans1 = keyboard.nextLine();
ans2 = keyboard.nextLine();
ans3 = keyboard.nextLine();
ans4 = keyboard.nextLine();
}
public static void gettingCorrectAnswer()
{
System.out.println("Please enter the correct answer. a/b/c/d");
correctAnswer = keyboard.next().charAt(0);
}
public static void main(String[] args)
{
mainMenu();
}
}
and the result is this:
Please enter the question
ahsdf
Please enter in the four answers each on its own line.
adsfh
adsfh
asdfh
asdfh
Please enter the correct answer. a/b/c/d
a
Please enter the question
Please enter in the four answers each on its own line.
asdf
asdfh
asdfh
asdfh
Please enter the correct answer. a/b/c/d
a
Please enter the question
Please enter in the four answers each on its own line.
asdfh
asdfh
asdfh
adsfh
Please enter the correct answer. a/b/c/d
asdfh
Please enter the question
Please enter the correct answer. a/b/c/d
asdfh
null
a: null
b: null
c: null
d: null
a
That was correct
null
a: null
b: null
c: null
d: null
a
That was correct
null
a: null
b: null
c: null
d: null
a
That was correct
null
a: null
b: null
c: null
d: null
a
That was correct
You achieved a score of 4 out of 4
Would you like to play again? y/n
y
Would you like to make a new quiz? y/n
n
Please enter the question
Please enter in the four answers each on its own line.
etc.

I have pasted some of your code to explain what is happening. We start here:
public static void mainMenu()
{
{
{
do{
gettingQuestion();
question = q1;
In the line below you are reading from keyboard and loading all values in ans1, ans2, ans3 and ans4 variables.
gettingAnswers();
Everything is ok, but when you do the following:
ans1 = a1;
ans2 = b1;
ans3 = c1;
ans4 = d1;
You are overwriting the ans1, ans2, ans3 and ans4 values, that's why you have null values.
As an extra note you can handle arrays or objects to keep your code with more order, it could be like this
public class Question{
private String realAnswer
private String question;
private String[] fakeAnswers = new String[4];
public Question(String realAnswer, String question, String [] fakeAnswers){
this.realAnswer = realAnswer;
this.question = question;
this.fakeAnswers = fakeAnswers;
}
/*
Some getters and setters
*/
}
Then you can create a main class that contains something like this:
public static void main(String[] args){
// Number 10 is the quantity of questions that your quiz will have
Question[] question = new Question[10];
/*
More code
*/
}

Classic mistake: Using == to compare Strings instead of equals. It's not a bug; it's you and your code.

You are assigning null to question here.
gettingQuestion();
question = q1; // q1 is null.
// Here question and q1 both are null and hence it is printing null in the answer.
Hence the output is printing null.
Also change the while condition.

next() doesn't handle the end of the line. So when you call nextLine() again, it'll take as input the enter (\n) you entered before. So it's "skipping" the actual input and swallows the \n from the previous input that was missed by next(). You have two solutions:
Call another nextLine() before the real nextLine() (So it will swallow the \n).
Get rid of next and replace it with nextLine().
Another thing:
The expression of the assignment returns the assigned value, look at this:
while(newQuiz = true);
What iside the while loop will be always true.
Also please note that it's redundant to write if(variable == true), it's enough to write if(variable).

Related

Can you add multiple questions in a while loop in java?

I'm currently a senior high school student and I'm doing a short quiz game as a project. And I was wondering if you can add multiple questions. Here Is the code
import java.util.Scanner;
import java.util.Random;
public class Quiz
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Random r = new Random();
int lives = 3;
String answers;
while (lives > 0)
{
System.out.println("Question Goes Here: ");
answers = s.nextLine();
if (answers.equalsIgnoreCase("Answer"))
{
System.out.println("Correct! Please press ENTER to continue");
s.nextLine();
}
//TO-DO IF THE ANSWER IS WRONG
else
{
--lives;
System.out.println("You have " + lives + " lives left");
}
}
//TO-DO IF "LIVES" IS EQUAL TO 0
if (lives == 0)
{
System.out.println("Game Over");
}
}
Assuming that you have prepared a 2D array of questions and answers:
final Scanner s = new Scanner(System.in);
String[][] arrQA = {
{"question1", "answer1"},
{"question2", "answer2"},
{"question3", "answer3"},
{"question4", "answer4"},
};
int lives = 3;
int success = 0;
for (int i = 0; i < arrQA.length && lives > 0; i++) {
String[] qa = arrQA[i];
System.out.print(qa[0] + " goes here, type your answer: ");
String answer = s.nextLine();
if (answer.equalsIgnoreCase(qa[1])) {
success++;
System.out.println("Correct! Please press ENTER to continue");
s.nextLine();
} else {
--lives;
System.out.println("Incorrect! You have " + lives + " lives left");
}
}
System.out.println("Game Over! You have answered " + success + " questions correctly");
I would recommend creating a POJO class for questions. Something like this:
class Question{
String question;
String answer;
public Question(String question, String answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
}
And then create your main function, with the list of questions, iterate over your question with some variable.
public static void main(final String[] args) {
//Variables
final Scanner s = new Scanner(System.in);
final Random r = new Random();
int lives = 3;
String answers;
ArrayList<Question> quizBrain = new ArrayList<Question>();
quizBrain.add(new Question("question1", "answer1"));
quizBrain.add(new Question("question2", "answer2"));
quizBrain.add(new Question("question3", "answer3"));
quizBrain.add(new Question("question4", "answer4"));
quizBrain.add(new Question("question5", "answer5"));
int questionCounter = 0;
//Conditions
while (lives > 0)
{
System.out.println(quizBrain.get(questionCounter).getQuestion());
answers = s.nextLine();
if (answers.equalsIgnoreCase(quizBrain.get(questionCounter).getAnswer()))
{
System.out.println("Correct! Please press ENTER to continue");
questionCounter++;
s.nextLine();
}
//TO-DO IF THE ANSWER IS WRONG
else
{
--lives;
System.out.println("You have " + lives + " lives left");
}
}
//TO-DO IF "LIVES" IS EQUAL TO 0
if (lives == 0)
System.out.println("Game Over");
}
You can see this for the advantages of POJO class. It would be a great help if you need to store your question in the database.
I recomend you to create an array with all the questions and then acces it with math.random. You will also have to create an array for the answers in the same order as the question's one, so math.random can get the correct answer for the choosen question.

how to stop the while loop in java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am new to Java and I am creating a simple calculator. I used while loop to run it continuously but I couldn't stop it, Please help me with the code.
My calculator class code is:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Boolean keepRunning = true;
while (keepRunning) {
double a, b, out;
int n;
String ans = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter two Numbers ");
a = in.nextDouble();
b = in.nextDouble();
System.out.println("Enter the mode of operation:" + "\n"
+ "1. Addition" + "\n"
+ "2. Subtraction" + "\n"
+ "3. Multiplication" + "\n"
+ "4. Division");
n = in.nextInt();
switch(n){
case 1:
out = add(a,b);
System.out.println("The output is: "+ out );
break;
case 2:
out = sub(a,b);
System.out.println("The output is: "+ out );
break;
case 3:
out = mul(a,b);
System.out.println("The output is: "+ out );
break;
case 4:
out = div(a,b);
System.out.println("The output is: "+ out );
break;
default:
System.out.println("Enter Valid option");
break;
}
System.out.println("Do you want to continue? (Y/N)");
Scanner in1 = new Scanner(System.in);
ans = in1.next();
if(ans == "Y" || ans == "y"){
}else if(ans == "N" || ans == "n"){
keepRunning = false;
System.exit(0);
}
}
}
public static double add(double a, double b){
return a+b;
}
public static double sub(double a, double b){
return a-b;
}
public static double mul(double a, double b){
return a*b;
}
public static double div(double a, double b){
return a/b;
}
}
The if loop is not at all running what's the problem in it.
Note: This question is already exist in Stackoverflow but I can't find my answer.
Don't compare strings with == in Java, use "N".equals(ans), for example. Look out to the duplicate that #EJP post for you

Let users input create object

I'm writing this program where the user takes a math test. The problem Im now facing and have been trying to fix is how to display the final score at the end of the test.
I have a counter and the score increments for every correct answer, but how do I (at the end) display the final/total score? Any help is appreciated.
This is one of three classes btw.
import java.util.Scanner;
public class Questions {
Scanner scan = new Scanner(System.in);
int answer = 0;
int point = 0;
String correct = "Correct";
public void pointers(){
point++;
System.out.println(point + " point added to total score");
}
public void totalPoints(){
pointers();
}
public void showQuestions(){
System.out.println("\n--------------\nQuestion #1: 1+1 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println(correct);
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #2: 340-23 = ? ");
answer = scan.nextInt();
if(answer == 317){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #3: 900/3 = ? ");
answer = scan.nextInt();
if(answer == 300){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #4: 23*2 = ? ");
answer = scan.nextInt();
if(answer == 46){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #5: -4+6 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
}
}
The problem is that you're trying to get the input first and then you're asking for the age. When you type keyboard.nextInt() it is expecting an input immediately. So the problem is here:
*int age = keyboard.nextInt();
* System.out.println("Age: " + age);
*age = keyboard.nextInt();
My suggestion is to just remove the first keyboard.nextInt():
Example:
System.out.println("\nName: " + name);
name = keyboard.nextLine();
System.out.println("Age: " + age);
final int age = keyboard.nextInt();
and that's about it. Just be careful where you place your method calls, e.g. they should be after your println()'s.
No idea what you try to achieve, but
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
System.out.println("Hello, it is time to take a math test.\nFirst we need you to enter some information about yourself.");
System.out.print("\nEnter name: ");
final String name = keyboard.nextLine();
System.out.print("Enter Age: ");
final int age = keyboard.nextInt();
keyboard.close();
System.out.println("Your personal information: " + name + " of " + age + " years old.");
}
}
output:
C:\Temp\123431>java -classpath .;Main.class Main
Hello, it is time to take a math test.
First we need you to enter some information about yourself.
Enter name: ttt
Enter Age: 321
Your personal information: ttt of 321 years old.
C:\Temp\123431>java -classpath .;Main.class Main

Looping if statements

Im looking to make this loop after it asks them a question in this case ""What is 2+2?" then taking there input, Then the program should ask "Are you sure Y/N" if they awnser no i want it to go back to the start of this loop and allow them to redo the question. As it is i can't get this to loop and after this part works i will need to do 9 more questions in the same format
import java.util.Scanner;
class Quiz
{
public static void main (String[] args)
{
int q1=0 , q2=0;
boolean correct = false;
char yn1='y';
String q3 , q4;
Scanner input1 = new Scanner( System.in );
int count = 0 ;
//Question 1 start
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
break;
}
}
//Question 2 start
while (correct == false)
{
System.out.println("how many legs does a legless cow have?");
System.out.println("Choices: 0,25,4,31");
q2 = input1.nextInt();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( q2 == 0)
System.out.println("You were correct, the cow has 0 legs");
else
System.out.println("You were wrong");
break;
}
}
//Question 3 start
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
q3 = input1.nextLine();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( "Ottawa".equals(q3))
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
break;
}
}
}
}
A new problem has occurred i have used the one helpful example and may try to change it to an array later but not in till i get the basics working. all the Questions usings int work so far Ie.
//Question 1 start
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
break;
}
}
But now i want to use a word awnser so i made a string and put it in instead of int but now instead of allowing input for q3 it skips to input of y/n i don't understand why all of a sudden it would do this yet the other questions work correctly with int.
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
String q3 = input1.nextLine();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( "Ottawa".equals(q3))
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
break;
}
}
Im sorry if this hasn't been enough detail or is formated wrong and will be sure to fix it if it is.
When reading input, always use q1 = Integer.parseInt(input1.nextLine()); (Even better, use the BufferedReader class). That way, your reading will work smoothly.
Secondly, you can place the if (q1 == 4) within the if (yn1.equals("Y")) statement. If the user has typed "Y" then set correct = true; to proceed to the next question. Further, if the user's answer is correct then increment the counter of right answers else print wrong. So the loop looks like this:
while (correct == false) {
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = Integer.parseInt(input1.nextLine());
System.out.println("Are You Sure? (Y/N)");
yn1 = input1.nextLine();
if (yn1.equals("Y")) {
correct = true;
if (q1 == 4) {
System.out.println("You were correct 2+2 = 4");
count++;
} else
System.out.println("You were wrong");
}
}
A few things to look into:
You print "Choices: 0,2,4,8", but nothing stops the user to enter 3 or 3000. Is the choices statement necessary? Then you'll need to check if the user has entered within that range or not also.
Instead of copying & pasting this same loop n times, make use an an array. Have all questions & answers stored in some String array for now. Something like this:
for (int i = 0; i < questions.length; i++) {
boolean nextQ = false;
while (nextQ == false) {
System.out.println(questions[i]);
String ans = input1.nextLine();
System.out.println("Are You Sure? (Y/N)");
yn = input1.nextLine();
if (yn.equalsIgnoreCase("Y")) {
nextQ = true;
if (ans.equals(answers[i])) {
System.out.println("You were correct " + questions[i]
+ " = " + answers[i]);
count++;
} else
System.out.println("You were wrong");
}
}
}
I changed the boolean variable correct to nextQ to avoid confusion. Hope the sets you in the right direction.
I tried to compile your program.But I am getting some errors:-
error: variable q1 might not have been initialized
According to what I understand from ur question.Here is the program u want:-
import java.util.Scanner;
class stack1
{
public static void main (String[] args)
{
int q1=0 , q2 , q3, q4, q5, q6 , q7 ,q8 ,q9 ,q10 , a ;
boolean correct = false;
char yn1='Y';
Scanner input1 = new Scanner( System.in );
int count = 0 ;
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (Y/N)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
System.out.println("Exiting the program");
correct = true; //It should now stop the loop and carry on
break;
}
}
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
//Soon will add int score and add 1 each time its correct
// will be using 9 more loops the exact same way
}
}
I have mentioned all the changed lines with comment '//changed line' .
This is the answer for the edited Question:-
import java.util.Scanner;
class stack2
{
public static void main (String[] args)
{
int q1=0 , q2 , q3, q4, q5, q6 , q7 ,q8 ,q9 ,q10 , a ;
boolean correct = false;
char yn1='Y';
String s="";
System.out.println(s);
Scanner input1 = new Scanner( System.in );
int count = 0 ;
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
s = input1.nextLine();
System.out.println(s);
System.out.println("Are You Sure? (Y/N)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
System.out.println("Exiting the program");
correct = true; //It should now stop the loop and carry on
break;
}
if (s.equals("Ottawa")) //q1 was stated during loop
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
}
//Soon will add int score and add 1 each time its correct
// will be using 9 more loops the exact same way
}
}
Be careful while entering the input.It shoul be exactly "Ottawa". Best of luck

If Statement not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am new to programming and would appreciate some help. The slightest bit of insight would be highly appreciated.
I have an issue with the following code. The program emulates a calculator but currently my main focus is on if and else if statements. The issue is that no matter what the user selects, the program will always add the two numbers i.e. 'number1' and 'number2' in the code
import java.util.*;
public class Input
{
private Scanner input;
public Input()
{
input = new Scanner(System.in);
}
public void calculation()
{
double number1, number2, answer;
String A, B, C, D, E;
String option;
A = "A"; B = "B"; C = "C"; D = "D"; E = "E"; //initialising the strings
System.out.println("add - option A \t (if your option is A, insert 'A')");
System.out.println("multiply - option B");
System.out.println("subtract - option C");
System.out.println("divide - option D");
System.out.println("power - option E (1st number - 'X' & 2nd number - 'n' following X^n)");
System.out.println("Remember Java is case sensitive, therefore, inserting 'a' as 'A' won't work");
System.out.println();
System.out.println("Insert your first number: ");
number1 = input.nextDouble();
System.out.println("Insert your second number: ");
number2 = input.nextDouble();
System.out.println("Choosing option: ");
option = input.next();
if(A == A)
{
answer = number1 + number2;
System.out.println("Your answer is: " + answer);
}
else if(B == B)
{
answer = number1 * number2;
System.out.println("Your answer is: " + answer);
}else if(C == C)
{
answer = number1 - number2;
System.out.println("Your answer is: " + answer);
}else if(D == D)
{
answer = number1 / number2;
System.out.println("Your answer is: " + answer);
}else if(E == E)
{
answer = Math.pow(number1, number2);
System.out.println("Your answer is: " + answer);
}else
{
System.out.println("Choose a suitable option");
}
}
}
Youre getting the selected option from user input in option = input.next(); line and than your not using it in your if statements.
Instead of if(A == A) use if(option.equals(A)) and so on for other cases.

Categories