Reopening a java program that is running - java

I have a calculator that I've been working on for school.
It's not going to have a typical calculator GUI though.
I have a beta version where I use input boxes in order to take the input.
I was actually wondering if there was a way to make a function to close it and then reopen it sort of like a loop.
import javax.swing.JOptionPane;
public class JOptionPaneCalc {
public static void main(String [] args){
char o = ' ';
String input = " ";
double num1 = 0;
double num2 = 0;
double result = 0;
while (true){
input = JOptionPane.showInputDialog("What is your operand? ");
o = input.charAt(0);
if (o == '/') {
result = num1 / num2;
break;
} else if (o == '*') {
result = num1 * num2;
break;
} else if (o == '+') {
result = num1 + num2;
break;
} else if (o == '-') {
result = num1 - num2;
break;
}else if (o == 'q'){
System.exit(0);
}
}
input = JOptionPane.showInputDialog("What is your first number? ");
num1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("What is your second number? ");
num2 = Double.parseDouble(input);
if (o == '/') {
result = num1 / num2;
} else if (o == '*') {
result = num1 * num2;
} else if (o == '+') {
result = num1 + num2;
} else if (o == '-') {
result = num1 - num2;
}else if (o == 'q'){
System.exit(0);
}
JOptionPane.showMessageDialog(null ,"Your answer is : " + result);
}
}
This is what I have, hopefully you can help me

There are quite a few issues with your code. If o == 'q', then your program will exit for good.
}else if (o == 'q'){
System.exit(0);
}
Read about repetition.
If you want your program to loop, then you should write it at least like this:
public static void main(String[] args) {
char o;
String input;
double num1;
double num2;
double result=0.;
input = JOptionPane.showInputDialog("What is your operand? ");
o = input.charAt(0);
while (o!='q') {
input = JOptionPane.showInputDialog("What is your first number? ");
num1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("What is your second number? ");
num2 = Double.parseDouble(input);
if (o == '/') {
result = num1 / num2;
} else if (o == '*') {
result = num1 * num2;
} else if (o == '+') {
result = num1 + num2;
} else if (o == '-') {
result = num1 - num2;
}
JOptionPane.showMessageDialog(null ,"Your answer is : " + result);
input = JOptionPane.showInputDialog("What is your operand? ");
o = input.charAt(0);
}
}
Keep in mind that your users must be very sober, in order to avoid typos and receiving a NumberFormatException...

Related

Return to start of the Java code(main menu of calculator)

I am new and somewhat a noob to Java, and I'm trying to make a calculator, didn't test everything to see if it works, but I'm having a problem. I can't seem to figure out how do I get back to the main menu after performing one calculation. I have added that question in the end to make it prompt the user either to exit or continue back to the main menu. I just don't know what to put in the if(whatnow == Y){ wtf am i supposed to do to get back to the main menu?? }. Sorry if it was a bit long or something, but they're really all the same so just skip the calculation thingy. Any help appreciated. I am really new to java and i probably have to write this code all over again.
package practice;
import java.util.Scanner;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int choice;
int firstnumber;
int secondnumber;
int result;
char whatnow;
System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
System.out.println("Made with love and basic Java");
System.out.println("Which math operation would you like to perform?");
System.out.println("");
System.out.println("WARNING: Enter the integer x, press ENTER, then enter y");
System.out.println("");
System.out.println("[1]-Addition (+)");
System.out.println("[2]-Subtraction (-)");
System.out.println("[3]-Multiplication (x)");
System.out.println("[4]-Division (/)");
System.out.println("");
System.out.println("Enter your choice[1-4 or 99]:"); choice = scan.nextInt();
while ((choice < 1 || choice > 4) && choice != 99) {
System.out.println("Please enter 1, 2, 3, 4, or 99: ");
choice = scan.nextInt();
}
if (choice == 1){
System.out.println("Enter two integer to add(x + y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
result = firstnumber + secondnumber;
System.out.println(firstnumber + " + " + secondnumber + " = " + result);
}
else if (choice == 2) {
System.out.println("Enter two integers to subtract(x - y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
result = firstnumber - secondnumber;
System.out.println(firstnumber + " - " + secondnumber + " = " + result);
}
else if (choice == 3) {
System.out.println("Enter two integers to multiply(x * y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
result = firstnumber * secondnumber;
System.out.println(firstnumber + " * " + secondnumber + " = " + result);
}
else if (choice == 4) {
System.out.println("Enter to integers to divide(x / y)");
firstnumber = scan.nextInt();
secondnumber = scan.nextInt();
while (secondnumber == 0) {
System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:");
secondnumber = scan.nextInt();
}
result = firstnumber / secondnumber;
System.out.println(firstnumber + " / " + secondnumber + " = " + result);
}
else if (choice == 99) {
System.exit(0);
}
while (choice !=99) {
System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0);
if (whatnow == 'Y' || whatnow == 'y') {
}
if (whatnow == 'N' || whatnow == 'n') {
System.exit(0);
}
}
}
}
P.S: I edited the end to look something like this with a while(true) at the beginning:
`while (choice !=99) {
System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0);
while(whatnow != 'Y' || whatnow != 'y' || whatnow !='N' || whatnow !='n') {
System.out.println("Enter [Y/N] only:"); whatnow = scan.next().charAt(0);
}
if (whatnow == 'N' || whatnow == 'n') {
System.exit(0);`
You just need to repeat everything you have written until the user insert N. So all you want to do is put everything inside a while(true) loop, whose last instruction will be:
if (whatnow == 'N' || whatnow = 'n') {
System.exit(0);
}
This way, if the user inserts anything besides N or n the loop will bring him back to the main menu printing section, so maybe you would need to add a test on the value of whatnow in the same way you did for choice.
The result will be like this:
public static void main(String[] args){
...
while(true){
System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
...
while (choice !=99) {
System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0);
//insert some loop to ensure that the value of whatnow will be either Y or N
if (whatnow == 'N' || whatnow == 'n') {
System.exit(0);
}
}
}
}
EDIT
Here is a sample code of what I anticipated with my last comment:
public static void main(String[] args){
char whatnow = 'Y';
Scanner scan = new Scanner(System.in);
while (whatnow != 'N' && whatnow != 'n') {
int choice = printMenuAndAsk(scan);
if (choice == 99)
break;
else performOperation(choice, scan);
System.out.println("Do you want to continue calculating? [Y/N]:");
whatnow = scan.next().charAt(0);
while(whatnow != 'N' && whatnow != 'Y' && whatnow != 'n' && whatnow != 'y') {
System.out.println("Incorrect answer");
whatnow = scan.next().charAt(0);
}
}
scan.close();
}
public static int printMenuAndAsk(Scanner scan) {
int choice;
System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
...
System.out.println("Enter your choice[1-4 or 99]:");
choice = scan.nextInt();
while ((choice < 1 || choice > 4) && choice != 99) {
System.out.println("Please enter 1, 2, 3, 4, or 99: ");
choice = scan.nextInt();
}
return choice;
}
public static void performOperation(int operation, Scanner scan) {
System.out.println("Enter first:");
int firstnumber = scan.nextInt();
System.out.println("Enter second:");
int secondnumber = scan.nextInt();
if (choice == 1)
System.out.println(firstnumber + " + " + secondnumber + " = " + (firstnumber+secondnumber));
else if (choice == 2)
System.out.println(firstnumber + " - " + secondnumber + " = " + (firstnumber-secondnumber));
else if (choice == 3)
System.out.println(firstnumber + " * " + secondnumber + " = " + (firstnumber*secondnumber));
else if (choice == 4) {
while (secondnumber == 0) {
System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:");
secondnumber = scan.nextInt();
}
System.out.println(firstnumber + " / " + secondnumber + " = " + (firstnumber/secondnumber));
}
}
Instead of trying to put a while loop at the end, try to put your entire code in awhile(true) block. Using an if statement at the end, you can ask whether the user wants to continue our not. Exit the loop by using thebreak keyword.
Try to exit like this:
if(input == 'n'){break;}
What this does is that it exits the while loop. You can execute more instructions outside the while block.
You could change it as follows:
Your main method as such:
public static void main(String[] args) {
calc();
}
And then create a method named calc():
public static void calc() {
Scanner scan = new Scanner(System.in);
//the rest of your code
} else if (choice == 99) {
System.exit(0);
}
calc(); //call the method again at the end of your code
//remove your while loop
}

Java Beginner, Why does my Program keep terminating?

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.

Simple calculator program in Java

I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.
I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}

Java calculate numbers in a string

I'm making a calculator program that can read in a string like this:
67+12-45
How can I perform the function that the string is intending to do? Here's what I've tried so far:
public static int calculate(String expression, int num1, int num2)
{
int answer = 0;
switch(expression)
{
case "+":
if(answer != 0)
{
answer = answer + num1 + num2;
}
else
{
answer = num1 + num2;
}
break;
case "-":
if(answer != 0)
{
answer = answer + (num1 - num2);
}
else
{
answer = num1 - num2;
}
break;
case "*":
if(answer != 0)
{
answer = answer + (num1 * num2);
}
else
{
answer = num1 * num2;
}
break;
case "/":
if(answer != 0)
{
answer = answer + (num1 / num2);
}
else
{
answer = num1 / num2;
}
break;
case "%":
if(answer != 0)
{
answer = answer + (num1 % num2);
}
else
{
answer = num1 % num2;
}
break;
}
return answer;
}
Is there a simpler way to perform the function intended in the string?
the easiest way to achieve this is using eval, you can do this:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("67+12-45"); //you can insert any expression here
This talk describes an Object Oriented solution to this problem:
http://youtu.be/4F72VULWFvc?t=7m40s
Essentially, you can parse the string into an expression tree that can be evaluated.

Why is my program crashing (java)?

I need to convert hexadecimal to decimal using different methods. When I enter numbers that are correct hexadecimal numbers, my program displays the decimal value and says that the number is valid. However, when I enter incorrect hexadecimal values, my program crashes.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
switch(choice){
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
if (isValid) {
System.out.println(hex + " is valid");
}
break;
case 'n':
System.out.print("Quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
public static long convert (String hexValue) {
long decimal = 0;
boolean isNegative = false;
int a = 0;
if (hexValue.charAt(0) == '-') {
isNegative = true;
a = 1;
}
for (int i = a; i<hexValue.length(); i++) {
decimal = decimal*16;
if (hexValue.charAt(i) >= '0' && hexValue.charAt(i) <= '9') {
decimal += hexValue.charAt(i) - '0';
}
else if (hexValue.charAt(i) >= 'a' && hexValue.charAt(i) <= 'f') {
decimal += hexValue.charAt(i) - 'a' + 10;
}
}
if (isNegative == true) {
decimal *= -1;
}
return decimal;
}
}
why is it crashing and how can I fix it so that it displays "invalid" when incorrect hexadecimal digits are entered?
If you enter an invalid hex number, Integer.parseInt() will throw NumberFormatException. Change your code like this:
...
isValid = valid(hex);
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
...
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
int base = 10;
switch(choice)
{
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase(); //I'm not sure if this step is necessary
try {
Integer value = Integer.parseInt(hex, 16);
System.out.println("Valid hex format");
System.out.println("Hex: " + hex);
System.out.println("Decimal: " + value);
}
catch (NumberFormatException e) {
System.out.println("Invalid hex format");
System.out.println("Input: " + hex);
}
break;
case 'n':
System.out.print("Quit");
break
}
} while (choice != 'n');
Now you can delete all your helper methods
Add Integer value = Integer.parseInt(hex,16); inside if statement and print invalid in else block.
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
else{
System.out.println("invalid");
}
Updated:
Change your valid method as follows:
public static boolean valid(String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i = a; i < validString.length(); i++) {
// if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F') || (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) {
// return false;
// }
char ch=validString.charAt(i);
if(!(Character.isDigit(ch) || (Character.isLetter(ch) && ((ch-'A')<=5))) ){
return false;
}
}
return true;
}

Categories

Resources