How to get a looping program in Java - java

I am new to Java programming and I wanted to try to make a calculator. I made the code, but the only problem is that it will only run once. I was wondering if there was any way to get it to "loop". By that I mean, add a question to go to the beginning of the main method that way I can run the calculator again. Here is the code I have...
import java.util.Scanner;
public class calculatorFull {
public static void main(String[] args){
int op;
double num1, num2;
Scanner operation = new Scanner(System.in);
System.out.println("1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");
System.out.print("Which operation would you like to perform? ");
op = operation.nextInt();
if((op != 1) && (op != 2) && (op != 3) && (op != 4)){
System.out.println("That wasn't an option...");
}else{
System.out.print("First number: ");
num1 = operation.nextDouble();
System.out.print("Second number: ");
num2 = operation.nextDouble();
if(op==1){
Add(num1, num2);
}else if(op==2){
Sub(num1, num2);
}else if(op==3){
Mult(num1, num2);
}else if(op==4){
Div(num1, num2);
}
}
}
public static void Add(double x, double y){
double numsum;
numsum = x + y;
System.out.printf("%s + %s = %s", x, y, numsum);
}
public static void Sub(double x, double y){
double numsum;
numsum = x - y;
System.out.printf("%s - %s = %s", x, y, numsum);
}
public static void Mult(double x, double y){
double numsum;
numsum = x * y;
System.out.printf("%s * %s = %s", x, y, numsum);
}
public static void Div(double x, double y){
double numsum;
numsum = x / y;
System.out.printf("%s / %s = %s", x, y, numsum);
}
}
Thanks in advance for the help!
Btw, I think this might be different from this question (User input to repeat program in Java). I have different methods that I call from and that was changed to call from the main to just 1 method. Don't know if that changes any of the solutions or if it is the same problem but thank you for pointing out that it might be.

You can set a sentinel value to exit the program (i.e., -1 in your option) and keep track of a variable that we will constantly check in a while loop. If op ever becomes -1, it exits. Otherwise, it will restart the logic inside the while loop.
int op = 0;
while(op != -1) {
double num1, num2;
Scanner operation = new Scanner(System.in);
System.out.println("1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");
System.out.print("Which operation would you like to perform? ");
op = operation.nextInt();
if((op != 1) && (op != 2) && (op != 3) && (op != 4)){
System.out.println("That wasn't an option...");
}else{
System.out.print("First number: ");
num1 = operation.nextDouble();
System.out.print("Second number: ");
num2 = operation.nextDouble();
if(op==1){
Add(num1, num2);
}else if(op==2){
Sub(num1, num2);
}else if(op==3){
Mult(num1, num2);
}else if(op==4){
Div(num1, num2);
}
}

int continue = 0;
while(continue == 0){
// Put your calculator code here
System.out.println("Enter 1 to exit or 0 to continue");
choice = Integer.parseInt(br.readLine());
}
Try this.
UPDATE:
Use this:
import java.io.*;
public class StackOverFlow
{
// arguments are passed using the text field below this editor
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cont = 0;
while(cont == 0){
System.out.println("Inside");
// Put your calculator code here
System.out.println("Enter 1 to exit or 0 to continue");
cont = Integer.parseInt(br.readLine());
}
System.out.println("Outside");
}
}

The simplest way to do this, is to just call the main method when the calculation is complete and printed. You can achieve this by using main(null). Just add it right after your if-else block. Code below:
if(op==1){
Add(num1, num2);
}else if(op==2){
Sub(num1, num2);
}else if(op==3){
Mult(num1, num2);
}else if(op==4){
Div(num1, num2);
}
System.out.println(); // prints blank line
main(null);// calls main method (re-runs program)
This will complete the operation, then repeat the process.

Related

Java program skips an input?

Hello,
I was trying to build a simple calculator using basic Java code and understand OOP better, so, I wrote this:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr;
opr = input.nextLine();
if(opr == "+") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
} else if (opr == "-") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
} else if (opr == "*") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
} else if (opr == "/") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
} else {
System.out.println("Please, Enter a valid operation!");
}
}
}
and another Class for math operations:
import java.util.Scanner;
public class Operation {
static int Num1;
static int Num2;
Scanner input = new Scanner(System.in);
public Operation(int x, int y) {
x = Num1;
y = Num2;
}
public void addition() {
System.out.println(Num1 + Num2);
}
public void subtraction() {
System.out.println(Num1 - Num2);
}
public void multiplication() {
System.out.println(Num1 * Num2);
}
public void division() {
System.out.println(Num1 / Num2);
}
}
but it doesn't take input for the operation, and it goes straight to the next line of code, like so:
Enter a number:
4
Enter an operation:
Please, Enter a valid operation!
Could anyone, please point my mistake?
Note: I'm a newbie in Java and programming in general. so, please don't mind me if my code isn't the best, I'm still learning.
Hello you had a couple of problems. The nextLine() will return an empty line the first time since nextInt consumes the integer only after receiving a new line char but leaves the new line char in the buffer. Additionally the equals comparison needs to be using opr.equals("+") or a switch statement. And finally your Operation class constructor had the variable assignment backwards. I have also modified the Operation private member variables to follow standard naming conventions and scoping practices. You generally want to make member variables private since if not explicitly defined they will be protected. I would recommend using a good IDE since it can catch a lot of those errors for you, try using the free IntelliJ. Here is an updated version of your code.
public class Operation {
private final int num1;
private final int num2;
public Operation(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void addition() {
System.out.println(num1 + num2);
}
public void subtraction() {
System.out.println(num1 - num2);
}
public void multiplication() {
System.out.println(num1 * num2);
}
public void division() {
System.out.println(num1 / num2);
}
}
And your main class
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr = null;
while(opr == null || opr.length() == 0){
opr = input.nextLine();
}
switch (opr) {
case "+": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
break;
}
case "-": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
break;
}
case "*": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
break;
}
case "/": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
break;
}
default:
System.out.println("Please, Enter a valid operation!");
break;
}
}
}
Use
input.next
rather than
input.nextLine
as nextInt accepts a number and the new line character \n.
In the switch ts checking for the new line character.

How would I loop my program back to the beginning after a question was answered correctly 3 times in a row/ and add variance

I'm creating a program to help with students solving y= m(x) + b. As of right now, I have the program to display the menu and evaluate if your response is correct to the answer. However, I need it to also count the number of correct answers in a row.
If 3 correct end program and output total correct out of attempts tried.
else if there were 3 attempts made the output a tip.
The main issue I'm having is the loop of the two (methods?). I apologize in advance if my code is atrocious, I'm having a hard time understanding methods and classes in this compared to how Python is. Anyone's suggestions or tips would be immensely helpful.
So far I've tried adding methods, and attempts at classes to certain parts of the program such as
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {}
and
public static test_input() {}
However, now I'm facing scoping problems as well as errors referencing certain variables.
package algebra_Tutor;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] args){
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Asks for user input
System.out.print("Enter your selection: ");
}
//Creates random # for values in formula
int y_ = point_of_line_cross;
int m_ = slope;
int b_ = y_intercept;
int x_ = independent_variable;
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
//Converts user input to an integer
int selection = user_Selection.nextInt();
user_Selection.close();
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " +slope +"("+independent_variable+")"+" + "+y_intercept);
System.out.println("Input your answer: ");
}
else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = "+"("+point_of_line_cross+" - "+y_intercept+")"+" / "+independent_variable);
System.out.println("Input your answer: ");
}
else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = "+point_of_line_cross+" - "+slope+"("+independent_variable+")");
System.out.println("Input your answer: ");
}
else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
return;
}
}
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m =(y_) - ((b_) / (x_));
int answer_b =(y_) - ((m_)* (x_));
public static test_input() {
//Problem solver defined
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
//Creates loop for program
var counter = 0;
int correct = 0;
var answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y){
counter++;
correct++;
System.out.println("You answered correctly");
return;
}
else if (counter >= 3 && correct < 3) {
System.out.println("Youve been missing the questions lately, let me help! ");
}
else
{
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
}
I expect the program to output correct answers out of attempts after the user completes 3 problems in a row. In addition, it needs to output a tip after 3 attempts. And then after 3 correct, it should loop back to the beginning of program.
well I figured I would let you figure out how to make it loop on your own but I solved your other problems and put comments where I changed things. Hope this helps
//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;
public static void main(String[] args) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Converts user input to an integer
int selection = user_Selection.nextInt();
//call user_input()
user_input(selection);
}
public static void user_input(int selection) {
Scanner user_Selection = new Scanner(System.in);
int userAnswer;
int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
int slope = (int) Math.floor(Math.random() * 201) - 100;
int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
int independent_variable = (int) Math.floor(Math.random() * 201) - 100;
y_ = point_of_line_cross;
m_ = slope;
b_ = y_intercept;
x_ = independent_variable;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
}
}
// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m = (y_) - ((b_) / (x_));
int answer_b = (y_) - ((m_) * (x_));
//Problem solver defined
int answer = entered_answer;
//Creates loop for program
int counter = 0;
int correct = 0;
boolean answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y) {
counter++;
correct++;
System.out.println("You answered correctly");
return;
} else if (counter >= 3 && correct < 3) {
System.out.println("You've been missing the questions lately, let me help! ");
} else {
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
`
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)
If you give a method parameters, then when the method is called you will have to enter the values into the parameter yourself. I don't think this is what you intended because you defined what you wanted those parameter values to be here:
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
In your test_input() method you wrote:
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
.nextInt() will make the program halt and wait for user input so you don't want to use it until you are ready to get the input.
I don't really know much about the var keyword in java but rather than using var I figured you should just declare the variable type so from this:
var counter = 0;
to this:
int counter = 0;
and to get a better understanding on how methods work I recommend these two videos:
Intro to java methods
Java method parameters and return types
For an in depth explanation of the fundamentals of java in general then I recommend this whole playlist
Java Beginner Programming
It's quite late on a saturday for me to do algebra, so I will stick to suggesting changes to the structure of your program. First, you can accomplish everything with a single class to contain the questions, and score for the user. The methods in that class can be chosen via a menu in the main.
I wrote a sample of how I would structure this based on standard Java OOP methodology. In my program, the main needs no static class, it loops a menu, and the choice of a question is made there. My methods hava single question, you can add as many as you like in the menu, the important thing is the structure.
import java.util.Scanner;
//This class contains the two methods and over-all score
class Material {
private int score;
//The user chooses this or the earth method
public void sky() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
//within the method, is this while loop which gives a hint after 3 attempts.
while (!answer.equals("blue") && (!answer.equals("exit"))) {
System.out.println("What color is the sky? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'b'");
}
if (answer.equals("blue"))
score += 1;//The score will increment if the choice is correct,
else//or else leave with nothing...
return;
}
//This method is the same as the sky() method, just different question and answer.
public void earth() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
while (!answer.equals("iron") && (!answer.equals("exit"))) {
System.out.println("What is the core made of? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'i'");
}
if (answer.equals("iron"))
score += 1;
else
return;
}
public int getScore() {
return score;
}
}
public class Questions {
public static void main(String[] args) {
//No static methods needed, here is an instance of our test materia class.
Material material = new Material();
//The choice and scanner are instantiated here.
int choice = 0;
Scanner input = new Scanner(System.in);
//This while loop uses a switch statement to choose the methods for the questions
while (choice != 3) {
if (material.getScore() == 3) {
System.out.println("Good job, you scored three right.");
return;
}
System.out.println("SCORE: " + material.getScore());
System.out.println("Anwer questions about the sky: 1");
System.out.println("Answer quetions about the earth: 2");
System.out.println("Exit: 3");
choice = input.nextInt();
//choices are 1 , 2 for questions, and 3 to leave.
switch (choice) {
case 1:
material.sky();
break;
case 2:
material.earth();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("not a valid number choice...");
}
}
}// main
}// class
Side note: instead of asking the user for 1, 2, 3 or 4, you should directly ask them to enter the variable they want to solve:
Solve the equation y = m * x + b for which variable (y, m, b, quit)?
This makes the users of the program think more in the problem domain instead of some technically useless indirection.
As you have a Python background you should know that the indentation of the lines is important and has meaning. It's the same for Java programs. The only difference is that the Java compiler ignores the indentation completely. But Java programs are also read by humans, and for them the indentation is viable for understanding the structure of the program. The code you posted has inconsistent indentation, and you should let your IDE fix that.
Your program should be structured like this:
public class AlgebraTutor {
private final Scanner in = new Scanner(System.in);
private final PrintStream out = System.out;
private int attempts = 0;
void solveForY() {
...
}
void solveForM() {
...
}
void solveForB() {
...
}
void mainMenu() {
while (true) {
out.println("Solve the equation y = m * x + b for which variable (y, m, b), or quit?");
if (!in.hasNextLine()) {
return;
}
switch (in.nextLine()) {
case "y":
solveForY();
break;
case "m":
solveForX();
break;
case "b":
solveForB();
break;
case "q":
case "quit":
return;
}
}
}
public static void main(String[] args) {
new AlgebraTutor().mainLoop();
}
}

How to exit return loop in java?

I'm not new to programming per se, I have studied C# for quite a while now, but I haven't really done a lot of exercises by myself, I'm just now starting with java because I want to do Android apps and to test my newly acquired knowledge I wanted to do a basic console calculator, here's what I got so far:
package calculatorSource;
import java.util.*;
public class calculatorJava {
private static Scanner input;
public static void main(String[] args) {
System.out.println("Select an operation");
String choice = null;
input = new Scanner(System.in);
while(choice == null) {
System.out.println("Type 'a' for adition, 's' for subtraction, 'm' for multiplication," + " 'd' for division, or 'mo' for module.");
choice = input.next();
}
while(choice != null) {
if(choice.equals("a")) {
System.out.println(adition(0, 0));
choice = null;
} else if(choice.equals("s")) {
System.out.println(subtraction(0, 0));
choice = null;
} else if(choice.equals("m")) {
System.out.println(multiplication(0, 0));
choice = null;
} else if(choice.equals("d")) {
System.out.println(division(0, 0));
choice = null;
} else if(choice.equals("mo")) {
System.out.println(module(0, 0));
choice = null;
} else {
System.out.println("Option not available, please try again.");
choice = null;
}
}
}
public static float adition(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 + n2;
System.out.println("Result is: " + result);
return adition(result, result);
}
public static float subtraction(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 - n2;
System.out.println("Result is: " + result);
return subtraction(result, result);
}
public static float multiplication(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 * n2;
System.out.println("Result is: " + result);
return multiplication(result, result);
}
public static float division(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 / n2;
System.out.println("Result is: " + result);
return division(result, result);
}
public static float module(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 % n2;
System.out.println("Result is: " + result);
return module(result, result);
}
}
I know it probably is not the best or more efficient calculator out there, but as I said, I just started with java and this is pretty much all I know so far, the program works, as I can make an addition, a division or whatever else I choose, but right after that I want it to give me the option of selecting a different operation, I put the "choice = null" right after the return but it doesn't not seems to be working, I've tried several stuff to this point, but I'm starting to think I may have misunderstood what return actually does, so I thought it would be better to turn to you guys for help.
Any advice is appreciated, thanks!
Instead of
return adition(result, result);
in your adition method, return result.
Otherwise you're just going to repeat the same method until the stack overflows. (Same for other methods also).
Your while (choice != null) { loop isn't necessary, as you always set choice = null;. Since you also don't otherwise change the value of choice in that loop, you may as well just remove the loop.
There is no point in passing parameters into the adition (etc) methods, since you always overwrite them. Just declare them as local variables in those methods:
public static float adition() { // No parameters
// ...
float n1 = input.nextFloat();
// ...
float n2 = input.nextFloat();
You are recursively calling all methods infinitely. choice = null is ok. it will terminate if you will correct your code :
Instead of
MethodaName(result, result);
just write
return result;
Also you need not pass any parameters if taking input from user in method itself.
It seems you have misunderstood the return statement inside the function.
Whenever we call a function/method in java it should have a return type and the returned value should be what the function has to actually return after processing the arguments.
Hence in your case the addition function should be like this
public static float adition(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 + n2;
System.out.println("Result is: " + result);
return result;
}
Here the result variable is the processed value of your function for which it was created.
Where as in your case you were calling the same function in return statement and it was becoming a recursive function and in recursive function we always need a break statement to come out of it.
There are 2 things you could do.
If you want to run the operation just once then instead of
return addition(result,result)
use
return result.
2 . Suppose you want to run the loop of addition until user says , he want to do some other operation, then use a global variable and suppose you add the condition when user enters -999 then you return.
Hence , in second case the loop of adition runs till user enters -999.
import java.util.*;
public class calculatorJava {
private static Scanner input;
static int flag = 1;
public static void main(String[] args) {
System.out.println("Select an operation");
String choice = null;
input = new Scanner(System.in);
while (choice == null) {
System.out.println(
"Type 'a' for adition, 's' for subtraction, 'm' for multiplication,"
+ " 'd' for division, or 'mo' for module.");
choice = input.next();
}
while (choice != null) {
if (choice.equals("a")) {
flag = 1;
System.out.println(adition(0, 0));
//choice = null;
} else if (choice.equals("s")) {
flag = 1;
System.out.println(subtraction(0, 0));
//choice = null;
} else if (choice.equals("m")) {
flag = 1;
System.out.println(multiplication(0, 0));
//choice = null;
} else if (choice.equals("d")) {
flag = 1;
System.out.println(division(0, 0));
//choice = null;
} else if (choice.equals("mo")) {
flag = 1;
System.out.println(module(0, 0));
//choice = null;
} else {
System.out.println("Option not available, please try again.");
choice = null;
}
}
}
public static float adition(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
if(n1 == -999){
flag = 0;
}
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 + n2;
System.out.println("Result is: " + result);
if(flag==0)
return result;
return adition(result, result);
}
public static float subtraction(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
if(n1 == -999){
flag = 0;
}
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 - n2;
System.out.println("Result is: " + result);
if(flag==0)
return result;
return subtraction(result, result);
}
public static float multiplication(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
if(n1 == -999){
flag = 0;
}
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 * n2;
System.out.println("Result is: " + result);
if(flag==0)
return result;
return multiplication(result, result);
}
public static float division(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
if(n1 == -999){
flag = 0;
}
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 / n2;
System.out.println("Result is: " + result);
if(flag==0)
return result;
return division(result, result);
}
public static float module(float n1, float n2) {
input = new Scanner(System.in);
float result;
System.out.println("Enter first number:");
n1 = input.nextFloat();
if(n1 == -999){
flag = 0;
}
System.out.println("Enter second number:");
n2 = input.nextFloat();
result = n1 % n2;
System.out.println("Result is: " + result);
if(flag==0)
return result;
return module(result, result);
}
}
To ask again
First, your while loop for the addition is not usefull, an IF could be enough, but useless to since you check the value before (in the first loop)
This is one possibility to loop on you code.
boolean letDoMath = true;
while(letDoMath ) { // aka while(letDoMath == true){
while(choice == null) {
System.out.println("Type 'a' for adition, 's' for subtraction, 'm' for multiplication," + " 'd' for division, or 'mo' for module.");
choice = input.next();
}
//HERE YOU KNOW CHOISE ISN'T NULL BECAUSE OF THE WHILE LOOP, NO NEED TO CHECK AGAIN.
if(choice.equals("a")) {
System.out.println(adition(0, 0));
choice = null;
} else if(choice.equals("s")) {
System.out.println(subtraction(0, 0));
choice = null;
} else if(choice.equals("m")) {
System.out.println(multiplication(0, 0));
choice = null;
} else if(choice.equals("d")) {
System.out.println(division(0, 0));
choice = null;
} else if(choice.equals("mo")) {
System.out.println(module(0, 0));
choice = null;
} else if(choice.equlas("end"){
letDoMath = false;
}
}
The boolean while give you the possibility to loop again an again until you input end. This in not perfect of course but this is a beginning. (And I didn't try or even write it in IDE so might contains errors.
Operation methods error
As precise everywhere, your operation methods are recursive, addition call itself at the end. Remove the return addition(x,y) and just return the result of the addition you do.
Some improvment idea :
Create a method to get a number an return it (usefull in every method).
The best would be to ask number outside the operation to pass the value to the methods, not reading the scanner in the methods. (of course, you need to be sure of the choice value (actualy, you could ask for the number before the choice). And ask again ONLY if a operation has been done.

Why does my calculator automatically answer "0" before i can put my sign in?

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

Java: Ask for continue

I'm trying to make a calculator. These operators: x, +, -, / work fine.
But I want the user to be able to do 2 things after he gets the answer on his math problem.
Ask user if he wants to continue.
If user types in yes he gets to put in 2 numbers that it counts again.
If the user types no just shut down.
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Minscanner = new Scanner(System.in);
int nr1 = Integer.parseInt(Minscanner.nextLine());
int nr2 = Integer.parseInt(Minscanner.nextLine());
int yes = Integer.parseInt(Minscanner.nextLine());//trying to fix reset
int ans =0;
int reset = J;/trying to make it reset if user types in yes
String anvin = Minscanner.nextLine();
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);
}
if(anvin.equalsIgnoreCase("yes")) {
return;
}
}
}
Put your code in a
do {
...
} while (condition);
loop, and in your case the condition would be something like wantToContinue if user say "yes".
Then the program will not end unless user no longer wants to calculate.
You can refactor your code as bellow. This may help you
boolean status=true;
while (status){
Scanner scanner = new Scanner(System.in);
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter your two numbers one by one :\n");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("Enter your operation you want to perform ? ");
int ans =0;
String option = scanner1.nextLine();
if(option.equalsIgnoreCase("+")) {
ans = num1 + num2;
}
else if(option.equalsIgnoreCase("-")) {
ans = num1 - num2;
}
else if(option.equalsIgnoreCase("*")) {
ans = num1 * num2;
}
else if(option.equalsIgnoreCase("/")) {
ans = num1 / num2;
}
System.out.println(ans);
System.out.println("you want to try again press y press j for shutdown\n");
Scanner sc = new Scanner(System.in);
String input=sc.nextLine();
if (input.equalsIgnoreCase("J")) {
System.exit(0);
} else if (input.equalsIgnoreCase("Y")) {
status = true;
}
}

Categories