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
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner, and I would like to know on how do I get this program out of bugs-
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.next().charAt(0);
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
System.out.println("Continue? Type Y to continue or N to end: ");
String st = sc.nextLine();
if(st.equals("n")) {
stop = true;
}
else {
stop = false;
}
} while(!stop);
}
}
There are no errors at all, these are my wrong-doings in the program. After all the calculations are done, it puts me through a loop, and I don't seem to quite figure it out, on how to get the user input. It comes back to the start.
This is all I can put up, since I really don't have much to tell, if anything, I will edit this questions as users ask questions.
Thanks:)
Replace String st = sc.nextLine() by String st = sc.next().
At this point the scanner has a line break in its buffer (remaining from reading the operator).
nextLine() returns whatever is left in the buffer, it does not wait for additional user input.
By calling next() instead you tell the scanner that you want to read another token. The line break is less than a token, so Scanner waits for additional user input.
You should put a nextLine(); after every nextFoo(); to consume the new line character
Also change to sc.nextLine().charAt(0); as suggested in the comments
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.nextLine().charAt(0);//change
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
// better check
String st ="";
do {
System.out.println("Continue? Type Y to continue or N to end: ");
st = sc.nextLine();
}while (!st.equals("N") || !st.equals("Y"));
if(st.equals("N")) {
stop = true;
}
else if (st.equals("Y")) {
stop = false;
}
} while(!stop);
}
}
Note that you didn't do a very good check to see if user wants to continue
I just suggest using something like this
More info about your problem
Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if (anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
} else if (anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
} else if (anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
} else if (anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}
I'm trying to write this java program for a user to input two rational numbers and ask from a menu of options to compute some sort of function A. I'm stuck in a few places and don't know what else to do. I need some guidance. it wont compile. says constructor Rational is undefined and the last default is an invalid label .it is two class files were the driver files uses the rational file. both files are uploaded and separated by text. need help
import java.util.Scanner;
import java.util.*;
public class RationalDriver{
public static void main(String[] args){
int rationalNum1, rationalDen1, rationalNum2, rationalDen2;
Scanner in = new Scanner(System.in);
// first rational
System.out.println(" Input first rational number for the Numerator");
rationalNum1 = in.nextInt();
System.out.println(" Input first rational number for the Denominator");
rationalDen1 = in.nextInt();
if (rationalDen1 == 0){
System.out.println(" Cannont divide by zero ");
System.out.println(" please re enter another number ");
}
System.out.println("Rational Number #1 = ("+rationalNum1+"/"+rationalDen1+")");
//Displays 1st Rational Number
// second rational
System.out.println(" Input 2nd rational number for the 2nd Numerator");
rationalNum2 = in.nextInt();
System.out.println(" Input 2nd rational number for the 2nd Denominator");
rationalDen2 = in.nextInt();
if (rationalDen2 == 0){
System.out.println("Cannont divide by zero");
System.out.println(" please re enter another number");
}
System.out.println("Rational Number #2 = ("+rationalNum2+"/"+rationalDen2+")");
//Displays 2nd Rational Number
Rational r1 = new Rational ( rationalNum1, rationalDen1);
Rational r2 = new Rational ( rationalNum2, rationalDen2);
// System.out.println;//toString
}
public void display_menu() //menu options
{
System.out.print(" Enter the corresponding number for the desired action ");
System.out.println("1) Addition\n2) 2) Subtraction\n3) 3) Multiplication\n4) 4)Division\n5) 5) Test for Eqaulity\n6) 6) Change 1st rational number\n7) 7) Change 2nd rational number");
}
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextInt())
{
case 'y' :
System.out.println ("Thank you and goodbye.");
break;
case 'n' :
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
public void InputMenu() // keys for the menu
{
Scanner in = new Scanner(System.in);
display_menu();
switch (in.nextInt())
{
case 1: //addition
System.out.println ( "1" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " + " + " ("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.add(r2));
break;
case 2: //subtraction
System.out.println ( "2" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " - " + "("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.subtract(r2));
break;
case 3: //mulitplication
System.out.println ( "3" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " * " + " ("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.multiply(r2));
break;
case 4: //division
System.out.println ( "4" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " / " + "("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.divide(r2));
break;
case 5: //compare to
System.out.println ( "5" );
question();
break;
case 6: //change the 1st Rational Number
System.out.println ( "6" );
Scanner in = new Scanner(System.in);
System.out.println(" Input first rational number for the Numerator");
rationalNum1 = in.nextInt();
System.out.println(" Input first rational number for the Denominator");
rationalDen1 = in.nextInt();
if (rationalDen1 == 0){
System.out.println(" Cannont divide by zero");
System.out.println(" please re enter another number");
}
break;
case 7: //change the 2nd Rational Number
System.out.println ( "7" );
System.out.println(" Input 2nd rational number for the 2nd Numerator");
rationalNum2 = in.nextInt();
System.out.println(" Input 2nd rational number for the 2nd Denominator");
rationalDen2 = in.nextInt();
if (rationalDen2 == 0){
System.out.println("Cannont divide by zero");
System.out.println(" please re enter another number");
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
}
}
Here is the class file for rational
public class Rational{
private int Numerator;
private int Denominator;
//constructors
public Rational(){
Numerator = 1;
Denominator = 1 ;
}
//setters
//a-numerator
//b-denmonator
//c other.getNumerator
//d-other.getDenominator
public void add (Rational other){ // (ad + bc) / bd
Numerator = (Numerator*other.getDenominator() + Denominator*other.getNumerator());
Denominator = (Denominator*other.getDenominator());
//Normalize();
}
public void subtract (Rational other){ // (ad-bc) / bd
Numerator = (Numerator*other.getDenominator() - Denominator*other.getNumerator());
Denominator = (Denominator*other.getDenominator());
//Normalize();
}
public void multiply (Rational other){ // ac/db
Numerator = (Numerator*other.getNumerator() / other.getDenominator()* Denominator);
// Normalize();
}
public void divide (Rational other){//
}
public int getNumerator(){
return Numerator;
}
public int getDenominator(){
return Denominator;
}
//toString
//public String toString(){
//return toString()+ (rationalNum1 + "/" + rationalDen1);
}
In your main class you have:
Rational r1 = new Rational ( rationalNum1, rationalDen1);
Rational r2 = new Rational ( rationalNum2, rationalDen2);
you are passing 2 integers to a constructer that recives void, so you have to change your constructer (of Rational class) like this:
public Rational(int rationalNumber, int rationalDen){
Numerator = rationalNumber;
Denominator = rationalDen;
}
Hope it helps, let me know if it worked or if there is more something wrong...
Edit: your Scanner and print error.
You have this:
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextInt()) // here you are assuming that you are reading a int in step
{ // of a string
case 'y' : // ' ' arent used for strings...
System.out.println ("Thank you and goodbye.");
break;
case 'n' :
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
so, what you need is:
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextLine()) // change nextInt to nextLine, that is the string method
{ // of a string
case "y" : //change ' ' to " "
System.out.println ("Thank you and goodbye.");
break;
case "n" : //change ' ' to " "
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
Hope it help :)
Edit 3:
in your code you have: `
public class RationalDriver{
public static void main(String[] args){
int rationalNum1, rationalDen1, rationalNum2, rationalDen2; // this are local variables, they only exist inside main method
...`
}
So, what you can do is:
public class RationalDriver{
private static int rationalNum1, rationalDen1, rationalNum2, rationalDen2;
public static void main(String[] args){
// your main
}
what i did was take your local variables that only exists in your main and turn them in global variables so when you want change their value or give them a value you just do:
rationalNum1 = your valor;
Please note that if you use any variable without initialize it with a value you will get a null point exception...
you need to create a constructor Rational (int rationalNum1, int rationalDen1){}
In your program you used the constructor Rational ( rationalNum1, rationalDen1)
when you have only declared the default constructor public Rational(), which does no accept any arguments.
It is possible to have multiple constructor for a class and they are differentiated by the type and number of argument they accept.
E.g
class A(int a, int b);
is same as
Class A(int c, int b);
but not
Class(int a, float d)
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.
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).