Local variable may have not been initialized in switch case - java

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");

Related

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

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.

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.

Calculating gpa is returning error

Hy guys i will need a quick help with my asigment. I tryed to debug this code and i dont know how do i got this error but when i try to calculate gpa it is sending me 0 instead of value from switch.
If user is pressing A and credits 4 it needs to return 4 * 4 but for letter A i am receiving 0
public class Gpa{
private int sumOfCredits;
private int sumOfPoints;
private int points = 0;
public Gpa(){
sumOfPoints=0;
sumOfCredits=0;
}
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
case "A":
points = 4;
break;
case "B":
points = 3;
break;
case "C":
points = 2;
break;
case "D":
points = 1;
break;
case "F":
points = 0;
break;
case "a":
points = 4;
break;
case "b":
points = 3;
break;
case "c":
points = 2;
break;
case "d":
points = 1;
break;
case "f":
points = 0;
break;
default:
points = -1;
}
return points;
}
public int getSumOfCredits(){
return sumOfCredits;
}
public int getSumOfPoints(){
return sumOfPoints;
}
public void addToTotals(String grade,int credits){
sumOfCredits =+ credits;
calcPoints(grade);
sumOfPoints =sumOfPoints + points * credits;
}
public double calcGPA(){
double gpa = sumOfPoints /sumOfCredits;
return gpa;
}
}
and this is my tester class:
import java.util.*;
public class ComputeGpa {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Gpa gpaC = new Gpa();
for (int i = 1; i <= 3; i++) {
System.out.printf("Enter grade (one character): ");
String grade = scan.next();
System.out.printf("Enter credits: ");
int credits = scan.nextInt();
gpaC.addToTotals(grade, credits);
System.out.printf("Sum Points: %d", gpaC.getSumOfPoints());
System.out.printf("\tSum Credits: %d\n", gpaC.getSumOfCredits());
}
System.out.printf("GPA: %.2f", gpaC.calcGPA());
}
}
in your calcGPA() method you are doing integer division when you want to do floating division. You either have to cast the sumOfPoints variable or the sumOfCredits to a double.
double gpa = sumOfPoints /sumOfCredits;
Is integer division in java and will return an integer value. Chances are it is always a value between 0 and 1, which will be equivalent to 0 after being casted to an integer. See if casting them to double fixes it.
double gpa = (double)sumOfPoints / (double)sumOfCredits;
You are also redefining points on each loop here:
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
Which means that instead of changing the global variable points you are changing the local variable points. So you need to remove that local variable points so it uses the global one, also you dont need to return anything so just use void:
public void calcPoints(String grade) {
switch (grade) {
//cont

How to use an object reference in a whole class

so for example in a switch statement "case 1" I declare an Object reference variable, its all good, but if I try to use in a "case 2" it says that reference variable cannot be resolved.
How can I use it in every case?
Edit:
switch(choice){
case 1: {
if(HotelObj.getClassicRoomsAvailable() == 0 && HotelObj.getExecutiveRoomsAvailable() == 0){
System.out.println("Sorry, there are no available rooms");
break;
}else {
Scanner scanInput = new Scanner(System.in);
System.out.print("\nEnter desired room type: ");
System.out.print ("\nEnter \"Classic\" for a classic type room, price: 90$ for a day");
System.out.println("\nEnter \"Executive\" for a executive type room, price: 150$ for a day");
String roomChoice = scanInput.nextLine();
System.out.print("Enter your name: ");
String clientName = scanInput.nextLine();
System.out.print("Enter for how many days you'll stay:");
int stayingDays = scanInput.nextInt();
Client ClientObj = new Client(clientName, roomChoice, stayingDays);
Client.clientCount++;
if(roomChoice.equals("Classic")){
ClientObj.clientRoom = new Room("Classic");
ClientObj.setMoney(ClientObj.getMoney()- stayingDays * ClientObj.clientRoom.getPrice());
HotelObj.decClassicRooms(1);
HotelObj.addIncome(stayingDays*ClientObj.clientRoom.getPrice());
} else {
ClientObj.clientRoom = new Room("Executive");
ClientObj.setMoney(ClientObj.getMoney()-stayingDays * ClientObj.clientRoom.getPrice());
HotelObj.decExecutiveRooms(1);
HotelObj.addIncome(stayingDays*ClientObj.clientRoom.getPrice());
}
}
break;
}
case 2: {
System.out.println("Name: "+ClientObj.getName());
//Error "ClientObj cannot be resolved"
}
}
Variables you declare inside your case statements are local to that statement, so, right-o, they won't be seen outside it. Just declare your variable before (above) the switch() and it'll be visible to them all.
Edit: this example is in response to Brian Roach below:
public void main(String[] args) {
int foo = 11;
switch (foo) {
case 1: {
int bar = 12;
System.out.println("1");
break;
}
case 2: {
System.out.println("2");
System.out.println("bar: " + bar);
break;
}
default: {
System.out.println("default");
break;
}
}
Compiler complains: "bar cannot be resolved to a variable"
To fix, move the declaration of bar to the same location as the declaration of foo.

Bracket expected.... not sure where [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm doing an assignment on modular programing and here Im getting a bracket expected error. Here is the code:
import java.util.*;
public class stlab09
{
public static void main (String args[])
{
System.out.println("\nLAB09 90 POINT VERSION\n\n");
enterData();
computeGPA();
displayData();
}
static String lGrade1;
static String lGrade2;
static String lGrade3;
static String lGrade4;
static int cHours1;
static int cHours2;
static int cHours3;
static int cHours4;
static String dummy;
public static double gpa;
public static void enterData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter course 1 Grade ===>> ");
lGrade1 = in.nextLine();
System.out.print("enter course 1 Hours ===>> ");
cHours1 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 2 Grade ===>> ");
lGrade2 = in.nextLine();
System.out.print("enter course 2 Hours ===>> ");
cHours2 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 3 Grade ===>> ");
lGrade3 = in.nextLine();
System.out.print("enter course 3 Hours ===>> ");
cHours3 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 4 Grade ===>> ");
lGrade4 = in.nextLine();
System.out.print("enter course 4 Hours ===>> ");
cHours4 = in.nextInt(); dummy = in.nextLine();
}
public static void computeGPA()
{
Grades.gradeValue();
Grades.courseValue();
Grades.getGPA();
}
public static void displayData()
{
System.out.println();
System.out.println("Course1 Grade: " + lGrade1 + " Course1 Credit Hours: " + cHours1);
System.out.println("Course2 Grade: " + lGrade2 + " Course2 Credit Hours: " + cHours2);
System.out.println("Course3 Grade: " + lGrade3 + " Course3 Credit Hours: " + cHours3);
System.out.println("Course4 Grade: " + lGrade4 + " Course4 Credit Hours: " + cHours4);
System.out.println();
System.out.println("Current GPA: " + gpa);
}
}
public class Grades() ***<<<<<<<<<<<<<<<<<< bracket expected here***
{
public static void gradeValue()
{
int value = 0;
char lg1 = lGrade1.charAt(0);
switch(lg1)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal1 = value;
char lg2 = lGrade2.charAt(0);
switch(lg2)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal2 = value;
char lg3 = lGrade3.charAt(0);
switch(lg3)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal3 = value;
char lg4 = lGrade4.charAt(0);
switch(lg4)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal4 = value;
}
public static void courseValue()
{
int cVal1 = gVal1 * cHours1;
int cVal2 = gVal2 * cHours2;
int cVal3 = gVal3 * cHours3;
int cVal4 = gVal4 * cHours4;
}
public static void getGPA()
{
double totalValue = cVal1 + cVal2 + cVal3 + cVal4;
double totalHours = cHours1 + cHours2 + cHours3 + cHours4;
double gpa = totalValue / totalHours;
}
}
So yeah I need some help figuring this out because I'm kinda going crazy about it. The expected program is supposed to use keyboard input of letter grades and course hours to compute GPA and grades. The assignment is to get that outcome but the main method must stay exactly as is, and almost every method was provided to me and i just had to organize them.
You have declared the inner class Grades as if it's a method (you added () onto the end of it), look at how the class stlab09 is declared, there aren't any ().

Categories

Resources