Here is my code so far:
public class PostfixCalculator {
private Stack<Float> stack;
private float result;
private Boolean isOperator (char op){
boolean operator;
switch (op){
case '+':
case '-':
case '*':
case '/':
case '^':
operator = true;
break;
default:
operator = false;
break;}
return operator;
}
private Boolean isFunction (String func){
String[] functions = {"sin", "cos", "max"};
for (int i=0; i<functions.length; i++){
if (func.equals(functions[i]))
return true; }
return false;
}
private void computeOperator (float op1, float op2, char op){
switch (op){
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '/':
result = op1/op2;
break;
case '*':
result = op1 * op2;
break;
case '^':
result = (float) Math.pow(op1, op2);
break;
default:
break;
}
}
public float calculate(String expr) throws IllegalArgumentException {
result = 0;
String token;
Float makeit;
char operator;
float op1, op2, pushFloat;
StringTokenizer calc=new StringTokenizer(expr);
stack = new Stack<Float>();
while (calc.hasNextToken()){
token=calc.getNextToken();
operator=token.charAt(0);
if (!(this.isOperator(operator))){
if (this.isFunction(token)){
if (token.equals("sin")){
op1=stack.pop();
result = (float) Math.sin(op1);
stack.push(result);
}
else if (token.equals("cos")){
op1=stack.pop();
result = (float) Math.cos(op1);
stack.push(result);
}
else if (token.equals("max")){
op1=stack.pop();
op2=stack.pop();
result=Math.max(op1, op2);
stack.push(result);
}
}
else {
makeit = new Float(token);
pushFloat = makeit.floatValue();
stack.push(pushFloat);
}
}
else {
op1 = stack.pop();
op2 = stack.pop();
computeOperator (op1, op2, operator);
stack.push(result);
}
}
return stack.pop();
}
}
I think I have the basics of it down, but how do I deal with postfix calculations with three digits in a row or more, like for example '2 3 4 * -'? Any help would be appreciated. Thanks in advance!
Yep, a stack. And one can implement a simple stack easily with an array and a counter -- no real need to use a fancy class.
The array would be as large as the most deeply nested expression that you can handle (10 elements should be sufficient for virtually all "real" problems).
Push is update A[i] and increment i. Pop is decrement i and reference A[i]. "8 9 +" is push(8), push(9), pop the top two elements, add them, push the result. Note that operators are never pushed, only operands/results.
'2 3 4 * -' would be push(2), push(3), push(4), pop top two, multiply, push result, pop two, subtract, push result.
"7 6 + cos" would be push(7), push(6), pop two, add, push result, pop one, perform "cos", push result.
Error if you need to pop an element and the counter is zero (eg, "7 +" -- you'd want to pop twice but you can only pop once). Also an error if the user expresses "finished" and there is more than one element in the stack.
Always "display" your top element, as that's the last value pushed or the result.
For a calculator like this, you should use a stack. Every number is a push and every operation has a corresponding action.
st = []
while input:
if isanumber(input.next()): st.push(input.consume())
else: #its an operator
#note this may be wrong for operators that have a specific order
if(input.next() == "+"):
stack.push(stack.pop() + stack.pop())
# more operations
input.consume()
print(st)
And that would be the rough python to do it, in this instance I look ahead a single token before making a decision.
edit:
Probably should have read your code before posting, anyway you must always push back the computed number, also attempt to simplify your code into only "functions" and "numbers" making functions that perform both. Regex is also useful for this sort of thing, such as the http://www.cplusplus.com/reference/std/regex/.
Related
I want to make the code use the stack class (stack of integers), together with a driver program which can handle the operations: 'm' unary minus -- negate the top item, 'r' exchange the top two items, 'd' duplicate top item on the stack, 'p' print (to the screen) the top item, n print and remove the top item, f print all the contents of the stack (leaving it intact), c clear the stack, 'q' quit, 'h' (or ?) print a help message.
import java.util.Scanner;
public class CalculatorDemo {
public static void main(String[] args)
{
String expression;
int result;
Scanner in = new Scanner(System.in);
do
{
calculator evaluator = new calculator();
System.out.println("Enter a valid post-fix expression one token " +
"at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)");
System.out.println("Each token must be an integer or an operator (+,-,*,/,%)for help(h/?)");
expression = in.nextLine();
result = evaluator.evaluate(expression);
System.out.println();
System.out.println(result);
}
while (result = 'q');
System.exit(0);
}
}
import java.util.*;
public class calculator
{
private Stack<Integer> stack;
public calculator()
{
stack = new Stack<Integer>();
}
public int evaluate(String expr)
{
int op1, op2, result = 0, help;
String key;
Scanner parser = new Scanner(expr);
while (parser.hasNext())
{
key = parser.next();
if (isOperator(key))
{
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evaluateSingleOperator(key.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push(new Integer(Integer.parseInt(key)));
}
return result;
}
private boolean isOperator(String key)
{
return ( key.equals("+") || key.equals("-") ||
key.equals("*") || key.equals("/") ||
key.equals("h") || key.equals("?") ||
key.equals("p") || key.equals("n") ||
key.equals("d") || key.equals("r") ||
key.equals("c") || key.equals("f") ||
key.equals("%") || key.equals("m") ||
key.equals("q") );
}
private int evaluateSingleOperator(char operation, int op1, int op2)
{
int result = 0;
switch (operation)
{
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
case 'p':
result = op2;
break;
case '%':
result = op1 % op2;
break;
case 'm':
result = --op1;
break;
case'q':
result = (0);
break;
case'h'|'?':
int help = 0;
result = help;
break;
case 'r':
result = op1 ;//help
break;
case 'd':
result = op1;//help
break;
case 'n':
result = op1;//help
break;
case 'f':
result = op1;//help
break;
case 'c':
result = op1;//help
break;
}
return result;
}
private void help(String string) {
// TODO Auto-generated method stub
System.out.println("+ add the top two items" +
"* multiply the top two items" +
"- subtract the top item from the next item" +
"/ integer divide the second item by the top item" +
"% find the integer remainder when dividing the second item by the top item" +
"m unary minus -- negate the top item" +
"r exchange the top two items" +
"d duplicate top item on stack" +
"p print (to the screen) the top item" +
"n print and remove the top item" +
"f print all the contents of the stack (leaving it intact)" +
"c clear the stack" +
"q quit" +
"h (or ?) print a help message");
}
}
I got most of the code out of the text book and every thing seems to be working. For example if I have the postfix 5 2 + it would give me 7, which is correct but if I have 5 2 4 * / 7 - then it throws the illegal input exception. When I got rid of the illegal input exception, it works but doesn't give the right answer.
import java.util.*;
import java.util.regex.Pattern;
//Here is my class and main method
public class postFix {
public static final Pattern UNSIGNED_DOUBLE = Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?");
public static final Pattern CHARACTER = Pattern.compile("\\S.*?");
public static Double postfixEvaluate (String expression) {
Stack<Double> numbers = new Stack<Double>( ); //Stack for numbers
Stack<Character> operators = new Stack<Character>( ); //Stack for ops
Scanner input = new Scanner(expression);
String next;
while (input.hasNext()) //Iterator is used (hasNext)
{
if (input.hasNext(UNSIGNED_DOUBLE))
{ // if next input is a number
next = input.findInLine(UNSIGNED_DOUBLE);
numbers.push(new Double(next)); //adding nums to the number stack
}
else
{ //The next input is an operator
next = input.findInLine(CHARACTER);
switch (next.charAt(0))
{
case '+':
case '-':
case '*':
case '/':
operators.push(next.charAt(0)); //adding operators to operator stack
break;
case ')':
evaluateStackTops(numbers, operators);
break;
case '(':
break;
default: //Illegal Character
throw new IllegalArgumentException("Illegal Character");
}
}
}
//This what seems to be throwing the exception but I got this right out of the book
if (numbers.size() != 1)
throw new IllegalArgumentException("Illegal Input");
return numbers.pop( );
}
public static void evaluateStackTops (Stack<Double> numbers, Stack<Character> operators)
{
double operand1 , operand2;
//check that the stacks have enough items, and get the two operands
if ((numbers.size()<2)||(operators.isEmpty())) {
throw new IllegalArgumentException("Illegal Expression");}
operand2 = numbers.pop();
operand1 = numbers.pop();
//carry out an operation based on the operator on top of the stack
for (int i = 0; i < numbers.size(); i++) {
switch (operators.pop()) {
case '+':
numbers.push(operand1 + operand2);
break;
case '-':
numbers.push(operand1 - operand2);
break;
case '*':
numbers.push(operand1 * operand2);
break;
case '/':
numbers.push(operand1 / operand2);
break;
default:
throw new IllegalArgumentException("Illegal Operator");
}
}
public static void main(String[] args) {
//String expression;
//Scanner input = new Scanner(expression);
System.out.println(postFix.postfixEvaluate("(2 3 5 * / )" ));
}
}
Your algorithm is flawed. All it does is build stacks of operators and operands, and then evaluate the expression backwards. That's never going to work.
I don't understand why you're even checking for parentheses. There are no parentheses in postfix expressions, because the conversion from infix to postfix has already removed the parentheses.
Also, there is no need for a stack of operators. The whole idea of postfix is that you can evaluate each operator as you encounter it, and push the result back onto the stack.
The basic algorithm is:
while not end of input
read next token
if token is a number
push on numbers stack
else if token is operator
pop value2 and value1 from stack
result = evaluate value1 <operator> value2
push result to numbers stack
else
invalid input
end while
// at this point, there should be 1 value on numbers stack
So when evaluating 5 2 4 * / 7 -, the sequence is:
push 5
push 2
push 4
// operator * read here
pop 4
pop 2
evaluate 2 * 4
push 8
// operator / read here
pop 8
pop 5
evaluate 5/8
push 0.625
push 7
// operator - read here
pop 7
pop 0.625
evaluate 0.625 - 7
push -6.375
// end of input here
pop final result
I'm trying to make a recursive program that reads and evaluates fully parenthesized arithmetic expressions. The program was already made, my task is to make the method evaluates recursively. However, I'm having a bit of difficulty doing this. I have gotten much done, but I'm now getting an error - java.lang.NumberFormatException - and I can't seem to figure out why and where it's coming from. Could someone please help me as I have been at this for a week and need some help desperately.
Heres my code:
package q2;
// FILE: EvaluateDemonstration.java
// This program reads a reads and evaluates fully parenthesized arithmetic
// expressions. The purpose is to illustrate a fundamental use of stacks.
import java.util.Scanner;
import java.util.regex.Pattern;
public class RecursiveEvaluateDemonstration
{
public static void main(String[ ] args)
{
Scanner stdin = new Scanner(System.in);
String expression;
double answer;
System.out.println("Please type an arithmetic expression made from");
System.out.println("unsigned numbers and the operations + - * /.");
System.out.println("The expression must be fully parenthesized.");
do
{
System.out.print("Your expression: ");
expression = stdin.nextLine( );
try
{
answer = evaluate(expression,0,0,0);
System.out.println("The value is " + answer);
}
catch (Exception e)
{
System.out.println("Error." + e.toString( ) + " Help");
}
}
while (query(stdin, "Another string?"));
System.out.println("All numbers are interesting.");
}
public static boolean query(Scanner input, String prompt)
{
String answer;
System.out.print(prompt + " [Y or N]: ");
answer = input.nextLine( ).toUpperCase( );
while (!answer.startsWith("Y") && !answer.startsWith("N"))
{
System.out.print("Invalid response. Please type Y or N: ");
answer = input.nextLine( ).toUpperCase( );
}
return answer.startsWith("Y");
}
public static double evaluate(String s, int i,int j, int charIndex)
// Precondition: The string is a fully parenthesized arithmetic expression
// formed from non-negative numbers, parentheses, and the four operations
// +, -, *, and /.
// Postcondition: The string has been evaluated and the value returned.
// Exceptions: Can throw an NumberFormatException if the expression contains
// characters other than digits, operations, parentheses and whitespace.
// Can throw IllegalArgumentException if the input line is an
// illegal expression, such as unbalanced parentheses or a division by zero.
{
double[] numbers = new double[3] ;
Character[] operations = new Character[1];
String next = "";
int length = s.length();
char first;
int numIndex = i;
int operatIndex = j;
if (charIndex < length)
{
if (Character.isDigit(s.charAt(charIndex))) //|| s.charAt(charIndex) == '.' )
{
next += s.charAt(charIndex);
}
else
{
first = s.charAt(charIndex);
switch (first)
{
case '+': // Addition
case '-': // Subtraction
case '*': // Multiplication
case '/': // Division
numbers[numIndex]=(new Double(next));
System.out.println(numbers[numIndex]);
operations[operatIndex] = first;
break;
case ')': // Right parenthesis
evaluateStackTops(numbers, operations);
break;
case '(': // Left parenthesis
break;
default : // Illegal character
throw new IllegalArgumentException("Illegal character");
}
}
evaluate(s, ++numIndex, operatIndex+1, charIndex+1);
}
if (numbers.length != 3)
throw new IllegalArgumentException("Illegal input expression");
return numbers[2];
}
public static void evaluateStackTops(double[] numbers, Character[] operations)
// Precondition: The top of the operations stack contains +, -, *, or /, and
// the numbers stack contains at least two numbers.
// Postcondition: The top two numbers have been popped from the numbers stack, and the
// top operation has been popped from the operations stack. The two numbers have been
// combined using the operation (with the second number popped as the left operand).
// The result of the operation has then been pushed back onto the numbers stack.
// Exceptions: Throws an IllegalArgumentException if the stacks are illegal or if the
// operation results in a division by zero.
{
double operand1, operand2;
// Check that the stacks have enough items, and get the two operands.
if ((numbers.length < 2))
throw new IllegalArgumentException("Illegal expression");
operand2 = numbers[1];
operand1 = numbers[0];
// Carry out an action based on the operation on the top of the stack.
switch (operations[0])
{
case '+': numbers[2] = (operand1 + operand2);
break;
case '-': numbers[2] = (operand1 - operand2);
break;
case '*': numbers[2]= (operand1 * operand2);
break;
case '/': // Note: A division by zero results in POSTIVE_INFINITY or
// NEGATIVE_INFINITY.
numbers[2] = (operand1 / operand2);
break;
default : throw new IllegalArgumentException("Illegal operation");
}
}
// These patterns are from Appendix B of Data Structures and Other Objects.
// They may be used in hasNext and findInLine to read certain patterns
// from a Scanner.
public static final Pattern CHARACTER =
Pattern.compile("\\S.*?");
public static final Pattern UNSIGNED_DOUBLE =
Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?");
}
Here's the trace:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.valueOf(Unknown Source)
at java.lang.Double.<init>(Unknown Source)
at q2.RecursiveEvaluateDemonstration.evaluate(RecursiveEvaluateDemonstration.java:94)
at q2.RecursiveEvaluateDemonstration.evaluate(RecursiveEvaluateDemonstration.java:107)
at q2.RecursiveEvaluateDemonstration.evaluate(RecursiveEvaluateDemonstration.java:107)
at q2.RecursiveEvaluateDemonstration.main(RecursiveEvaluateDemonstration.java:29)
You're probably getting the number format exception because you're doing
case '+': // Addition
case '-': // Subtraction
case '*': // Multiplication
case '/': // Division
numbers[numIndex]=(new Double(next));
But at this point, the next could be the empty string "", so it will fail with that.
Add
e.printStackTrace();
to the catch block in the main method and run the program again with same input to receive the stacktrace, then share the stacktrace here.
this code is supposed to recieve two integers and an operation and then calculate the numbers. this is only part of the entire program everything else works but the calculations are wrong. The only correct output that i get when i run the whole thing is the subtraction. Whats wrong with it?
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
Here is the entire code for the program
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
printIntro();
Scanner kb = new Scanner(System.in);
String answer = "yes";
while (answer.equals("yes"))
{
System.out.println("Enter your problem");
String fullExpression=kb.nextLine();
fullExpression=fullExpression.replaceAll("\\s","");
int length=fullExpression.length();
char op1=fullExpression.charAt(0);
char op2=fullExpression.charAt(1);
String operation=fullExpression.substring(2,length);
printEnglish(op1,op2,operation);
System.out.println("Type yes to continue");
Scanner kb1 = new Scanner(System.in);
answer=kb1.nextLine();
};
}
/*this methods gets the operands and the operation and
prints the English version: if we call this method
printEnglish(2,3, plus), then this method will output:
Two plus three = 5 */
public static void printEnglish(char op1, char op2, String operation)
{
String resultOp1CharToString=charToString(op1);
String resultOp2CharToString=charToString(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, resultOperationConversion);
System.out.print(resultOp1CharToString+ operationConversion(operation) + resultOp2CharToString+ "=" + resultCalculate);
/*1. call the method charToString(op1) to convertlish
word for example ‘1’ to one or ‘2’ to two,….
2. call the method operandConversionToNumber(op1) to
get its numeric value. For example if op1 is ‘1’ then
this method call should return the integer value 1
3. call the method operationConversion(operation) to
convert the operation to a mathematical operation. For
example if you call this method with the string plus
then it will return ‘+’
4. finally call the method calculate to get the result
of the operation.*/
}
/*this method prints the numeric version which is 2 *3
=6*/
//public static boolean printNumeric(char op1, char op2, String operation)
//{
/*String resultCharToString=charToString(op1);
String resultCharToString2=charToString(op2);
int resultOperandToNumber=operandConversionToNumber(op1);
int resultOperandToNumber2=operandConversionToNumber(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, operation); */
//}
/*this method gets a number as a character and returns
its numeric value as an integer. You must use case
statement for this method*/
public static int operandConversiontoNumber(char operand)
{
int numberOperand=0;
switch(operand)
{
case '0':
numberOperand=0;
break;
case '1':
numberOperand=1;
break;
case '2':
numberOperand=2;
break;
case '3':
numberOperand=3;
break;
case '4':
numberOperand=4;
break;
case '5':
numberOperand=5;
break;
case '6':
numberOperand=6;
break;
case '7':
numberOperand=7;
break;
case '8':
numberOperand=8;
break;
case '9':
numberOperand=9;
break;
}
return numberOperand;
}
/*this method gets the operation as a string and
return the equivalent operation in math. For example
if it receives “plus” the it will return ‘+’ */
public static char operationConversion(String s)
{
char operation=0;
if(s.equals("plus"))
{
operation= '+';
}
else if(s.equals("minus"))
{
operation= '-';
}
else if(s.equals("multiply"))
{
operation= '*';
}
else if(s.equals("divide"))
{
operation= '/';
}
else
{
operation= '^';
}
return operation;
}
/*this method recives two numbers and the operation
and returns the result*/
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
/*this method converst a number character to its
English word for example if this method receives ‘1’
it will return “one” */
public static String charToString(char num)
{
String englishOperand="one";
switch(num)
{
case '0':
englishOperand= "zero";
break;
case '1':
englishOperand="one";
break;
case '2':
englishOperand="two";
break;
case '3':
englishOperand="three";
break;
case '4':
englishOperand= "four";
break;
case '5':
englishOperand= "five";
break;
case '6':
englishOperand= "six";
break;
case '7':
englishOperand= "seven";
break;
case '8':
englishOperand= "eight";
break;
case '9':
englishOperand= "nine";
break;
}
return englishOperand;
}
//this method prints the decription of this program.
public static void printIntro()
{
System.out.println("This program is a calculator, you need to enter two");
System.out.println("single digit numbers and an operation(plus, minus,");
System.out.println("divide, multiply, power) and it outputs its numeric");
System.out.println("and English version. Your operand and operation can be");
System.out.println("separated by space(s) or there could be no spaces");
System.out.println("between them. For example you can enter “23plus” or “2 3 plus”");
}
}
I entered 2 3 plus and i expect 5 but i dont recieve that, but when i enter 2 3 minus i recieve -1
if (operand2==0)
{
System.out.println("Cant divide by zero");
return -1; // some dummy value
}
else
{
return(operand1/operand2);
}
Division will be incorrect as it's doing integer division and you want a double result. It will also throw a divide by zero error because you don't return.
if (operand2 == 0)
{
System.out.println("Cant divide by zero");
return 0; // I guess
}
return (double)operand1 / (double)operand2;
All the rest look like they should work fine.
How can I add conditions into a switch statement?(ex:-Displaying the grade for the average marks)
I recommend using if-else... switch statements can only compare on equality.
With an integer score, you COULD do something like...
switch (score)
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:
grade = 'A';
break;
case 89:
/* ... */
}
See the problem? :-)
You can't. Use an if-else-if-else.
Here is how I use less than greater than in a switch statement. The following is in actionscript 3...
var unknown1:Number = 8;
var unknown2:Number = 2;
var lowerBoundary = 1;
var upperBoundary = 5
switch(true){
case (unknown2 < lowerBoundary || unknown2 > upperBoundary):
trace("value is out of bounds");
break;
case (unknown2 > lowerBoundary && unknown2 < upperBoundary):
trace("value is between bounds");
break;
default:
trace("Out of Luck");
break;
}
Output...
value is between bounds
This question is listed with a Java tag so...
Generic switch statement:
// ... within class scope
private final int CONSTANT_1 = 1;
private final int CONSTANT_2 = 2;
private final int CONSTANT_3 = 3;
// ...
public void doStuff(MyObject myObject){
int variable = myObject.getIntValue();
switch(variable){
case CONSTANT_1:
System.out.println(variable + " is equal to " + CONSTANT_1);
// use a break statement to tell the switch to stop here
// or else it will execute all subsequent cases:
break;
case CONSTANT_2:
System.out.println(variable + " is equal to " + CONSTANT_2);
// what happens if I leave out the break?
case CONSTANT_3:
System.out.println(variable + " is equal to " + CONSTANT_2);
break;
default:
System.out.println(variable + " wasn't equal to anything!");
}
Let's say I run through this 3 times and "myObject.getIntValue()" returns these values in this order; 3, 1, 2, and finally 42. Then the following output would be generated:
First time through using the value '3'...
3 is equal to 3
Second time through using the value '1'...
1 is equal to 1
Third time through using the value '2'...
2 is equal to 2
2 is equal to 3
Fourth time through using the value '42' ...
42 wasn't equal to anything!
Notice the third run has two lines (and one incorrect one) because I left out the break keyword for the second case.
Now in Java 1.5 and up, you can also switch on the Enum type:
public void doStuff(MyObject myObject){
MyEnumType varType = myObject.getEnum();
switch(varType){
case MyTypeOne:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
case MyTypeTwo:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
case MyTypeThree:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
default:
// code for unknown case goes here
}
}
Depending on what your ranges are you can use a formula.
e.g.
switch(score/10) {
case 10: case 9: case 8: return 'A';
case 7: return 'B';
case 6: return 'C';
case 5: return 'D';
default: return 'U';
}
In this example, does the code generate a random number and do something if it's that number or that number.
int num; //Just declares a variable
Random r = new Random(); //This makes an object that generates random numbers.
num = r.nextInt(2); //This "Choose" the random number. The possible numbers are 0 and 1. and the sets the the num variable to the number.
switch(num){
case 0: //This says if the number is 0 then do this.
//put code here.
break;
case 1: //This says if the number is 1 then do this.
//put code here
break;
}
And this is a switch statement that do different things based on the number that randomly gets chosen.