I have implemented a calculator, however, I only want the user to be able to pick two options then close the program. My code is having the user cycle through each operation. I would like the user to pick a number 1 through 6 and have it complete the operation the selected. Also if someone knows how to get the program to exit if they press 0 at the menu that would be fantastic.
import java.util.*;
public class Calculator
{
private int option = -1; // option is initially not 0
to 6
private Scanner scan; // we’ll use scan to read input
// constructor for class
public Calculator()
{
System.out.println ("java Homework1");
System.out.println ("Welcome to Math Calculator!");
System.out.println ("Please choose an option:");
System.out.println (" ");
System.out.println ("1 - add two real numbers");
System.out.println ("2 - subtract two real numbers");
System.out.println ("3 - multiply two real numbers");
System.out.println ("4 - divide two real numbers");
System.out.println ("5 - get the factorial of an
number");
System.out.println ("6 - menu");
System.out.println ("0 - exit");
scan = new Scanner(System.in); // creates scan
}
// entry point for class
public void run()
{
// stick code for calculator in here...may want to
create
// other functions to make code more readable
int selection1;
Scanner first = new Scanner(System.in);
selection1 = first.nextInt();
if (selection1 == 1);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
+ secondnum));
}
if (selection1 == 2);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
- secondnum));
}
if (selection1 == 3);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
* secondnum));
}
if (selection1 == 4);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
/ secondnum));
}
if (selection1 == 5);
System.out.println ("Enter the number you would
like the factorial of: ");
int factorialnum = scan.nextInt();
int i,start = 1;
for (i = 1; i <= factorialnum;i++)
{
start = start*i;
}
System.out.println ("your answer is: " + start);
}
}
The problem is with the if conditions. The following if condition is not correct. It will have no effect on the section following it, since it is ended with the semicolon (;)
if (selection1 == 1); //This condition will have no effect on the section following it
This is the correct way to write the if condition.
if (selection1 == 1){
//your logic here
}
Also, note the last if condition for factorial. It does not have braces for the code following it.
So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.
import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.
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
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.