Program error cannot end program - java

Main Class
import java.util.Scanner;
class Calculator
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Addition objecta = new Addition ();
Multiplacation objectmu = new Multiplacation();
Division objectd = new Division();
Minus objectmi = new Minus();
System.out.println("Enter operation");
System.out.println("1.Addition");
System.out.println("2.Multiplacation");
System.out.println("3.Division");
System.out.println("4.Subtraction");
input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
if (test1 == 1)
{
Addition plus = new Addition();
plus.add();
}
if (test2 == 2)
{
Multiplacation multi = new Multiplacation();
multi.multiply();
}
if (test3 == 3)
{
Division div = new Division();
div.divide();
}
if (test4 == 4)
{
Minus mi = new Minus();
mi.subtract();
}
}
}
Classes
import java.util.Scanner;
class Addition
{
public static void add()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Multiplacation
{
public static void multiply()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum * snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Division
{
public static void divide()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum / snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Minus
{
public static void subtract()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum - snum;
System.out.println(answer);
}
}
Question
I am making a calculator and I am new to computer programming. I got the program to work but the only problem is that I cannot get the program to stop. It answers one problem then starts another one continuously. Any ideas how to stop it please comment.

I think you need to understand how to accept input from the user.
In your code, this is wrong:
input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
Because later on, you check whether test1 is 1, test2 is 2 etc. Since you did not change the values of these variables, your conditions will always evaluate to true.
The correct way to do it is this:
int userInput = input.nextInt();
and then check the userInput variable:
if (userInput == 1) {
...
}
if (userInput == 2) {
...
}
etc
Tip: in this situation you should use else ifs:
if (userInput == 1) {
...
} else if (userInput == 2) {
...
} else if (userInput == 3) {
...
} else if (userInput == 4) {
...
}
Other improvements:
You should not create multiple scanners, one is enough.
You can declare a scanner in the Calculator class:
class Calculator {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
...
}
}
In your other classes, use Calculator.input instead of creating a new scanner. I'll give you an example:
class Addition
{
public static void add()
{
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = Calculator.input.nextDouble();
System.out.println("Eneter Second Number");
snum = Calculator.input.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}

This logic
if (test1 == 1)
and
if (test2 == 2)
is always going to be true.
You should be comparing
int test = input.nextInt();
if (test == test1) { // etc

You need to check the input given by the user, and since that is only one
if/if-else is the best approach to do...
if (userInput == 1) {
Addition plus = new Addition();
plus.add();
} else if (userInput == 2) {
...your code
} else if (userInput == 3) {
......your code
} else if (userInput == 4) {
......your code
}
here when math is done, you should ask again the user for another input...
and one scanner object is more than ok, you dont need to define multiple ones....

You can change your calculator class like this mentioned below so that it asks for an option when it completes execution. In similar situations you can use switch case instead of if conditions. Add an exit option to list of options to terminate program when ever user required it.
class Calculator
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Addition objecta = new Addition ();
Multiplacation objectmu = new Multiplacation();
Division objectd = new Division();
Minus objectmi = new Minus();
while(true){
System.out.println("Enter operation");
System.out.println("1.Addition");
System.out.println("2.Multiplacation");
System.out.println("3.Division");
System.out.println("4.Subtraction");
System.out.println("5.Exit");
switch(input.nextLine()){
case "1":
Addition plus = new Addition();
plus.add();
break;
case "2":
Multiplacation multi = new Multiplacation();
multi.multiply();
break;
case "3":
Division div = new Division();
div.divide();
break;
case "4":
Minus mi = new Minus();
mi.subtract();
break;
case "5":
System.exit(0);
default:
System.out.println("Please enter valid option");
}
}
/*input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
if (test1 == 1)
{
Addition plus = new Addition();
plus.add();
}
if (test2 == 2)
{
Multiplacation multi = new Multiplacation();
multi.multiply();
}
if (test3 == 3)
{
Division div = new Division();
div.divide();
}
if (test4 == 4)
{
Minus mi = new Minus();
mi.subtract();
}*/
}
}

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.

Use of Private static

Can you find the source of error in this?
package calc;
import java.util.Scanner;
public class Calc {
Scanner scan = new Scanner(System.in);
public void add() {
System.out.println("Enter 1st number");
int s1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int s2 = scan.nextInt();
scan.nextLine();
int sum = s1 + s2;
System.out.println("The sum is: " + sum);
}
public void diff() {
System.out.println("Enter 1st number");
int d1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int d2 = scan.nextInt();
scan.nextLine();
int diff = d1 - d2;
System.out.println("The difference is: " + diff);
}
public void prod() {
System.out.println("Enter 1st number");
int p1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int p2 = scan.nextInt();
scan.nextLine();
int prod = p1 + p2;
System.out.println("The product is: " + prod);
}
public void quo() {
System.out.println("Enter 1st number");
int q1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter 2nd number");
int q2 = scan.nextInt();
scan.nextLine();
int quo = q1 + q2;
System.out.println("The quotient is: " + quo);
}
public static void main(String[] args) {
do {
Calc op = new Calc();
Scanner scan = new Scanner(System.in);
char ans = 0;
System.out.println("Calculator");
System.out.println("1.Addition\n" + "2.Subtraction\n" + "3.Multiplication\n" + "4.Division\n" + "Enter operation number:");
int n1 = scan.nextInt();
scan.nextLine();
switch (n1) {
case 1:
op.add();
break;
case 2:
op.diff();
break;
case 3:
op.prod();
break;
case 4:
op.quo();
break;
default:
System.out.println("Invalid input");
break;
}
System.out.println("Try again? [Y/N]");
ans = scan.nextLine().charAt(0);
} while (ans == 'Y' || ans == 'y');
}
}
and then netbeans has this auto correct that resulted into this:
package calc;
import java.util.Scanner;
public class Calc {
private static char ans;
it added a "private static char ans;" and I would like to understand more how did that fix my code. Thanks
ans is defined within the do{ ... } while() loop but it must be defined outside, to make it available for condition in the while.
So do:
char ans = 0;
do {
Calc op = new Calc();
Scanner scan = new Scanner(System.in);
ans = 0;

Illegal Start of Type alphabet

yes, i have looked at other code, but i have a unique situation, and here it is: okay so my high school teacher is making us do a project to where we have to use IF and ELSE declarations to find out our initials just from YES and NO inputs (0 = no , and 1 = yes) and it has to work with every letter he chooses, but on line 45 it says illegal start of type, but the only thing there is else... anyways here's the code and thank you for the help in advance
/* Objective: practice completing if, if-else,block statements.
* and relational operators.
*/
import java.io.*;
import java.util.*;
public class Alphabet2 {
public static void main(String args[]) {
final int YES = 1;
final int NO = 0;
int answer = 0;
Scanner kbReader = new Scanner(System.in);
System.out.println("Think of a letter from A to Z\n\n");
System.out.println("0 = A-M");
System.out.println("1 = N-Z");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == NO){
System.out.println("\nOK, A thru M\n");
System.out.println("0 = A-G");
System.out.println("1 = H-M");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == YES){
System.out.print("\nOK, H thru M \n");
System.out.print("\n0 = H-J \n");
System.out.print("\n1 = K-M \n");
System.out.print("Enter your choice \t");
answer = kbReader.nextInt();
if(answer == YES){
System.out.print("lol");
}
else {
}
}
//else
// System.out.print("");
}
else {
System.out.println("OK, A thru G\n");
}
}
else {
System.out.println("\nOK, N thru Z\n");
System.out.println("0 = N-S");
System.out.println("1 = T-Z");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == NO){
System.out.println("OK, N thru S\n");
}
else {
System.out.println("OK, T thru Z\n");
}
}
}
At the bottom is your code properly indented.
Note that
else {
System.out.println("\nOK, N thru Z\n");
appears after the brace that closes your main method.
The reason you get that particular error message is that the parser thinks the else that appears after the main method is the type for another method or field declaration, because it is not a keyword modifier that could be part of a member declaration.
One way to think about this problem is to break it down completely before filing things in:
// A-Z
if (...) {
// A-M
} else {
// N-Z
}
then one layer more
// A-Z
if (...) {
// A-M
if (...) {
// A-F
} else {
// G-M
}
} else {
// N-Z
if (...) {
// N-S
} else {
// T-Z
}
}
etc.
/* Objective: practice completing if, if-else,block statements.
* and relational operators.
*/
import java.io.*;
import java.util.*;
public class Alphabet2 {
public static void main(String args[]) {
final int YES = 1;
final int NO = 0;
int answer = 0;
Scanner kbReader = new Scanner(System.in);
System.out.println("Think of a letter from A to Z\n\n");
System.out.println("0 = A-M");
System.out.println("1 = N-Z");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == NO){
System.out.println("\nOK, A thru M\n");
System.out.println("0 = A-G");
System.out.println("1 = H-M");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == YES){
System.out.print("\nOK, H thru M \n");
System.out.print("\n0 = H-J \n");
System.out.print("\n1 = K-M \n");
System.out.print("Enter your choice \t");
answer = kbReader.nextInt();
if(answer == YES){
System.out.print("lol");
}
else {
}
}
//else
// System.out.print("");
}
else {
System.out.println("OK, A thru G\n");
}
}
else {
System.out.println("\nOK, N thru Z\n");
System.out.println("0 = N-S");
System.out.println("1 = T-Z");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == NO){
System.out.println("OK, N thru S\n");
}
else {
System.out.println("OK, T thru Z\n");
}
}
}
/* Objective: practice completing if, if-else,block statements.
* and relational operators.
*/
import java.io.*;
import java.util.*;
public class Alphabet2 {
public static void main(String args[]) {
final int YES = 1;
final int NO = 0;
int answer = 0;
Scanner kbReader = new Scanner(System.in);
System.out.println("Think of a letter from A to Z\n\n");
System.out.println("0 = A-M");
System.out.println("1 = N-Z");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == NO){
System.out.println("\nOK, A thru M\n");
System.out.println("0 = A-G");
System.out.println("1 = H-M");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == YES){
System.out.print("\nOK, H thru M \n");
System.out.print("\n0 = H-J \n");
System.out.print("\n1 = K-M \n");
System.out.print("Enter your choice \t");
answer = kbReader.nextInt();
if(answer == YES){
System.out.print("lol");
}
else{
System.out.print("");
}
}
else {
System.out.println("OK, A thru G\n");
}
}
else {
System.out.println("\nOK, N thru Z\n");
System.out.println("0 = N-S");
System.out.println("1 = T-Z");
System.out.print("Enter your choice\t");
answer = kbReader.nextInt();
if (answer == NO){
System.out.println("OK, N thru S\n");
}
else {
System.out.println("OK, T thru Z\n");
}
}
}
}

My calculator program is not recognising first method and subtracts for both methods, why?

import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner taken = new Scanner(System.in);
int fnum;
int snum;
int ans;
String meth;
System.out.println("Please type method you wish to use:");
meth = taken.nextLine();
if (meth == "+" || meth == "plus") {
System.out.println("Please enter the First number:");
fnum = taken.nextInt();
System.out.println("Please enter the Second number:");
snum = taken.nextInt();
ans = fnum + snum; // This is the bit it misses even if the user goes through this method.
System.out.println("The answer is " + ans);
} else {
subCalc subCalcObject = new subCalc();
subCalcObject.subCalculator();
}
}
}
Like whats in the title my program does not + the numbers which is whats supposed to be done in the first statement and always subtracts no matter what method is chosen.
Use equals to compare the strings. == will return false so that you always go the else code.
if (meth.equals("+") || meth.equals("plus"))
equals checks for value equality while == checks for reference equality. So, when you do
meth = taken.nextLine();
meth is a different object from the constant strings "+" and "plus", so reference equality check will fail.
you have to use equals and not ==
public static void main(String[] args) {
Scanner taken = new Scanner(System.in);
int fnum;
int snum;
int ans;
String meth;
System.out.println("Please type method you wish to use:");
meth = taken.nextLine();
if (meth.equals("+") || meth.equals("plus")){
System.out.println("Please enter the First number:");
fnum = taken.nextInt();
System.out.println("Please enter the Second number:");
snum = taken.nextInt();
ans = fnum + snum; // This is the bit it misses even if the user goes through this method.
System.out.println("The answer is " + ans);
}
}
Change
if (meth == "+" || meth == "plus"){
To
if ("+".equals(meth) || "plus".equals(meth) ){
Now you can see there are adding.

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