Java Beginner, Why does my Program keep terminating? - java

Trying To create a calculator, Done a lot of this before about 4 years ago and just getting back into java. It just keeps terminating, it doesn't print out anything, runs for approx 5 seconds then terminates. Any help would be much appreciated.
EDIT: The problem was with the main function. The problem is fixed, thank you!
Adding the OOJCalculation code for those wanting to laugh at my stupidity more
public class OOJCalculation {
int Calculation (int Num1, int Num2, String Function,int Num3){
if(Function == "+"){
Num1 += Num2 = Num3;
return Num3;
}
else if(Function == "-"){
Num1 -= Num2 = Num3;
return Num3;
}
else if(Function == "*"){
Num1 *= Num2 = Num3;
return Num3;
}
if(Function == "/"){
Num1 /= Num2 = Num3;
return Num3;
}
return Num3;
}
}
public class Main {
public static void main(){
int State = 0;
int Num1 = 0;
int Num2 = 0;
String Function = "";
Scanner reader = new Scanner(System.in);
OOJCalculation calc = new OOJCalculation();
while(State < 5){
if(State == 0){
System.out.println("Enter first number.");
Num1 = reader.nextInt();
State++;
}
if(State == 1){
System.out.println("Enter the function.");
Function = reader.next();
State++;
}
if(State == 3){
System.out.println("Enter the second number.");
Num2 = reader.nextInt();
State++;
}
if(State == 4){
calc.Calculation(Num1, Num2, Function);
System.out.println(calc);
}
}
}
}

As the jls state :
The method main must be declared public, static, and void. It must specify a formal parameter (ยง8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:
public static void main(String[] args)
So your program is not running because it can't find the main.
EDIT :
Just saying about your code, the loops and conditon are not necessay.
public static void main(String[] args ) {
int State = 0;
int Num1 = 0;
int Num2 = 0;
String Function = "";
Scanner reader = new Scanner(System.in);
System.out.println("Enter first number.");
Num1 = reader.nextInt();
reader.nextLine(); //Read the <enter> key
System.out.println("Enter the function.");
Function = reader.nextLine();
System.out.println("Enter the second number.");
Num2 = reader.nextInt();
System.out.println(Num1 + Function + Num2);
}

Your main method is missing mandatory argument:
public class Main {
public static void main(String[] args){
....
}
}
Secondly it will be terminating, because it will reach the end of the block, and then have no more instruction to run.
Your OOJCalculation method is invalid:
int calculation(int num1, int num2, String function) {
if ( "+".equals(function)) {
return num1 + num2;
} else if ( "-".equals(function)) {
return num1 - num2;
} else if ( "*".equals(function)) {
return num1 * num2;
}else if ( "/".equals(function)) {
return num1 / num2;
}
throw new IllegalArgumentException("Unknown operator");
}
it should start with lowerCase. Use also lov\wwer case for variables. CamelCase are reserved for class names and constructors. You have also wrongly declared returned type. Above implementation is covorrected.

Related

Continuous user input calculator

so I'm trying to create a simple calculator program that have these features:
Continuously calculating user input depending on the operation
Exit the program when user inputs 'x' in any part of the program
So far, I'm able to just calculate 2 numbers but what I need is for it to keep going until the user presses or inputs 'x'.
Sample output I want would be like this:
Num 1: 5
Operator: +
Num 2: 5
---------------
Result: 10
Operator: +
Number 3: 10
--------
Result: 20
and this keeps going until X is pressed
Here's my code so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
int result = 0;
String operator;
boolean isNumber;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter First Number: ");
if (scanner.hasNextInt()) {
num1 = scanner.nextInt();
isNumber = true;
} else {
System.err.println("Not a valid number");
isNumber = false;
scanner.next();
}
} while (!(isNumber));
System.out.println("Enter Operator ");
operator = scanner.next();
while (!operator.equals("+") && !operator.equals("-") && !operator.equals("*") && !operator.equals("/")) {
System.err.println("Invalid operator. Enter Correct Operation:");
operator = scanner.next();
}
do {
System.out.println("Enter Second Number: ");
if (scanner.hasNextInt()) {
num2 = scanner.nextInt();
isNumber = true;
} else {
System.err.println("Invalid Input. Enter Correct Number");
isNumber = false;
scanner.next();
}
} while (!(isNumber));
switch (operator) {
case "+":
addition(num1, num2, result);
break;
case "-":
subtraction(num1, num2, result);
break;
case "*":
multiplication(num1, num2, result);
break;
case "/":
division(num1, num2, result);
case "x":
System.exit(0);
}
}
public static void addition(int num1, int num2, int result) {
result = num1 + num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void subtraction(int num1, int num2, int result) {
result = num1 - num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void multiplication(int num1, int num2, int result) {
result = num1 * num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void division(int num1, int num2, int result) {
result = num1 / num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
}

Checking to see if a numbe is prime using methods

The answer is probably staring me in the face but I have been looking at this so long the words are blurring together. The assignment is to have the user input 3 numbers, add the numbers together using a method, then to determine if the sum is a prime number using a different method.
package chpt6_Project;
import java.util.Scanner;
public class Chpt6_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = scan.nextInt();
System.out.println("Enter the second number: ");
num2 = scan.nextInt();
System.out.println("Enter the third number: ");
num3 = scan.nextInt();
Chpt6_Project.sum(num1, num2, num3);
if(isPrime()) {
System.out.println("The number is prime");
} else {
System.out.println("The number is not prime.");
}
}
public static void sum(int num1, int num2, int num3) {
int total = num1 + num2 + num3;
System.out.println(total);
}
public static boolean isPrime(int total) {
if((total > 2 && total % 2 == 0) || total == 1) {
return false;
}
for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
if (total % i == 0) {
return false;
}
}
return true;
}
}
Edit the code as follow and you should do the trick.
The sum function now returns the sum calculated, this value is passed by main to the isPrime function which will return the right value
package chpt6_Project;
import java.util.Scanner;
public class Chpt6_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = scan.nextInt();
System.out.println("Enter the second number: ");
num2 = scan.nextInt();
System.out.println("Enter the third number: ");
num3 = scan.nextInt();
if(isPrime(Chpt6_Project.sum(num1, num2, num3))) {
System.out.println("The number is prime");
} else {
System.out.println("The number is not prime.");
}
}
public static int sum(int num1, int num2, int num3) {
int total = num1 + num2 + num3;
System.out.println(total);
return total;
}
public static boolean isPrime(int total) {
if((total > 2 && total % 2 == 0) || total == 1) {
return false;
}
for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
if (total % i == 0) {
return false;
}
}
return true;
}
Morover i guess this is an homework but there are better way of doing this. For example, there is no need for a sum function.

Is a number a multiple of the other in Java

I wrote a simple program to check if 2 numbers are multiples of each other.
My issue is that the program outputs that they are multiples no matter what integers are input.
Here's the code:
import java.util.Scanner;
public class twoIntegerMultiples {
public static void main(String[] args) {
int num1, num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.printf("%nEnter second number: ");
num2 = input.nextInt();
boolean multiple = isMultiple(num1,num2);
if(multiple = true){
System.out.printf("%n%d and %d are multiples of each other", num1, num2);
}
else{
System.out.printf("%n%d and %d are not multiples of each other", num1, num2);
}
}
public static boolean isMultiple(int num1, int num2){
int remainder = num1 % num2;
boolean multiple;
if (remainder != 0){
multiple = false;
}
else{
multiple = true;
}
return multiple;
}
}
Can someone help me out?
There is bug in your code.
if(multiple = true) // assigning true to multiple
Here your are assigning true to multiple. Bu you should compare true with multiple.
Replace above line with
if(multiple == true) // Checking if multiple is true or checking equality
In java = is assignment operator and == is equal to operator.
Another way
You can directly write multiple in your if condition:
if(multiple)
As if accepts boolean datatype we can directly use multiple in if.
You are using the wrong operator to check is multiple is true. Currently you have:
if(multiple = true) //....
With this, you are forcefully assigning true to multiple, and it will always be true. You need to have:
if(multiple == true) //... '==' to check for equality.
Also, your isMultiple() function can be simplified, using boolean logic, to this:
public static boolean isMultiple(int num1, int num2){
int remainder = num1 % num2;
boolean multiple = true;
if (remainder != 0){
multiple = false;
}
return multiple;
}
In fact, you could simplify this EVEN more like this:
public static boolean isMultiple(int num1, int num2){
return !(num1 % num2 != 0);
}
if(multiple = true)
That sets multiple to true then checks
If(multiple)
after it has been set true therefore it will always return true.
Use == for comparisons of primitive data types like int, char, boolean etc...
Here you have a complete program with the mistakes fixed.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num1, num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.printf("%nEnter second number: ");
num2 = input.nextInt();
boolean multiple = isMultiple(num1, num2);
if (multiple) {
System.out.printf("%n%d and %d are multiples of each other", num1, num2);
} else {
System.out.printf("%n%d and %d are not multiples of each other", num1, num2);
}
}
private static boolean isMultiple(int num1, int num2) {
int remainder = num1 % num2;
boolean multiple;
if (remainder != 0) {
multiple = false;
} else {
multiple = true;
}
return multiple;
}
}
Test
Enter first number: 350
Enter second number: 7
350 and 7 are multiples of each other
In addition to the improper use of the assignment operator, you must also observe that for integers a and b, then in general (a % b) != (b % a), e.g. 2%72 = 2 != 0 = 72%2.

In java, how to call the values from input class?

I can't figure out how to bring a variable from one method into another for use, especially that from input class. For example, this test program doesn't work. How would I make it work?
So here's my main class(Main.java):
class Main
{
public static void main(String args[])
{
Input f = new Input();
f.inputting(num1, num2, num3);
}
}
and my input class(Input.java):
import java.io.*;
class Input
{
void inputting(int number1, int number2, int number3)
{
Console d = System.console();
String a = d.readLine("Enter 1st number:");
String b = d.readLine("Enter 2nd number:");
String c = d.readLine("Enter 3rd number:");
int num1 = Integer.parseInt(a);
int num2 = Integer.parseInt(b);
int num3 = Integer.parseInt(c);
Sort e = new Sort();
e.sorting(num1, num2, num3);
}
}
and my sort class(Sort.java):
class Sort
{
void sorting(int number1, int number2, int number3)
{
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
if (number2 > number3) {
int temp = number2;
number2 = number3;
number3 = temp;
}
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.println("\nThe sorted numbers in ascending order are "
+ number1 + " " + number2 + " " + number3);
}
}
You are passing arguments into inputting with f.inputting(num1, num2, num3);, but you never declared num1, num2, or num3 in main.
If your intent is to do the user input from within the inputting method, you don't need the parameters for the inputting method, so you could do f.inputting(); in main and change the method declaration to void inputting().
This is how it should be
class Main
{
public static void main(String args[])
{
int num1=1;
int num2=2;
int num1=3;
Input f = new Input();
f.inputting(num1, num2, num3);
}
}
Also, you should use ELSE IF!, if not, it could enters the 3 ifs...
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
else if (number2 > number3) {
int temp = number2;
number2 = number3;
number3 = temp;
}
else if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
You need to either set up a global variable that sub classes or other classes use or you can call the variable from the class like so:
Class Main
class Main
{
public static void main(String args[])
{
Static int number1;
Static int number2;
Static int number3;
Input f = new Input();
f.inputting(number1, number2, number3);
}
}
Class Input
int Main.number1 = Integer.parseInt(a);
int Main.number2 = Integer.parseInt(b);
int Main.number3 = Integer.parseInt(c);

java calculator loop not working properly

For some reason my calculator won't wait for user input to finish the do while loop. I'm very new to java coding (currently only been doing it for a few hours). I want the user to be able to do more math before the program closes instead of having to reopen it every time they want to use it (obviously I don't mean anything serious by this I just want to learn and I think this will help.
heres my code
import java.util.Scanner;
public class calculator {
public static void main(String[] args){
double Answer;
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
while (yesorno = true){
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
} while (yesorno = true);
}
}
please ignore the akward formatting at the beggining and end of this code.
1) while(yesorno = true ) you are doing assignation
change to
while(yesorno == true) to prevent this thing you can use yoda style while(true = yesorno) then a compile error would throw cause you can't assign something to a value.
Or even more simpler just use while(yesorno)
2) Follow Java Code Convention , variable names are in lower case.
3)if this block get executed while (yesorno = true); you will have an infinite loop.
4) If you are using java 7 , you can do switch over strings
switch(op){
case "+":answer = num1 + num2;break;
case "-":answer = num1 - num2;break;
case "*":answer = num1 * num2;break;
case "/":answer = num1 / num2;break;
default: throw new IllegalArgumentException("Invalid operation "+ op);
}
System.out.println(answer);
You are assigning, not testing for equality in while (yesorno = true){. You should use while (yesorno == true){, since the double equals (==) tests for equality.
There were many errors, I have fixed it and commented it for you. Hope it helps:
import java.util.Scanner;
// KK: by general convention class names should always start with an upper case letter
public class calculator {
public static void main(String[] args) {
double Answer; //KK: local variable should be lower case
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
//KK: for comparing you need the double-equals
//KK: the loop will be executed as long as the expression is true, so for a boolean you don't need it at all
//KK: you can use either of the following:
// while (yesorno == true)
// while (yesorno)
while (yesorno) {
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
//KK: you need to call nextLine twice because you printed 2 lines here
//KK: otherwise again will be empty, so yesorno will always be true and you have an endless loop
again = input.nextLine();
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
}
// KK: the following line was an empty loop, that didn't do anything, so I commented it
// while (yesorno = true);
}
} //KK: this one was missing at the end too ;)
(I started my comments with KK, so you see them and can remove them later.)
Try this....
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean status = true;
while(status){
String answer = "";
String choise = "";
System.out.println("\"WELCOME TO JAVA CALCULATOR\"");
Scanner scn = new Scanner(System.in);
Scanner cal = new Scanner(System.in);
Scanner cho = new Scanner(System.in);
System.out.println("Enter the numers one by one that you want to calculate..");
int numA = scn.nextInt();
int numB = scn.nextInt();
int result = 0;
System.out.println("What you want to calculate...?");
answer = cal.nextLine();
if(answer.equals("+")){
result = numA+numB;}
if(answer.equals("-")){
result = numA-numB;}
if(answer.equals("*")){
result = numA*numB;}
if(answer.equals("/")){
result = numA/numB;}
System.out.println( "The result of " + numA + " and " + numB + " is : " + result);
System.out.println("Do you want to continue.....(y) or (n)?");
choise = cho.nextLine();
if(choise.equalsIgnoreCase("y")){
System.out.println("Welcome back.....:)\n\"Make By Saikat Halder\"");
status = true;}
if(choise.equalsIgnoreCase("n")){
System.out.println("Good bye....Thanks for useing java Calculator......:)");
System.exit(0);
}
}
}
}

Categories

Resources