Lets say you have:
int number1 = 5;
int number2 = 5;
char operator = '*';
How can I use the character for a calculation: number1 (operator) number2 = 5*5
Edit: It was my first time posting anything on this site and I am also an amateur, so I guess thats why I got downvoted 8x cus it was unclear but ty for the people who answered. Will be more thorough next time :)
You can use switch or a simple if condition for an example
if(operator == '*'){
int total = number1 * number2;
}else if(operator == '+'){
int total = number + number2;
}
Like this you can do the calculations
you can use switch case for your purpose.
if operator is char type than
int result=0;
switch(operator){
case '+':
result=number1+number2;
case '-':
result=number1-number2;
case '*':
result=number1*number2;
case '/':
result=number1/number2;
}
Related
I'm a new java coder getting into it doing a project. I coded it how i believe the system would execute it and yet it doesn't seem to be following the While loops requirements. I want it to generate random number, do a random operation, then ask the user for an answer. The answer must be not decimal and the random numbers must be below 10 to make the questions easier as its for a lower target audience. I'm kind of stuck now on this piece. Apologies if this doesn't make sense as i say it is a first attempt for me.
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
public class RandomisedQuestions{
public static void QuestionGenerator(){
Random r = new Random();
Scanner s = new Scanner(System.in);
int intA = 0;
int intB = 0;
char operator ='?';
double value = 1.2;
for (int i = 0; i < 3; i++) {
intA = (int)(10.0 * Math.random());//the (int) forces the number to be an int
intB = (int)(10.0 * Math.random());
if (intA <= 0 && intB <= 0){
intA = (int)(10.0 * Math.random());//the (int) forces the number to be an int
intB = (int)(10.0 * Math.random());
System.out.println(intA + intB);
}
while ((value % 1) !=0 && value > 1){//Runs while value is not whole
switch (r.nextInt(4)){
case 0: operator = '+';
value = intA+intB;
break;
case 1: operator = '-';
value = intA-intB;;
break;
case 2: operator = '*';
value = intA*intB;;
break;
case 3: operator = '/';
value = intA/intB;;
break;
default: operator = '?';
}
//System.out.println(operator);
}
System.out.println(intA +""+ operator +""+ intB);
System.out.println("Enter the answer");
int uGuess = s.nextInt();
if (uGuess == value){
System.out.println("Correct");
}
else{
System.out.println("Incorrect");
}
}
}
}
It's better to use ThreadLocalRandom.nextInt to generate your numbers:
// At the start of your program initialize the generator:
ThreadLocalRandom r = ThreadLocalRandom.current();
// Later use it:
do {
intA = ThreadLocalRandom.nextInt(1, 10);
intB = ThreadLocalRandom.nextInt(1, 10);
switch (r.nextInt(4)) {
case 0: operator = '+';
value = intA + intB;
break;
case 1: operator = '-';
value = intA - intB;
break;
case 2: operator = '*';
value = intA * intB;
break;
case 3: operator = '/';
value = (double)intA / intB;
break;
default: operator = '?';
}
} while (value != (int)value || value <= 1);
Also note the conversion to double in division case, otherwise the division will be performed for integer types.
I'm trying to create a random sum generator that generators random sums!
The only problem with what I created is, it can generate sums that have a negative result as well. So I want it to only generate sums with positive outcomes.
Example:
7-10 = -3
My code:
number1 = (int)(Math.random()* LT) + 1;
number2 = (int)(Math.random()* LT) + 1;
operator = (int)(Math.random()* OP) + 1;
switch(operator) {
case 1:
operation = "+";
result = number1 + number2;
break;
case 2:
operation = "-";
result = number1 - number2;
break;
case 3:
operation = "*";
result = number1 * number2;
break;
case 4:
operation = "/";
result = number1 * number2;
break;
}
Since you will always be dealing with positive integers your only issue is checking for negative numbers in your subtraction case. I would also recommend switching to the Random class to generate random integers. One way to get around negative results is to flip the numbers you are subtracting.
boolean flip = false;
int num1, num2, op, result;
String operation;
Random r = new Random();
num1 = r.nextInt(8)+2;
num2 = r.nextInt(8)+2;
op = r.nextInt(4);
switch(op) {
case 0:
// Always be positive.
operation = "+";
result = num1+num2
break;
case 1:
// Could be negative if num2 is larger than num1. Simply flip the numbers.
flip = num1 < num2;
operation = "-";
result = flip ? num2-num1 : num1-num2;
break;
case 2:
// Always be positive.
operation = "*";
result = num1*num2;
break;
case 3:
// Always be positive.
operation = "/";
result = num1/num2;
break;
}
The simplest fix you can do is let the random operation complete. I assume you do multiple loops of {add,sub,mult,divide}. If the final result is negative, convert it back to positive.
But a more distributed random number generation can be done with the java runtime:
double d = java.lang.Math.random() * MAX_RANDOM_VALUE; // MAX_RANDOM_VALUE is a max value you define, like 100000
int result = (int)d;
You haven't mentioned anything about required distribution of outputs, but if it's really as simple as making sure you have no negative outputs, you could pass each output through Math.abs() before returning it...
As far as I understood you want to pick random number from the set of positive integers which can be written as a + b where a and b are integers. Since every positive integer between 1 and the maximum value of a+b, can be written like this, you just want to select a random positive integer.
int result = new Random().nextInt(maxPossibleSumValue);
Since random number generated would be in the range 0-1. You will get negative result only when you are subtracting two numbers and number2 is greater than number1. In this case you can simply swap number1 and number2 if number2 is greater than number1.
For some class homework I need to create a program that converts roman numerals to decimal form. I can convert just fine as long as there are no exception characters such as IV or IX. How do I check for these exceptions? My attempt was to translate both the current character and the next one into decimal, then to compare them and if the next one (going right to left) is smaller to then subtract it. The problem is that I get out of bounds errors from this.
My current code is this:
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (int count = roman.length()-1; count >= 0; count--)
{
char numeral = roman.charAt(count);
switch (numeral){
case 'I':
decimal = 1;
break;
case 'V':
decimal = 5;
break;
case 'X':
decimal = 10;
break;
case 'L':
decimal = 50;
break;
case 'C':
decimal = 100;
break;
case 'D':
decimal = 500;
break;
case 'M':
decimal = 1000;
break;
default:
System.out.println("Error: Invalid character detected.");
break;
}
number = number + decimal;
}
System.out.println("The decimal equivalent is: " + number);
System.out.println("Later!");
I'm still a beginner and most of the information I see on this kind of problem uses advanced solutions that I simply don't understand. I know I need to compare the characters but I'm not sure how to do this in a way that won't eventually go out of bounds.
EDIT: Solved! After posting the question I was struck by insight and solved the problem myself. This code works but I would appreciate any insights into how to improve it!
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
int last = 0;
System.out.println("This program converts Roman Numerals to decimal form.");
System.out.println("Note: Roman Numerals are I, V, X, L, C, D and M.");
System.out.println("All letters entered will be treated as capitalized.");
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (int count = roman.length()-1; count >= 0; count--)
{
char numeral = roman.charAt(count);
switch (numeral){
case 'I':
decimal = 1;
break;
case 'V':
decimal = 5;
break;
case 'X':
decimal = 10;
break;
case 'L':
decimal = 50;
break;
case 'C':
decimal = 100;
break;
case 'D':
decimal = 500;
break;
case 'M':
decimal = 1000;
break;
default:
System.out.println("Error: Invalid character detected.");
System.exit(0);
break;
}
if (decimal >= last){
number = number + decimal;
}
else {
number = number - decimal;
}
last = decimal;
}
System.out.println("The decimal equivalent is: " + number);
System.out.println("Later!");
Well, a decimal is ##.##, and an integer is ##, so you should probably change demical to num.
Set the number as you already do, and add a check after it for the exception character. But first ensure that it exists:
if(this character is not the first && the previous character is an exception)
adjust the number as necessary
This will avoid an out-of-bounds exceptions.
My program works properly when I only enter 1 or 2 integers in a row such as: + 13 24 or * 4 - 165 235. But if I enter % * 5 12 8 it does not give me the right answer. How can I change my loops so that it works when there is a longer string of integers in a row. Given the order of operations and format of prefix notation? *My stack class and its methods do work properly.
import java.util.*;
public class part1Main {
public static void main(String[] args) {
// Reference variables
String temp2;
int num, num1, num2, ch;
char op;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
PrefixStack<Character> operands = new PrefixStack<Character>();
PrefixStack<Integer> S = new PrefixStack<Integer>();
System.out.print("Do you want to perform a prefix operation?");
System.out.print(" 1 for yes or 0 to quit: ");
ch = keyboard.nextInt();
temp2 = keyboard.nextLine();
while(ch != 0){
System.out.print('\n'+ "Enter the operation with a space between "
+ "each character. End your operation with a period: ");
while(keyboard.hasNext()){
if (keyboard.hasNextInt()){
num = keyboard.nextInt();
S.push(num);}
else{
temp2 = keyboard.next();
switch(temp2.charAt(0)){
case '+': operands.push('+');
break;
case '-': operands.push('-');
break;
case '/': operands.push('/');
break;
case '*': operands.push('*');
break;
case '%': operands.push('%');
break;
}
}
if(temp2.charAt(0) == '.')
break;
}
while(S.size > 1){
op = operands.pop();
num2 = S.pop();
num1 = S.pop();
switch(op){
case '+': S.push(num1 + num2);;
break;
case '-': S.push(num1 - num2);;
break;
case '/': S.push(num1 / num2);;
break;
case '*': S.push(num1 * num2);;
break;
case '%': S.push(num1 % num2);
break;
}
}
System.out.println("Your operation = " + S.pop());
System.out.print('\n'+"Do you want to perform another operation?");
System.out.print(" 1 for yes or 0 to quit: ");
ch = keyboard.nextInt();
}
}
}
The algorithm you are using is wrong!
For example, suppose you give:
% * 5 12 8
your program will output 5 as answer
It will push % and * on stack and 5 12 and 8 on stack
Then it will take out 8 and 12 and take out * and do 8 * 12 = 96 and push it on stack
Now in next round it will take out 96 and 5 and % as operator and do 5 % 96 = 5 which is given as output
Here you need to consider 2 very important thing:
% operator has same precedence as * and / (in Java). But the prefix expression is not evaluated in a way your program is doing it:
% * 5 12 8 should be evaluated as:
(5 * 12) % 8 which is 4.
So update your algorithm.
Your algorithm does not consider operator precedence. Add that feature in your program!
Try out some examples here
Hope this helps!
"Order of operations is defined within the structure of prefix notation and can be easily determined. One thing to keep in mind is that when executing an operation, the operation is applied to the first operand by the second operand. This is not an issue with operations that commute, but for non-commutative operations like division or subtraction, this fact is crucial to the analysis of a statement. For example, the following statement:
/ 10 5
is read as "divide 10 by 5". Thus the solution is 2, not 1/2 as would be the result of an incorrect analysis.
Since you didn't post what the wrong results are, I'm assuming this is your problem
I have a program where the user inputs 6 doubles, and the program outputs every combination of operators that can go in-between the doubles as 1024 separate strings. Here are the first two results if the user inputed 14,17,200,1,5, and 118:
"14.0+17.0+200.0+1.0+5.0+118.0"
"14.0+17.0+200.0+1.0+5.0-118.0"
What I want to do is perform the arithmetic according to the order of operations. Each double is stored as a variable a through f and each operator in-between these variables is stored as a char a_b through e_f. So:
double a, b, c, d, e, f;
char a_b, b_c, c_d, d_e, e_f;
My first thought was to write the code like this:
public double operateGroup() {
value = 0;
switch (a_b) {
case '+':
value += a + b;
break;
case '-':
value += a - b;
break;
case '*':
value += a * b;
break;
case '/':
value += a / b;
break;
default:
break;
}
switch (b_c) {
case '+':
value += c;
break;
case '-':
value += -c;
break;
case '*':
value *= c;
break;
case '/':
value /= c;
break;
default:
break;
}
switch (c_d) {
case '+':
value += d;
break;
case '-':
value += -d;
break;
case '*':
value *= d;
break;
case '/':
value /= d;
break;
default:
break;
}
switch (d_e) {
case '+':
value += e;
break;
case '-':
value += -e;
break;
case '*':
value *= e;
break;
case '/':
value /= e;
break;
default:
break;
}
switch (e_f) {
case '+':
value += f;
break;
case '-':
value += -f;
break;
case '*':
value *= f;
break;
case '/':
value /= f;
break;
default:
break;
}
return value;
}
But this doesn't work because it is the same as doing (a O b) O c) O d) O e) where O is any arbitrary operator. Any tips?
Since there are no parentheses, a trivial approach will work:
Go through the list once to process multiplications and divisions
When an operator between X and Y is * or /, replace X by X*Y or X/Y, and remove Y; also remove the operator
Now go through the list again, this time processing additions and subtractions in sequence.
To implement this approach, define two lists - the list of N Doubles, and N-1 operators, and implement the calculation as follows:
ArrayList<Double> vals = ...
ArrayList<Integer> ops = ... // 1=+, 2=-, 3=*, 4=/
for (int i = 0 ; i < ops.Count ; i++) {
int op = ops.get(i);
if (op == 3 || op == 4) {
if (op == 3) {
vals.set(i, vals.get(i) * vals.get(i+1));
} else {
vals.set(i, vals.get(i) / vals.get(i+1));
}
ops.remove(i);
vals.remove(i+1);
i--;
}
}
double res = vals.get(0);
for (int i = 0 ; i != ops.Count ; i++) {
if (op == 1) {
res += vals.get(i);
} else {
res -= vals.get(i);
}
}
If you need the operators' and operands' information, you should build a Parse Tree (this has been asked before).
If you are only interested in the result, you can evaluate the String directly:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Eval {
public static void main(String[] args) throws Exception {
ScriptEngineManager s = new ScriptEngineManager();
ScriptEngine engine = s.getEngineByName("JavaScript");
String exp = "14.0+17.0+200.0+1.0+5.0-118.0";
System.out.println(engine.eval(exp));
}
}
Output:
119.0
I would say you should parse it into a tree and then walk the tree to evaluate. Numbers are leaf nodes and operators are parents.