This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.* ;
class Main {
public static double op(String operation, double number1, double number2) {
double x = 0;
if (operation == "+") {
x = number2 + number1;
}
else if (operation == "x" || operation == "*") {
x = number1 * number2;
}
else if (operation == "/" || operation == "÷") {
x = number1 / number2;
}
else if (operation == "-") {
x = number1 - number2;
}
else {
System.out.println("Error: Please re-execute the program and try again!");
}
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
System.out.println("Please enter a number...");
double x = input.nextDouble();
System.out.println("Please enter an operation.... +, -, /, *");
String y = input.next();
System.out.println("Please enter your other number...");
double z = input.nextDouble();
System.out.println(op(y, x, z));
}
}
I want this function to return the correct value when the operation is performed. However, it always returns 0 the initial value assigned. Please help!!!
String comparison should always be done using equals try the below code :-
public static double op(String operation, double number1, double number2) {
double x = 0;
if (operation.equals("+")) {
x = number2 + number1;
}
else if (operation.equals("x") || operation.equals("*")) {
x = number1 * number2;
}
else if (operation.equals("/") || operation.equals("÷")) {
x = number1 / number2;
}
else if (operation.equals("-")) {
x = number1 - number2;
}
else {
System.out.println("Error: Please re-execute the program and try again!");
}
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
System.out.println("Please enter a number...");
double x = input.nextDouble();
System.out.println("Please enter an operation.... +, -, /, *");
String y = input.next();
System.out.println("Please enter your other number...");
double z = input.nextDouble();
System.out.println(op(y, x, z));
}
Related
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);
}
}
I have two classes: MyNumbers and MyScanner. I am trying to pass the validated inputs to the calculateSum (int x, int y) method in order to print the final result in the MyScanner class, but I don't know how I can take the user inputs from the MyScanner class to pass them to the validate() method in the MyNumbers class so that it allows the calculateSum() method to perform its task.
P.S. validate() method should be void and parameterless, but calculateSum() method should be string to return the result as a string and take two parameters. I also want the validate() method to prompt for user input and validate the values to make sure that they are in the certain range. This method needs to keep prompting until user inserts a valid number.
How can I achieve this without introducing another variable/implementing setters/ passing variables as a parameter to the validate() method?
public class MyNumbers {
int number1;
int number2;
public void validate() {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
validate();
return "Sum: " + number1 + number2;
}
}
public class MyScanner {
public static void main(String[] args) {
MyNumbers myNumbers = new myNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
do{
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.calculateSum(x, y);
break;
}
}
while(option!=0);
}
}
EDIT :
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate() {
int valid=0;
int x;
int y;
Scanner s = new Scanner(System.in);
System.out.println("Welcome!");
do{
System.out.println("Enter Number 1: ");
x = s.nextInt();
if (x >= 10 && x <= 50) {
valid=2;
}
else {
System.out.println("Number 1 should be between 10 and 50");
}
}while(valid!=2);
do {
System.out.println("Enter Number 2: ");
y = s.nextInt();
if(y >= 5 && y <= 20){
System.out.println(calculateSum(x, y));
valid=3;
}
else {
System.out.println("Number 2 should be between 5 and 20");
}
}while(valid!=3);
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + (number1 + number2);
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
myNumbers.validate();
}
}
Try
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate(int number1 , int number2) {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + number1 + number2;
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.validate(x, y);
myNumbers.calculateSum(x, y);
break;
}
}
}
Having a problem getting the program to keep running after an error message has occurred. I have tried using different If/Else or While loops to get it to work but none seem to be giving any luck. The current code posted works until you enter something other than y, Y, n, or N. The error message will keep popping up after even if i enter y, Y, n, or N.
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class FutureValueApp {
public static void main(String[] args) {
// Avery Owen
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment, interestRate,
years, futureValue);
// see if the user wants to continue
choice = askToContinue(sc);
}
}
public static double getDoubleWithinRange(Scanner sc, String prompt,
double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
try {
i = sc.nextInt();
isValid = true;
} catch (InputMismatchException e) {
System.out.println("Error! Enter a whole number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static double calculateFutureValue(double monthlyInvestment,
double monthlyInterestRate, int months) {
double futureValue = 0;
for (int i = 1; i <= months; i++) {
futureValue = (futureValue + monthlyInvestment) *
(1 + monthlyInterestRate);
}
return futureValue;
}
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
}
return choice;
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue) {
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
// print the results
System.out.println(results);
}
}
Try this:
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
System.out.print("Continue? (y/n): "); //this was missing
choice = sc.next(); //take the input again
}
return choice;
}
You are getting stuck in a while loop in case of invalid input and not accepting the input again.
I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}
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);