How do i connect input variables from file 1 to file 2 - java

Im trying to make a simple calculator but with 2 files. The first file is for the normal code and the 2nd file is for the switch case. What im trying to do is to use the input from num1 num2 to switch.java My issue is that num1 num2 cannot be resolved to a variable in Switch.java
week1.java
import java.util.Scanner;
public class week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int operator2 = 0;
Switch swish = new Switch();
swish.switchcase();
}
}
Switch.java
import java.util.Scanner;
public class Switch
{
void switchcase()
{
switch(operator1){
case '+':
operator2 = num1 + num2;
System.out.println("Addition: " + (week1.num1) + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '-':
operator2 = num1 - num2;
System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '*':
operator2 = num1 * num2;
System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '/':
operator2 = num1 / num2;
System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
}
}
}

You must pass parameters to your switchcase method, and obtain a result back.
Class Week1:
import java.util.Scanner;
public class Week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int result = Switch.switchcase(num1, operator1, num2);
System.out.println(num1 + " " + operator1 + " " + num2 + " = " + result);
}
}
Class Switch:
public class Switch {
public static int switchcase(int num1, char operator1, int num2) {
switch(operator1){
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
}
}
}

Try using the below classes. Local variables inside a method will only be accessible inside that method. The variables has to be passed to another method for processing.
It is a best practice to begin class with capital letter.
Visit https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html
import java.util.Scanner;
public class Week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int operator2 = 0;
Switch swish = new Switch();
swish.switchcase(num1, operator1, num2);
}
}
public class Switch
{
void switchcase(int num1, char operator1, int num2)
{
int operator2;
switch(operator1){
case '+':
operator2 = num1 + num2;
System.out.println("Addition: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '-':
operator2 = num1 - num2;
System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '*':
operator2 = num1 * num2;
System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '/':
operator2 = num1 / num2;
System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
}
}
}

Related

Syntax error on token "{", SwitchLabels expected after this token-switch (char)

I'm banging my head against the wall.... I'm new...very new to this. I'm receiving an error "Syntax error on token "{", SwitchLabels expected after this token" at the bolded line - switch (operator) {. Every time I change it something else fails.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
// Prompt for 2 numbers and a symbol
Scanner scan = new Scanner(System.in);
//Prompt for input
System.out.println("Enter a number: ");
double num1 = scan.nextDouble();
System.out.println("Enter a number: ");
double num2 = scan.nextDouble();
System.out.println("Enter + - * or /");
char operator = scan.next().charAt(0);
switch (operator) {
/*previous attempt
//if (operator == "+")
// System.out.println(num1 + "+" + num2 + "=" + (num1+num2));
// else if (operator == "-")
// System.out.println(num1 - num2);
// else if (operator == "*")
// System.out.println(num1 * num2);
// else if (operator == "/")
// System.out.println(num1 / num2); */
double answer;
case "+":
answer = num1 + num2;
System.out.println(num1 + "+" +num2 + "=" + answer);
break;
case "-":
answer = num1 - num2;
System.out.println(num1 + "-" +num2 + "=" + answer);
break;
case "*":
answer = num1 * num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
case "/":
answer = num1 / num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
//reject all others
default:
System.out.println("Error: Not a valid symbol!");
break;
}
scan.close();
}
}
You were reading the operator as char and in the switch case you were using them as string. The below code should work for you.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) { // Prompt for 2 numbers and a symbol
Scanner scan = new Scanner(System.in);
//Prompt for input
System.out.println("Enter a number: ");
double num1 = scan.nextDouble();
System.out.println("Enter a number: ");
double num2 = scan.nextDouble();
System.out.println("Enter + - * or /");
char operator = scan.next().charAt(0);
double answer;
switch (operator) {
/*previous attempt
//if (operator == "+")
// System.out.println(num1 + "+" + num2 + "=" + (num1+num2));
// else if (operator == "-")
// System.out.println(num1 - num2);
// else if (operator == "*")
// System.out.println(num1 * num2);
// else if (operator == "/")
// System.out.println(num1 / num2); */
case '+':
answer = num1 + num2;
System.out.println(num1 + "+" +num2 + "=" + answer);
break;
case '-':
answer = num1 - num2;
System.out.println(num1 + "-" +num2 + "=" + answer);
break;
case '*':
answer = num1 * num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
case '/':
answer = num1 / num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
//reject all others
default:
System.out.println("Error: Not a valid symbol!");
break;
}
scan.close();
}
}
You cant define variables there, put the line double answer; before switch (operator) {
try this
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) { // Prompt for 2 numbers and a symbol
Scanner scan = new Scanner(System.in);
//Prompt for input
System.out.println("Enter a number: ");
double num1 = scan.nextDouble();
System.out.println("Enter a number: ");
double num2 = scan.nextDouble();
System.out.println("Enter + - * or /");
char operator = scan.next().charAt(0);
double answer;
switch (operator) {
case '+':
answer = num1 + num2;
System.out.println(num1 + "+" + num2 + "=" + answer);
break;
case '-':
answer = num1 - num2;
System.out.println(num1 + "-" + num2 + "=" + answer);
break;
case '*':
answer = num1 * num2;
System.out.println(num1 + "*" + num2 + "=" + answer);
break;
case '/':
answer = num1 / num2;
System.out.println(num1 + "*" + num2 + "=" + answer);
break;
//reject all others
default:
System.out.println("Error: Not a valid symbol!");
break;
}
scan.close();
}
}

How do I tell my program to ignore an instruction if a certain case is true?

I'm a very beginner java coder and I'm coding a simple calculator using swing, and I want to implement square roots into the operators. I want it to be so that in the case that the operator is a square root, the calculator wont ask for the second number.
package swingcalculator;
import javax.swing.JOptionPane;
public class SwingCalculator {
public static void main(String[] args) {
double num1, num2, answer;
String operator;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first number:"));
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch(operator) {
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
case "*":
answer = num1 * num2;
break;
case "/":
answer = num1 / num2;
break;
case "sqrt":
answer = Math.sqrt(num1);
break;
case "^":
answer = Math.pow(num1, num2);
break;
default:
System.out.println("You have entered an invalid operator");
return;
}
if (Boolean.parseBoolean(operator) == Boolean.parseBoolean("sqrt")){
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
else{
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
}
}
Any help would be appreciated!
Put everything after the operator = line inside a conditional (you can also move the JOptionPane.showMessageDialog lines inside the appropriate block of the conditional statement, because you don't need to check operator again):
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
if (!operator.equals("sqrt")) {
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch (...) { ... }
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
} else {
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
if(!operator.equals("sqrt"){
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
}
Read the second number only if operator is not 'sqrt', however your program seems to have many anomalies, as suggested to you in comments by others

Making a calculator using switch case

The result i get :
Enter a number :
5
Enter another number :
4
What do you want to perform on these numbers?
You have entered a wrong action, please try again
Where did i go wrong in my code?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
}
Instead of using sc.nextline() on line 15 use sc.next(). The program will now wait for your input before continuing.
Can you change your code like below:
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine(); // ADD THIS LINE
String word = sc.nextLine();
The problem here is with the num2 = sc.nextDouble(); the newline char is not consumed.
Below is the code I use:
public static void main(String args[]) throws Exception {
// A1Pattern.printPattern(26);
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine();
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
OUTPUT:
Enter a number :
1
Enter another number :
2
What do you want to perform on these numbers?
Subtraction
1.0 Subtraction 2.0 : -1.0
The java.util.Scanner.next() method finds and returns the next complete token from this scanner.
Use scanner.next() instead of scanner.nextLine().

JOptionPane showMessageDialog usage

i'm beginner for java.
I have a project for final mark. I did something but i need your help.
My project is about mathematical operations. I should use JOptionPane.
I could first part InputDialog But I can't show them in the messagebox ( i used println only to see how to work). And of course the division part is very important. If you try to divide by zero it should be error and should write something about error. I'm waiting your help. Thanks a lot and best regards.
import javax.swing.JOptionPane;
public class JavaMath3 {
public static void main(String[] args) {
int num1, num2, add, sub, multi;
double div;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Write 1st number."));
num2 = Integer.parseInt(JOptionPane.showInputDialog("Write 2nd number."));
add = num1+num2;
System.out.println("Addition " + add);
sub = num1-num2;
System.out.println("Subtraction " + sub);
multi = num1*num2;
System.out.println("Multiplication " + multi);
if(num2 != 0 ) {
div = (double) num1/num2;
System.out.println("Division: " + div);
}
else {
System.out.println("A number can not divided by zero.");
}
}
}
it's a very simple you can use the JOPtionPane method showMessageDialog
JOptionPane.showMessageDialog(parent, "your message");
and here's a sample code
public static void main(String[] args)
{
int num1 = Integer.parseInt(JOptionPane.showInputDialog("Write 1st number."));
int num2 = Integer.parseInt(JOptionPane.showInputDialog("Write 2nd number."));
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "sum = " + sum);
}
After update
here's a complete example
public static void main(String[] args)
{
int num1, num2, add, sub, multi;
double div;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Write 1st number."));
num2 = Integer.parseInt(JOptionPane.showInputDialog("Write 2nd number."));
add = num1 + num2;
sub = num1 - num2;
multi = num1 * num2;
String result = "sum = " + add + "\n" + "sub = " + sub + "\nmul = " + multi;
if (num2 != 0)
{
div = (double) num1 / num2;
result = result + " \n div = " + div;
} else
{
result = result + " \n div = A number can not divided by zero";
System.out.println("A number can not divided by zero.");
}
JOptionPane.showMessageDialog(null, result);
}
I don't get what mean by box but if you want them all in a same dialog box you could just write this line after your else statement:
JOptionPane.showMessageDialog(null, "Addition: " + add+ "\nSubtraction: " + sub+"\nMultiplication " + multi+ "\nDivision: " + div);

Java looping is not exiting when typing "quit"

Hello I can't seem to get my while loop to terminate the code when I'm typing the String "quit". Any help would be appreciated.
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args){
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while(true){
String calc;
String num1;
String num2;
num1 = userinput.next();
calc = userinput.next();
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if(calc.equals("+")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Add(x, y));
}
else if(calc.equals("-")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Subtract(x, y));
}
else if(calc.equals("*")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Multiply(x, y));
}
else if(calc.equals("/")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Divide(x, y));
}
else{
System.out.println("The operation is not valid.");
}
if(input[0].equalsIgnoreCase("quit")){
break;
}
}
System.exit(0);
}
}
The code is waiting on user input at calc = userinput.next();
public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
You should first validate the input inside its own condition.
Example:
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args) {
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while (true) {
String calc;
String num1;
String num2;
num1 = userinput.next();
calc = userinput.next();
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if (!input[0].equalsIgnoreCase("quit")) {
if (calc.equals("+")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Add(x, y));
} else if (calc.equals("-")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Subtract(x, y));
} else if (calc.equals("*")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Multiply(x, y));
} else if (calc.equals("/")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Divide(x, y));
} else {
System.out.println("The operation is not valid.");
}
} else {
break;
}
}
System.exit(0);
}
}
Try checking for the 'quit' before any of the other conditions:
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args){
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while(true){
String calc;
String num1;
String num2;
num1 = userinput.next();
if(num1.equalsIgnoreCase("quit")){
break;
}
calc = userinput.next();
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if(calc.equals("+")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Add(x, y));
}
else if(calc.equals("-")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Subtract(x, y));
}
else if(calc.equals("*")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Multiply(x, y));
}
else if(calc.equals("/")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Divide(x, y));
}
else{
System.out.println("The operation is not valid.");
}
}
System.exit(0);
}
}
The problem may have been that it is trying to parse 'quit' to an integer, which would cause an error and never reach the quit condition.
Or it could be that the code is waiting for an input at 'calc = userinput.next();', but i'm not sure if you tried entering the next two inputs
Code is probably stuck on the second next() call. Try just using a single call to nextLine() and a call to String::split
String input = userinput.nextLine(); // Get an entire line
if (input.equalsIgnoreCase("quit")){ // Check the exit first
break;
}
// If it hasn't exited assume that its an equation
String[] inputSplit = input.split(); // Split the input by spaces
String calc inputSplit[1];
String num1 inputSplit[0];
String num2 inputSplit[2];
I hope it will fit for you. I give it to some helping information to users when the program is running. You can try it out! :D
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args){
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while(true){
String calc;
String num1;
String num2;
System.out.print("Number 1 (if quit then program exits) =");
num1 = userinput.next();
if(num1.equalsIgnoreCase("quit")) {
System.out.println("program quit");
break;
}
System.out.print("Operator =");
calc = userinput.next();
System.out.print("Number 2 =");
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if(calc.equals("+")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Add(x,y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x+y));
}
else if(calc.equals("-")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Subtract(x, y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x-y));
}
else if(calc.equals("*")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Multiply(x, y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x*y));
}
else if(calc.equals("/")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Divide(x, y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x/y));
}
else{
System.out.println("The operation is not valid. You can give +, -, *, / for operator!");
}
}
System.exit(0);
}
}

Categories