Java – how to select a value from an array?
•
Java
How do I select a value from an array? For example, string [] ans = {'', "– ''," / "," * "}; Then I want to choose ""
public static void main(String[] args) { String[] ans = {"+","-","/","*"}; Random random = new Random(); Scanner calcu = new Scanner(system.in); System.out.print("Enter First number: "); numOne = calcu.nextInt(); System.out.print("Enter Second number: "); numTwo = calcu.nextInt(); System.out.print("Choose an Operator to use"); }
Solution
You can use ans [0] for "" and so on
ans[0] = "+"; ans[1] = "-"; ans[2] = "/"; ans[3] ="*";
In your case, this code will help you:
public static void main(String[] a) { String[] ans = {"+","*"}; double result = 0; Scanner calcu = new Scanner(system.in); System.out.print("Enter First number: "); int numOne = calcu.nextInt(); System.out.print("Enter Second number: "); int numTwo = calcu.nextInt(); System.out.print("Choose an Operator to use"); String oparation= calcu.next(); if(oparation.equals(ans[0])){ result = numOne + numTwo; } else if(oparation.equals(ans[1])){ result = numOne - numTwo; } else if(oparation.equals(ans[2])){ result = numOne / numTwo; } else if(oparation.equals(ans[3])){ result = numOne * numTwo; } System.out.println("result is " + result); }
If you want to use the switch statement to get the same result:
public static void main(String[] a) { double result = 0; Scanner calcu = new Scanner(system.in); System.out.print("Enter First number: "); int numOne = calcu.nextInt(); System.out.print("Enter Second number: "); int numTwo = calcu.nextInt(); System.out.print("Choose an Operator to use"); String oparation= calcu.next(); switch(oparation){ case "+" : result = numOne + numTwo; break; case "-" : result = numOne - numTwo; break; case "/" : result = numOne / numTwo; break; case "*" : result = numOne * numTwo; break; } System.out.println("result is " + result); }
However, using the switch statement, if you want to compare variables such as case ans [0]: instead of case "*", you can use enum
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码