How i can use the string in switch case as an action? - java

I'm trying to code a Calculator on Java but in the switch statement, it takes the operation as a String, how can I transform it into an action?
switch(op) {
case 1: operation = "res= a + b";
break;
case 2: operation = "res = a - b";
break;
case 3: operation = "res = a * b";
break;
case 4: operation = "res = a / b";
break;
}
System.out.println(operation);
If I remove the quotes it says that I haven't initialized the variables. They are asked after choosing the operation.
EDIT:
I was applying the wrong logic to the program.

Don't perform the operation until you have the arguments:
import static java.lang.Integer.*;
import java.util.*;
class t1 {
static void calc(Scanner in) {
System.out.print("Operation: ");
int op = in.nextInt();
System.out.print("a: ");
int a = in.nextInt();
System.out.print("b: ");
int b = in.nextInt();
int res = 0;
switch(op) {
case 1:
res = a + b;
break;
case 2:
res = a - b;
break;
case 3:
res = a * b;
break;
case 4:
res = a / b;
break;
default:
System.out.println("Invalid operation");
System.exit(-1);
}
System.out.println(res);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
while (true) {
calc(in);
}
}
}
You could verify the operation before asking for the operands, with an additional switch statement.
There are ways to set the operation before obtaining the operands, but it's best to learn to walk before you run.

Related

Local variable may have not been initialized in switch case

I've initialized the variable I wanted, but after adding it's values through a switch case, I cannot return it. Is there any solutions?`
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Masukkan nilai a = ");
int a = input.nextInt();
System.out.print("Masukkan nilai b = ");
int b = input.nextInt();
System.out.print("Mau diapain bang angkanya? ");
String o = input.next();
int hasil;
switch (o) {
case "+":
hasil = a + b;
break;
case "-":
hasil = a - b;
break;
case "*":
hasil = a * b;
break;
case "/":
hasil = a / b;
break;
default:
System.out.println("Operator tidak valid");
}
// Error is here, stating that I haven't initialized the variable
System.out.println(hasil);
}
}
`
I've tried putting the console out in each of the case, and it did worked. So, is my first way of doing it is not working?
It shows that error because you declared them but didn't initialized them.
Your variable should be initialized as int hasil = 0;
Check this reference for a better idea. This user has explained it very smoothly.
init your int hasil = 0; or assign a value for it in the default case
default:
hasil = 0;
System.out.println("Operator tidak valid");

Ways to reverse print a string?

I'm trying to code a program that would convert an int to binaries. So far I have it print out the remainders, but it has to be printed in reverse for it to be a proper binary. I am not allowed to use any methods.
Here's my code.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Postive Number:");
int i = sc.nextInt();
int j = i; //backup
int k = 0; //remainder
while (j != 0) {
k = j % 2;
j /= 2;
String reversedStr = "";
switch (k) {
case 0:
reversedStr += "0";
break;
case 1:
reversedStr += "1";
break;
case 2:
reversedStr += "2";
break;
case 3:
reversedStr += "3";
break;
case 4:
reversedStr += "4";
break;
case 5:
reversedStr += "5";
break;
case 6:
reversedStr += "6";
break;
case 7:
reversedStr += "7";
break;
case 8:
reversedStr += "8";
break;
case 9:
reversedStr += "9";
break;
case 10:
reversedStr += "A";
break;
case 11:
reversedStr += "B";
break;
case 12:
reversedStr += "C";
break;
case 13:
reversedStr += "D";
break;
case 14:
reversedStr += "E";
break;
case 15:
reversedStr += "F";
break;
}
for (int l = reversedStr.length() - 1; l >= 0; l--) {
reversedStr.charAt(i);
System.out.print(reversedStr.charAt(l));
}
}
System.out.println("done");
}
}
this code gives me
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 178
at java.lang.String.charAt(String.java:658)
at radixHandmade.Handmade.main(Handmade.java:73)
The for loop at the bottom is the reversing part, but im not sure how to use charAt to complete the code. To be honest im very confused.
Any help would be greatly appreciated.
This statement causes the problem:
reversedStr.charAt(i);
Aside from causing an exception (because you're trying to get the (originally entered value)-th character in the string, which is by outside the bounds of the string, unless that value happens to be 0), it has no other side effect.
Just remove this line.
import java.util.Scanner;
public class Reverse {
public static void main(String[] args){
userInput();
}
public static void userInput(){
Scanner console = new Scanner(System.in);
String reverseString = console.nextLine(); //This is the word to be written backwards.
int s = reverseString.length()-1; //length of the word.
for (int i = s ; i>=0; i--){
System.out.print(reverseString.charAt(i));
}
}
}
Hope this helps.
Good luck.
removing the line reversedStr.charAt(i) will resolve the issue, but the program will still not convert to binary correctly. Your string still needs to be reversed. Might I suggest using the StringBuilder class:
import java.util.Scanner;
import java.lang.StringBuilder;
public class App {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder out = new StringBuilder();
System.out.println("Enter A Postive Number:");
int i = sc.nextInt();
int r = 0;
int b = 2; // now you can just change this for what base (binary, hex, ...)
while (i != 0) {
r = i % b;
i /= b;
switch (r) {
case 0:
out.append("0");
break;
case 1:
out.append("1");
break;
}
}
System.out.println(out.reverse());
}
}
Your code would work fine if you move the reversing for loop out of the while loop:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String revStr = "";
System.out.println("Enter A Postive Number:");
int i = sc.nextInt();
int r = 0;
int b = 2; // now you can just change this for what base (binary, hex, ...)
while (i != 0) {
r = i % b;
i /= b;
switch (r) {
case 0:
revStr += "0";
break;
case 1:
revStr += "1";
break;
// ... for hex
}
}
for (int j = revStr.length() - 1; j >= 0; j--) {
System.out.print(revStr.charAt(j));
}
System.out.print("\n");
}
But what I really don't understand is why you even have to reverse the string if you can just do:
reversedStr = "0" + reversedStr; // of course it will no longer be reversed
// ... for all the cases
Even better if you stick with just binary, you could skip the whole switch and do
public static void main(String[] args) {
String str = "";
System.out.println("Enter A Postive Number:");
for(int i = new Scanner(System.in).nextInt(); i != 0; i /= 2)
str = String.valueOf(i % 2) + str;
System.out.println(str);
}

Magic 8ball Using securerandom with switch statements and while loops

I have my following code working like this:
import java.util.Scanner;
import java.lang.Math;
public class Magiceightball {
private static void Number() {
int magic = (int) Math.ceil(Math.random() * 10);
String x;
switch (magic)
{
case 1: x = "Yes.";
break;
case 2: x = "No.";
break;
case 3: x = "The odds are in favor.";
break;
case 4: x = "The odds are against you.";
break;
case 5: x = "Never.";
break;
case 6: x = "Definitely!";
break;
case 7: x = "Maybe.";
break;
case 8: x = "I don't think so.";
break;
case 9: x = "I'd say no.";
break;
case 10: x = "Probably.";
break;
default: x = "Try Again.";
break;
}
System.out.println(x);
}
public static void main (String [ ] args)
{
Scanner scan = new Scanner(System.in);
boolean a = true;
while (a)
{
System.out.println();
System.out.println();
System.out.println("What would you like to ask the Magic Eight Ball? Make it a \"Yes\" or \"No\" question for it to work.");
System.out.print("\n\n--> ");
String what = scan.nextLine();
System.out.println();
Number();
System.out.println();
System.out.println();
System.out.println();
System.out.println("Would you like to go again? Enter \"Y\" for yes, and \"N\" for no.");
System.out.print("\n\n--> ");
String run = scan.nextLine();
run = run.toLowerCase();
if (run.equals("n"))
{
a = false;
}
}
}
} `
My dilemma is, I want all these methods being used the switch statement, the while loop but I want to replace the Math.random with the SecureRandom method how would I go about doing that?
I tried using the whole SecureRandom randomNumber = new SecureRandom(); to do it but it kept giving me errors that I could not convert secure random to "int".
You just need to instantiate a SecureRandom object and use its nextInt() method:
Random rand = new SecureRandom();
int magic = 1 + rand.nextInt(10);
You can use this function:
public static int generateRandomInteger(int min, int max) {
SecureRandom rand = new SecureRandom();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Call it with
int magic = generateRandomInteger(1,10); // to get a number between 1 and 10.

Why do I get this "unreachable statement" error?

I am converting a roman numeral input to it's integer value. In my convertChar method, I keep getting an error that it is an unreachable statement whenever I add a break statement in to the code. I don't know why this is. I'm a new student and I must have done something wrong and I was hoping maybe someone can show me what I did wrong and how to fix it. It must have something to do with the way I set the methods up right? I still get confused on what variables to input so maybe I messed up there but I'm not experienced enough to know exactly what I did wrong. Here is everything I have:
public class RomanNumeralConverter {
public int romanInput() {
return convert(getUserInput());
}
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
switch (value) {
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default:
System.out.println("Invalid character!");
return 0;
break;
}
return value;
}
public void printValue() {
System.out.println(romanInput());
}
public static void main(String[] args) {
new RomanNumeralConverter().printValue();
}
}
Your problem lies in your switch statement. You can minimize this occurring elsewhere by attempting to have methods return only once (which i think is best practice)
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result
}
In Java, it is a compile error to have statements that will never be reached while execution. In your case, the break statement will never be reached as there is a return statement above it. Also that last return statement will never be reached as you already would have returned in any case by the end of the switch block.
The problem is in your switch statement.
A default case can be thought of like the else in an if-else statement; it will always execute if no other condition in the switch is satisfied. If you are performing a return (or throw) inside of a default case, any code that follows after that will not be reachable.
You have two options:
Change the return statements to only assign a value to result instead, meaning that there's only one point of return from your code, or
Remove the return result from after your switch.

Switch statement + user input

Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}

Categories

Resources