im doing an assignment which requires me to create 3 classes.
1 with getting 2 random integers,
1 with getting random operators such as + - * / which should be done so in char method
the last one to check if the simple mathematics answer is correct using booleans via user Scanner input.
i need a little help here as im not sure if i've done the random operators method correctly and am really lost at how i should tabulate both random int and operators together in one class.
here's the code i've done so far:
public static char getOperator (int x, int y)
{
char operator;
int answer;
switch (rand.nextInt(4))
{
case 0: operator = '+';
answer = x + y;
break;
case 1: operator = '-';
answer = x - y;;
break;
case 2: operator = '*';
answer = x * y;;
break;
case 3: operator = '/';
answer = x / y;;
break;
default: operator = '?';
}
return operator;
}
I believe you mean you need to create 3 methods (and not classes).
One that creates a random integer (it's a bad design to create a
method that returns two integers instead of just calling two times
one that returns one int).
One that returns a random operator
One that checks if an operation consisting of "random-number
random-operator random-number" is equal to user input
Anyways, there's a lot to unpack here, so:
Your first method getTwoIntegers is incorrect, you're asking for two integers in input but you never actually use them, then you return one random number.
The method getOperator needs to be redesigned to have no input and return one char (equal to + - x /).
Your final method will call the your first method twice, then the second method once, it will then print the operation for the user to see, and check if the response is correct.
Hopefully this can help you conceptualize better the way you should build your code.
I didn't post the source code since I believe it's much better for you if you try to do it by yourself (this being an assignment and all)
Good luck and have fun :)
Related
I am currently a early CS student and have begun to start projects outside of class just to gain more experience. I thought I would try and design a calculator.
However, instead of using prompts like "Input a number" etc. I wanted to design one that would take an input of for example "1+2+3" and then output the answer.
I have made some progress, but I am stuck on how to make the calculator more flexible.
Scanner userInput = new Scanner(System.in);
String tempString = userInput.nextLine();
String calcString[] = tempString.split("");
Here, I take the user's input, 1+2+3 as a String that is then stored in tempString. I then split it and put it into the calcString array.
This works out fine, I get "1+2+3" when printing out all elements of calcString[].
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
I then convert the integer parts of calcString[] to actual integers by putting them into a integer array.
This gives me "1 0 2 0 3", where the zeroes are where the operators should eventually be.
if (calcString[1].equals("+") && calcString[3].equals("+")) {
int retVal = calcIntegers[0] + calcIntegers[2] + calcIntegers[4];
System.out.print(retVal);
}
This is where I am kind of stuck. This works out fine, but obviously isn't very flexible, as it doesn't account for multiple operators at the same like 1 / 2 * 3 - 4.
Furthermore, I'm not sure how to expand the calculator to take in longer lines. I have noticed a pattern where the even elements will contain numbers, and then odd elements contain the operators. However, I'm not sure how to implement this so that it will convert all even elements to their integer counterparts, and all the odd elements to their actual operators, then combine the two.
Hopefully you guys can throw me some tips or hints to help me with this! Thanks for your time, sorry for the somewhat long question.
Create the string to hold the expression :
String expr = "1 + 2 / 3 * 4"; //or something else
Use the String method .split() :
String tokens = expr.split(" ");
for loop through the tokens array and if you encounter a number add it to a stack. If you encounter an operator AND there are two numbers on the stack, pop them off and operate on them and then push back to the stack. Keep looping until no more tokens are available. At the end, there will only be one number left on the stack and that is the answer.
The "stack" in java can be represented by an ArrayList and you can add() to push items onto the stack and then you can use list.get(list.size()-1); list.remove(list.size()-1) as the pop.
You are taking input from user and it can be 2 digit number too.
so
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
will not work for 2 digit number as your modification is i+=2.
Better way to check for range of number for each char present in string. You can use condition based ASCII values.
Since you have separated your entire input into strings, what you should do is check where the operations appear in your calcString array.
You can use this regex to check if any particular String is an operation:
Pattern.matches("[+-[*/]]",operation )
where operation is a String value in calcString
Use this check to seperate values and operations, by first checking if any elements qualify this check. Then club together the values that do not qualify.
For example,
If user inputs
4*51/6-3
You should find that calcString[1],calcString[4] and calcString[6] are operations.
Then you should find the values you need to perform operations on by consolidating neighboring digits that are not separated by operations. In the above example, you must consolidate calcString[2] and calcString[3]
To consolidate such digits you can use a function like the following:
public int consolidate(int startPosition, int endPosition, ArrayList list)
{
int number = list.get(endPosition);
int power = 10;
for(int i=endPosition-1; i>=startPosition; i--)
{
number = number + (power*(list.get(i)));
power*=10;
}
return number;
}
where startPosition is the position where you encounter the first digit in the list, or immediately following an operation,
and endPosition is the last position in the list till which you have not encountered another operation.
Your ArrayList containing user input must also be passed as an input here!
In the example above you can consolidate calcString[2] and calcString[3] by calling:
consolidate(2,3,calcString)
Remember to verify that only integers exist between the mentioned positions in calcString!
REMEMBER!
You should account for a situation where the user enters multiple operations consecutively.
You need a priority processing algorithm based on the BODMAS (Bracket of, Division, Multiplication, Addition and Subtraction) or other mathematical rule of your preference.
Remember to specify that your program handles only +, -, * and /. And not power, root, etc. functions.
Take care of the data structures you are using according to the range of inputs you are expecting. A Java int will handle values in the range of +/- 2,147,483,647!
This question already has answers here:
How to convert String object to Boolean Object?
(16 answers)
Closed 7 years ago.
I am very, very new at programming so sorry if this is a stupid question, but I can't find an answer anywhere.
In a program that I am working on the user can choose one of five options for problems to practice: addition, subtraction, multiplication, division, and remainders. There is a scanner that asks them to put in the fist letter of the name of the types of problems they want to practice (A or a, S or s, M or m, D or d, R or r). I want to make an if/else statement that will print out different problems depending on which one they choose.
The problem is, from what I can tell if/else statements will only work with boolean variables, but boolean variables don't like strings or string variables. I have seen ways to convert specific strings to variables, but since the user is deciding on the string, I have no way to know what they are going to choose every time. Is there anyway to convert a string variable to a boolean variable?? (i.e. the boolean variable is true when the string variable = "A")
if(s) can take boolean expressions (and use boolean operators, such as or). For example, String.equals(Object) (or String.equalsIgnoreCase(String)). Something like,
if (string.equals("A") || string.equals("a")) {
// ...
} else if (string.equalsIgnoreCase("B")) {// <-- or equalsIgnoreCase(String).
// ...
}
Personally, my favorite way is to use a switch statement when you're dealing with input, and while it doesn't use boolean values as you are use to in an if statement, for me it feels cleaner.
Your code would look like something such as:
switch(userInput.toLowerCase())
{
case "a":
// addition code
break;
case "s":
// subtraction code
break;
case "m":
// multiplication code
break;
case "d":
// division code
break;
case "r":
// remainder code
break;
default: // every other option besides (a, s, m, d, and r)
// print some error, user put wrong input
break;
}
Ypu can use
java.lang.Boolean(String s)
Allocates a Boolean object representing the value true if the string
argument is not null and is equal, ignoring case, to the string
"true".
Here's what you can do.You're dealing with a fairly simple problem.
Pseudo-Code
if(input=="A")
{
Do Addition
}
if(input=="M")
{
Do Multiplication
}
else
{
Give Error
}
Essentially, you want to check if the user input is equal to a particular string. You use the double equal to operator (==) here to perform the check.If the condition is TRUE and it will enter the block.
The Point is that the if block is evaluated on the basis of any expression that results into boolean values(i.e. true or false).
So there is no need to convert a String to Boolean.
All you have to do is just check if input string meets your criteria using a method provided by String Class in java called String.equals(String) or String.equalsIgnoreCase(String);
The return type of above methods is boolean (primitive) which will be evaluated by if statement as per your requirements.
To explore String Class in java
run "javap java.lang.String" on shell/bash/command prompt for programmer's guide to check out the contents of String Class
So your code will be something like
if(input.equalsIgnoreCase("a"))
{
// Calculations for addition
}
else if(input.equalsIgnoreCase("s"))
{
// Calculations for Substraction
}
Instead you can use switch-case as support for String in switch-case has been included from jdk7.
Also switch-case should be faster in this case as it will not check all cases as done by else if.
switch(input)
{
case "a":
case "A":
// Calculations for addition
break;
case "s":
case "S"
// Calculations for subtraction
break;
case "m":
case "M":
// Calculations for multiplication
break;
case "d":
case "D":
// Calculations for division
break;
case "r":
case "R":
// Calculations for remainder
break;
default: // for any other option besides above
// whatever handling you wanna do for wrong input
break;
}
I am using Stack class to calculate simple arithmetic expressions involving integers,
such as 1+2*3.your program would execute operations in the order given,without regarding to the precedence of operators.
*Thus, the expression 1+2*3 should be calculated (1+2)*3=9,not 1+(2*3)=7.
If i get the input as 1+2*3,i know how to convert the string 1,2,3 to Integer.but i don't know how to covert +,* from string type to operator.
My code logic is:
For eg: Given string 2 + (3 * 5), So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.
probably the best way to do it will be equals, but it's best to ignore whitespaces:
i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:
String str = op.replace(" ", "");
if(str.equals("*")){
retVal = a*b;
} else if(str.equals("+")){
retVal = a+b;
}//etc
Do what Ogen suggested and manually check the operator. A quick shortcut to doing the if, else if .... structure is switch, that is
switch(operand) {
case "*":
break;
case "+":
break;
.....
default:
}
You will have to manually check and assign the operator. E.g.
if (s.equals("+")) {
// addition
}
Quick solution: Use below code for executing correct javascript Arithmetic expression in java.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");
try {
Object result = se.eval(val);
System.out.println(result.toString());
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ok, assuming your assignment needs you to use the Stack class and you already have the logic to pick numbers ( including the negative numbers -- that would an operator followed by another operator in all but one cases) and operators and parens, what you could do is as follows.
If you encounter a number, pop the last two elements from your stack. The first item you pop will be an operator and the next will be a number. Evaluate the expression and push it into Stack and continue.
You can ignore the parenthesis. You will also have to handle the case of reading a number or parenthesis the first time.
What I'm trying to do is read a line (string) and use it as a mathematical function to get (double) values or answers to it at different points (like a calculator basically)
I included a very simplistic code of what I'm trying to do just for the sake of being direct and straight forward:
double x, y, z;
String function;
x = 5;
y = 4;
function = "(x*y)+y";
z = Double.parseDouble(function);
/*
I want z to equal this
z = (x*y)+y;
*/
System.out.print("z= " + z);
Again, this is only a sample code to be clearer about my question. My question again is: how can I set z = function when z is a double and function is a string?
NOTE: I tried parse as you can see, but it didn't work. I also tried to read the string character by character, but it didn't work either because it added the value of the characters together.
I guess you are looking for a lexer and a parser.
These are basical components of every compiler or interpreter as
the lexer is able to split input (your string) into tokens
the parser is able to build a tree which represent the syntatic shape of your tokens to be furtherly interpretated semantically
This discipline is quite wide and I suggest you to start with something like ANTLR for Java, it is a parser generator that will generate both lexer and parser according to rules you specify through a grammar. There are many, this is just the first that came into my mind.
If you want to forget about all this theory just embed something like JavaScript or Groovy in your Java program, they are able to interpret code that is given at runtime so that you can just go that way.
Java does not have something like eval builtin. But you can use an expression language like spEL, mvel or Jexl for this.
Maybe this SO question can help you.
I suggest you have a look at Parboiled. Unlike nearly all other parser solutions for Java, you write your grammars... In Java.
What is more, among the Java examples, there are working calculators.
float eval(String exp)
{
char[] a = exp.toCharArray();
float[] buffer = new int[exp.length];
int k = 0;
for(int i : a)
{
if(a[i] >= 48 && a[i] <= 57) //checking for numbers
{
int x = a[i] - '0';
buffer[k++] = x;
}
else if(a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/') //checking for operands
{
float result;
switch(a[i])
{
case '+': result = buffer[k] + buffer[k-1]; break;
case '-': result = buffer[k] - buffer[k-1]; break;
case '*': result = buffer[k] * buffer[k-1]; break;
case '/': result = buffer[k] / buffer[k-1]; break;
}
}
buffer[k++] = result;
}
return buffer[k]; //finally returning the recent value
}
Use a method like this. Will help a lot. Implemented using a stack data structure.
I have to write a program which reads in 3 numbers (using input boxes), and depending on their values it should write one of these messages:
All 3 numbers are odd
OR
All 3 numbers are even
OR
2 numbers are odd and 1 is even
OR
1 number is odd and 2 are even
This is what I have so far:
import javax.swing.JOptionPane;
class program3
{
public static void main(String[] args)
{
String num1 = JOptionPane.showInputDialog("Enter first number.");
String num2 = JOptionPane.showInputDialog("Enter second number.");
String num3 = JOptionPane.showInputDialog("Enter third number.");
boolean newnum1 = Integer.parseInt(num1);
boolean newnum2 = Integer.parseInt(num2);
boolean newnum3 = Integer.parseInt(num3);
}
}
This is where I am stuck. I am not sure how to use the MOD to display the messages. I think I have to also use an IF Statement too...But I'm not too sure.
Please help! :D
In Java, the modulus operator is %. You can use it like this:
if ( (a % 2) == 0) {
System.out.println("a is even");
}
else {
System.out.println("a is odd");
}
Combine it with some if statements or some counter to implement the final result.
PS: the type of newnumX looks odd :)
I would recommend you to
Start writing down in a piece of paper how would you do it manually.
( Write the algorithm )
Then identify which parts are "programmable" and which ones are not ( identify variables, statements, etc ) .
Try by hand different numbers and see if it is working.
From there we can help you to translate those thoughts into working code ( that's the easy part ).
These are basics programming skills that you have to master.
It is not worth we just answer:
boolean areAllEven = ( one % 2 == 0 ) && ( two % 2 == 0 ) && ( three % 2 == 0 ) ;
boolean areAllOdd = ( one % 2 != ..... etc etc
Because we would be diss-helping you.
Related entry: Process to pass from problem to code. How did you learn?
To avoid big ugly nested IFs, I would declare a small counter (in pseudocode):
if newnum1 mod 2 == 1 then oddcount += 1;
etc...
switch oddcount
case 0:
print "All three numbers are even"
etc...
Just a warning if you choose to use the % operator in Java: if its left-hand operand is negative, it will yield a negative number. (see the language specification) That is, (-5) % 2 produces the result -1.
You might want to consider bitwise operations e.g. "x & 1" to test for even/odd-ness.
Its even simpler than that, you have tree numbers a, b, c
n = a%2 + b%2 +c%2
switch (n):
case 0: 'three are even'
case 1: 'one is odd'
case 2: 'one is even'
case 3: 'three are odd'
And voila!
Write down the basic steps that you have to do to perform the task and then try to implement it in code.
Here is what you have to do:
1 - Get 3 numbers from the user.
2 - You need two variables: one to hold the number of odd inputs and the other to hold the number of the even ones. Lets call these evenCnt and oddCnt. (Hint: Since you know you only have 3 numbers, once you have determined one of these, the other one is just the difference from 3)
3 - Then you need a series of tests (If evenCnt is 3 then show "3 evens", else if ....)
(And Pascal and Kurosch have pretty much given you the fragments you need to fill in steps 2 and 3.)
[Edit: My #2 is wooly-headed. You only need one variable.]
Here you go. I just compiled and ran some test cases through this to confirm it works.
import javax.swing.JOptionPane;
class Program3 {
public static void main(String[] args) {
int evenCount = 0;
for (int i=0; i<3; i++) {
// get the input from the user as a String
String stringInput = JOptionPane.showInputDialog("Enter number " + (i+1) + ".");
// convert the string to an integer so we can check if it's even
int num = Integer.parseInt(stringInput);
// The number is considered even if after dividing by 2 the remainder is zero
if (num % 2 == 0) {
evenCount++;
}
}
switch (evenCount) {
case 3:
System.out.println("All are even");
break;
case 2:
System.out.println("Two are even, one is odd");
break;
case 1:
System.out.println("One is even, two are odd");
break;
case 0:
System.out.println("All are odd");
break;
}
}
}
BTW: I capitalized the class name because it's best practice to do so in Java.
I disagree with alphazero. I don't think two variables are REQUIRED. every number is either ever or odd. So keeping count of one is enough.
As for Asaph's code, I think it is well documented, but if you still want an explanation, here goes:
This is what the for loop does:
It reads (as Strings) user input for the 3 numbers
Integer.parseInt is a function that takes a String as a parameter (for example, '4') and returns an int (in this example, 4). He then checks if this integer is even by modding it by 2. The basic idea is: 4%2 = 0 and 9%2 = 1 (the mod operator when used as a%b gives the remainder after the operation a/b. Therefore if a%2 is 0, then a is even). There is a counter (called evenCount) that keeps track of how many integers are even (based on the %s test).
He then proceeds to do switch statement on the evenCount. A switch statement is sort of like an if-else statement. The way it works is by testing the switch parameter (in this case, evenCount) against the case values (in this case, 3, 2, 1, 0). If the test returns True, then the code in the case block is executed. If there is no break statement at the end of that case block, then, the code in the following case block is also executed.
Here, Asaph is checking to see how many numbers are even by comparing the evenCount to 0, 1, 2, and 3, and then usinga appropriate print statements to tell the user how many even numbers there are
Hope this helps