Having trouble with java contains - java

How do I check if a variable is equal or not equal to a contains? I want to make it so if someone where to put in an invalid operator it would say try again.
String operator = "+, -, *,/, %";
double num1, num2, sum=0;
System.out.println("First number: ");
num1 = input.nextDouble();
System.out.println("Second number: ");
num2 = input.nextDouble();
if (operator.contains("+")){
sum = num1 + num2;
} else if (operator != operator.contains("+,-,*,/,%"){
System.out.println("Error");
}

If you want to check what operator should be used based on the user entry, you could use switch statement as below
String operator = "";
while (operator.isEmpty()) {
System.out.println("Enter Operator: ");
operator = input.next();
switch (operator) {
case "+" : result = num1 + num2; break;
case "-" : result = num1 - num2; break;
case "*" : result = num1 * num2; break;
case "/" : result = num1 / num2; break;
default : System.out.println("Invalid operator: " + operator);
operator = "";
}
System.out.println("Result is " + result);
}
DEMO
If you only want to check if the operator is valid, you can use List contains() method:
String[] operators = { "+", "-", "*", "/" , "%" };
List<String> ops = Arrays.asList(operators);
:
System.out.println("Enter Operator: ");
String operator = input.next();
if (ops.contains(operator)) {
// do some calculation here
}

Related

How do I stop my code from executing every println after I execute the right code?

Scanner scan = new Scanner(System.in);
System.out.print("Enter 2 numbers: ");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
System.out.println("Numbers Saved! Choose your operator + - * / ");
String operator = scan.next();
int result;
result = (operator.equals("+")) ? (num1 + num2) : (num1);
System.out.println("The addition result is " +result);
result = (operator.equals("-")) ? (num1 - num2) : (num1);
System.out.println("The subtraction result is " +result);
result = (operator.equals("*")) ? (num1 * num2) : (num1);
System.out.println("The multiplication result is " +result);
result = (operator.equals("/")) ? (num1 / num2) : (num1);
System.out.println("The division result is " +result);
}
}
This is my simple calculator code, for example when i choose the + option, it runs all System.out.println lines, how do I prevent it from doing this and only execute the println that matches the operator?
Try a switch:
switch (operator) {
case "+":
result = num1 + num2;
System.out.println("The addition result is " + result);
break;
case "-":
result = num1 - num2;
System.out.println("The subtraction result is " + result);
break;
case "-":
result = num1 * num2;
System.out.println("The multiplication result is " + result);
break;
case "/":
result = num1 / num2;
System.out.println("The integer division result is " + result);
break;
default:
throw IllegalArgumentException("Unsupported operator: " + operator);
}
I would encapsulate the operator logic (resolution and evaluation) into an enum. Like,
enum Oper {
ADDITION("+"), SUBTRACTION("-"), MULTIPLICATION("*"), DIVISION("/");
Oper(String symbol) {
this.symbol = symbol;
}
public int eval(int a, int b) {
switch (this) {
case ADDITION: return a + b;
case SUBTRACTION: return a - b;
case MULTIPLICATION: return a * b;
case DIVISION: return a / b;
}
return -1;
}
private String symbol;
public static Oper from(String operator) {
for (Oper o : values()) {
if (o.symbol.equals(operator)) {
return o;
}
}
return null;
}
}
That simplifies the logic in main, just resolve the operator and evaluate it. Like,
Oper o = Oper.from(operator);
System.out.printf("The %s result is %d%n", o.name().toLowerCase(), o.eval(num1, num2));

Calling variable when using Scanner Class and Multiple Classes

Trying to call the total value from the operatorSelection class while that class references what the user enters as the operator.
I want it to end up coming out as number1 (operator chosen) number2...= total.
Not sure how to call class so that it prints the " System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total); " correctly.
Any knowledge would be greatly appreciated on the subject.
Thanks.
import java.util.Scanner;
class NumbersEntered
{
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
double total = 0;
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total);
}
}
Your problem is that you declare the total variable within the operatorSeletion method, and you try to access it without specifying it's location. You need to declare the total variable as a field, and then access it at its location (new NumbersEntered().total). Also, you never invoke operatorSeletion, which might help ;)
class NumbersEntered {
public double total = 0; //declare as accessable field
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
nums.operatorSeletion(number1, number2, number3, operator);
//invoke the method
System.out.println(number1 + " " + operator + " " + number2 + " " + operator + " " + number2 + " = " + nums.total);
//Access at location (nums.total)
}

logical bug in my code in java... in switch case

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please select your operator:\n"
+ "1 for +\n" +
"2 for -\n" +
"3 for *\n" +
"4 for %\n" +
"");
operator = myScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" +
"y for yes\n" +
"n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput=='n') ask=false;
}
}
}
i got trouble in my switch case
if i press any number or letter somthing like 5 or 6 or... it should print you chose wrong operator.
i think problem is in my default but i don't know where is it?
Just reorder your code like this
`public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
System.out.println("please select your operator:\n"
+ "1 for +\n"
+ "2 for -\n"
+ "3 for *\n"
+ "4 for %\n"
+ "");
operator = myScanner.nextInt();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("you chose " + operator + " operator babe");
System.out.println("do yo want to continue?\n"
+ "y for yes\n"
+ "n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput == 'n') {
ask = false;
}
}
}`
and you'll be fine
as for my comment, if you want to validate the input the user does (for the option) before having the user input another 2 numbers, than, yeah you should actually programm it that way that the validation goes RIGHT AFTER the first userinput. HereĀ“s a slightly corrected version of your code.
public static void main(String[] args) {
int operator;
double result;
boolean ask = true;
Scanner numberScanner = new Scanner(System.in);
while (ask) {
System.out.println(
"please select your operator:\n" + "1 for +\n" + "2 for -\n" + "3 for *\n" + "4 for %\n" + "");
operator = numberScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
// Here was your "Mistake". You instantly started asking the user for another input,
// but actually wanted to ahve the switch statment here
switch (operator) {
case 1:
result = get_num1(numberScanner) + get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 2:
result = get_num1(numberScanner) - get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 3:
result = get_num1(numberScanner) * get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 4:
result = get_num1(numberScanner) % get_num2(numberScanner);
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" + "y for yes\n" + "n for no\n");
char askInput = numberScanner.next().charAt(0);
if (askInput == 'n')
ask = false;
}
}
public static double get_num1(Scanner scanner) {
System.out.println("please enter your first number");
return scanner.nextDouble();
}
public static double get_num2(Scanner scanner) {
System.out.println("please enter your second number");
return scanner.nextDouble();
}
simply you could validate the operator while you assign it with the input.
for example use if condition and check whether its between 1 and 5 and if not print whatever you want
2 things:
you dont need 2 scanners using only one will be enough
the code is behaving so because you go into the switch case AFTER asking the numbers you want to operate...
some condition like:
operator = myScanner.nextInt();
if (operator < 1 || operator > 4) {
}
may help....

How to use math operators from commandline in program?

I try to calculate digits (in my calculator) in args from commandline. Example:
args[0] = 2*3;
String result = method(args[0]);
System.out.println(result) // should be 6
I don't know how to use my char between two digits example "+", "-". I can't use loops. My method idea is use charAt like:
char a = arg.charAt(0);
char b = arg.charAt(1);
char c = arg.charAt(2);
But I don't know to change my b char (*) to do calculation.
You are not passing the value correctly. Your input is a String, right? Your code shows an integer expression.
args[0] = "2*3"; //note that this changed to a string
double result = parse(args[0]);
System.out.println(result) // should be 6
Then you can parse your string in your method:
double parse(String str){
int num1 = Integer.valueOf(str.substring(0,1));
char operator = str.charAt(1);
int num2 = Integer.valueOf(str.substring(2,3));
switch(operator){
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
case '/': return num1/num2;
default: throw new IllegalArgumentException();
}
}
Running System.out.println(parse("2*3")); prints 6.0 with my code.
Of course this only works with operands that have exactly one digit. But that's a restriction that comes from your charAt idea.
I'm not normally using JAVA, but..
You will get the input as a string, if you run a process like this:
> MyCalculator 2*3
now, you want to separate this string into three parts:
Number1, Operation, Number2
for this you can do something like:
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
now, you may notice that you'll be missing the operator..
so you want locate it and fetch it, or you can do something like this:
if( args[0].indexOf("*") > -1)
{
System.out.println(Number1 * Number2);
}
edit:
for more flexibillity, you may want to do it the opposite way around:
if( args[0].indexOf("*") > -1)
{
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 * Number2);
}
if( args[0].indexOf("/") > -1)
{
String[] parts = args[0].split("/");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 / Number2);
}
etc...
notice that "-" will be especially annoying
Its not the best solution but it works, you can enter numbers of any length.
String[] number = args[0].split("[*]|[/]|[+]|[-]");
int stringLength = args[0].length();
int operatorBeginning = number[0].length();
int operatorEnd = stringLength - number[1].length();
String operator = args[0].substring(operatorBeginning,operatorEnd);
double answer = 0;
switch(operator) {
case "*":
answer = Integer.valueOf(number[0]) * Integer.valueOf(number[1]);
break;
case "/":
answer = Integer.valueOf(number[0]) / Integer.valueOf(number[1]);
break;
case "+":
answer = Integer.valueOf(number[0]) + Integer.valueOf(number[1]);
break;
case "-":
answer = Integer.valueOf(number[0]) - Integer.valueOf(number[1]);
break;
default:
System.out.println("Wrong operator");
break;
}
System.out.println(answer);

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");
}

Categories

Resources