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().
Related
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;
}
}
}
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();
}
}
My code works, but what I need it to do is when nothing is enter the evaluation for the highest and the lowest should be N/A. Right now all it displays is the max and min number when something isn't entered.
Example:
Press K for keyboard or F to read expressions from a file OR escape to exit:
k
Please Enter a Post-Fix Expression (eg: 5 2 *)
Application Closed
Evaluations complete....
Highest Value: -3.4028235E38
Lowest Value: 3.4028235E38
Agregate result: 0.0
Average result: NaN
Valid expressions: 0.0
Invalid Expressions: 0.0
I need the ones in bold to say n/a but i don't know how.
private static void keyboardService(){
while (true){
System.out.println("Please Enter a Post-Fix Expression (eg: 5 2 *)");
String postfix=keyboard.nextLine();
String [] elements =postfix.split(" ");
if (postfix.equals("")){
System.out.println("Application Closed");
evaluation();
System.exit(0);
}
if (elements.length == 3){
try{
num1 = Float.valueOf(elements[0]);
num2 = Float.valueOf(elements[1]);
float total;
if(elements[2].equals("+")){
total = num1 + num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("*")){
total = num1 * num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("/")){
total = num1 / num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("-")){
total = num1 - num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else{
display("Error Invalid Expression: "+ postfix);{
invalid_count = invalid_count + 1;
}
}} catch(NumberFormatException e){
display("Error Invalid Expresion: "+postfix);
invalid_count = invalid_count + 1;
} //end of second if
} else {
display("Error Invalid Expression: "+ postfix);
invalid_count = invalid_count + 1;
}
}
}//end of keyboard service
////////////////////////////////////////////////////////////////////////////////////////////////////////
private static void calc(float total){
highest = Math.max(highest, total );
lowest= Math.min(lowest, total);
aggregate = aggregate + total;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private static void evaluation(){
display("Evaluations complete....");
display("Highest Value: " + highest);
display("Lowest Value: " + lowest);
display("Agregate result: " + aggregate );
display("Average result: " + aggregate/valid_count);
display("Valid expressions: " + valid_count);
display("Invalid Expressions: " + invalid_count);
}
}
Here you go:
display("Highest Value: " + (highest == Float.MIN_VALUE ? "N/A" : String.valueOf(highest)));
display("Lowest Value: " + (lowest == Float.MAX_VALUE ? "N/A" : String.valueOf(lowest)));
and so on
In the evaluation method, before you print, check highest and lowest.
if (highest < 0)
display("Highest Value: " + "N/A");
else
display("Highest Value: " + highest);
Beside the fact that a better structure for you code would be the prefered solution you could achieve it with following changes in your code.
in your method ` keyboardService()
...
String [] elements =postfix.split(" ");
boolean validInput = true;
if (postfix.equals("")){
validInput = false;
in your method evaluation()
display("Highest Value: " + (validInput ? highest : "n/a"));
display("Lowest Value: " + (validInput ? lowest : "n/a"));
display("Agregate result: " + (validInput ? aggregate : "n/a"));
display("Average result: " + (validInput ? aggregate / valid_count : "n/a"));
display("Valid expressions: " + valid_count);
display("Invalid Expressions: " + invalid_count);
I am new to programming, first year college of BSIT and we were tasked to code a SimpleArithmetic where it will ask your name first and after that you will be asked to enter the first and the second integer.
After giving what is asked it must show "Hello (the name that was entered)" then what follows next is the sum, difference, product and the mod of the two integers and lastly it will show "Thank You!".
I tried a lot of codes but I will not run, so can someone help me? I would appreciate it really because I really want to learn how would that happen.
This was my code
public class SimpleArithmetic{
public static void main(String[] args){
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
System.out.print("Enter your name: ");
name = in.next(); // <---- HERE
System.out.printf("\nEnter first integer: ");
System.out.printf("\nEnter second integer: ");
System.out.printf("\nnum 1 + num 2");
System.out.printf("\nnum 1 - num 2");
System.out.printf("\nnum 1 * num 2");
System.out.printf("\nnum 1 % num 2");
System.out.print("Hello \n + name");
System.out.println("num 1" + "+" + "is" + "sum");
System.out.println("num 1" + "-" + "is" + "difference");
System.out.println("num 1" + "*" + "is" + "product");
System.out.println("num 1" + "%" + "is" + "mod");
System.out.print("Thank You!");
}
}
The bold one was the error when I tried to compile the java file
Use the class Scanner as below to read input:
Scanner scanner = new Scanner(System.in); // Init scanner
String name = scanner.nextLine(); // Reads a full line
int a = scanner.nextInt(); // Reads one integer
int b = scanner.nextInt(); // Reads another integer
Check documentation here if you like to know more about the class Scanner.
Basically Scanner is a useful class to read input from a stream (System.in) in that case. From javadoc
A simple text scanner which can parse primitive types and strings
using regular expressions.
The following will work for you...
package com.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SimpleArithmetic{
public static void main(String[] args){
try{
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = in.readLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
String str1 = in.readLine();
int number1 = Integer.parseInt(str1);
System.out.printf("\nEnter second integer: ");
String str2 = in.readLine();
int number2 = Integer.parseInt(str2);
System.out.print("Hello \n "+ name);
System.out.println("num 1" + "+" + "is" + (number1 + number2));
System.out.println("num 1" + "-" + "is" + (number1 - number2));
System.out.println("num 1" + "*" + "is" + (number1 * number2));
System.out.println("num 1" + "%" + "is" + (number1 % number2));
System.out.print("Thank You!");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Remove all the double qoutes on variables.
change System.out.print("Hello \n + name"); to
System.out.print("Hello \n + name);
System.out.println("num 1" + "+" + "is" + "sum"); to System.out.println("num 1" + "+" + "is" + sum);
System.out.println("num 1" + "-" + "is" + "difference"); to `System.out.println("num 1" + "-" + "is" + difference);`
System.out.println("num 1" + "*" + "is" + "product"); to System.out.println("num 1" + "*" + "is" + product);
System.out.println("num 1" + "%" + "is" + "mod"); to `System.out.println("num 1" + "%" + "is" + mod);`
Use Scanner and try catch block:
There is no declaration of variables which is listed in assignment comments.
You should have done something similar to this:
import java.util.Scanner;
public class SimpleArithmetic {
int num1 = 0, num2 = 0, sum = 0, difference = 0, product = 0, mod = 0;
String name = null;
Scanner in = null;
public static void main(String[] args) {
SimpleArithmetic sa = new SimpleArithmetic();
try {
sa.doSimpleArithmetic();
} catch (Exception e) {
e.printStackTrace();
}
}
void doSimpleArithmetic() throws Exception {
in = new Scanner(System.in);
System.out.print("Enter your name: ");
name = in.nextLine();
System.out.printf("\nEnter first integer: ");
num1 = Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
num2 = Integer.parseInt(in.nextLine());
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
mod = num1 / num2;
System.out.println("\n" + "Hello " + name + "\n");
System.out.println(num1 + " + " + num2 + " is :" + sum);
System.out.println(num1 + " - " + num2 + " is :" + difference);
System.out.println(num1 + " * " + num2 + " is :" + product);
System.out.println(num1 + " % " + num2 + " is :" + mod);
System.out.println("\n" + "Thank You!");
in.close();
}
}
try {
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
int nnum1=Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
int nnum2=Integer.parseInt(in.nextLine());
System.out.println("Hello \n" + name);
System.out.println("num 1" + "+" + "is " + (nnum1 + nnum2));
System.out.println("num 1" + "-" + "is " + (nnum1 - nnum2));
System.out.println("num 1" + "*" + "is " + (nnum1 * nnum2));
System.out.println("num 1" + "%" + "is " + (nnum1 % nnum2));
System.out.print("Thank You!");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("Please enter valid number");
e.printStackTrace();
}
I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...