Cannot find symbol when already declared - java

Please someone help me on this error :
import java.util.*;
class Cinema
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
int t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
int t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
int t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}
I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

You need to declare your variable before switch block for it to be accessible outside of the switch block ... please see the below
import java.util.*;
public class Cinema {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
int t = 0;
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}

Your 't' variable is declared within the case blocks repeatedly, which creates different variables. In this case, it can be seen only inside those blocks. You might consider putting the variable declaration before your switch block.

The variable t is being declared inside the switch statement in the code above which is resulting in the error.You need to initialize it outside and change the value inside the switch statement accordingly.
import java.util.*;
public class Main {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
int t=0;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}

Ok i figured it out, i had to put int t = 0; after the switch block not before.
When i put it before the switch block, it said variable t is already defined in main(Java.lang.String[]). The correct code is as following :
import java.util.*;
class Cinema
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
int t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
int t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
int t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
int t = 0;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}

Related

My array is only remembering last last element entered and histogram is not printing right

import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
for (int j = 0; j < this.rainRecorded[i] - 1; j++) {
System.out.print("*");
}
System.out.println(i);
}
System.out.print("");
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
I guys i being struck on this for a couple of days in my switch statement in case 3 is where i create my elements to enter into my array , but in seems to only remember the last array entered when i print my histogram out in case 4 displayHistogram(); and this is where my histogram is printing wrong as well.
So to issues my array isn't recording property and histogram is printing wrong.
For example users chooses 3 days to enter and values are 10,20,30, and when i print histogram its prints this.
0
1
*****************************2
What i want this below , one * for ever ten mills of rain with index printed first.
0 *
1 **
2 **
You need to move the initialisation of this.rainRecorded to createGauge method and update the displayHistogram to print as required. You can try the following:
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
this.rainRecorded = new int[this.days]; // move the array initialization here
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
System.out.print(i + " ");
for (int j = 0; j < this.rainRecorded[i] - 1; j += 10 ) {
System.out.print("*");
}
System.out.println();
}
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
So, your codes a little bit over the place and I've had some issues trying to understand the basic intent, for example
private int[] rainRecorded;
private int[] rainEntered;
I'm not sure what the intention is for these two variables. So in my example, I've discarded rainEntered for the time been.
So, your first problem starts here...
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
First, I'd remove the need to for the two exit conditions, as it is going to make it more difficult to reasons about
Next, the checks for the validity of the data should be done outside of the loop and I'd also avoid calling mainMenu from within it, this is going to quickly put you in a strange place.
But, my main problem is with
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
You keep creating new instances of both this.rainRecorded and this.rainEntered, meaning that each time the loop runs, you've lost anything that was previous entered.
So, in my "simplified" version, I modified it down to something like...
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
I then simplified the histogram workflow as well, but I'm still trying to get my head around what rainEntered is suppose to do...
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
One last thing I also did, was to remove all the calls to mainMenu and instead relied on a simple do-while loop to reprint the menu each time it returned from Chosen method
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
This simplifies the workflow, as it's easier to reason about where you are at any point in the execution of the program, instead of wondering why when, under some condition, when you chose something from the menu, you end up in some other part of the program instead.
Example
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
//private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
private boolean shouldContinue = true;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8: shouldContinue = false;
break;
default:
System.out.println("Invalid input, try again");
}
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
if (days > 0) {
this.rainRecorded = new int[this.days];
}
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
}
}
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
Now, if rainEntered is suppose to be some kind of compounding array, where it allows you to record multiple days of rain over different periods, you might consider using a multi-dimensional array instead, so you could n periods and each period could have n days of rain...

How to pass user input variables in my Java code?

//Inventory Items classs
import java.util.Scanner;
public class InventoryItems {
public int sackrice = 4;
public int animalfeed = 12;
public int trayeggs = 15;
public int bottlemilk = 9;
ItemSupplier supple = new ItemSupplier();
public void inventoryItem() {
System.out.println("\nAvailable items:\n");
sackrice = sackrice + supple.getRice();
System.out.println("Sack of rice: " + sackrice);
if(sackrice < 10)
System.out.println("Sack of rice low, please restock");
System.out.println();
System.out.println("Animal feed: " + animalfeed);
if(animalfeed < 10)
System.out.println("Animal feed low, please restock");
System.out.println();
System.out.println("Tray of eggs: " + trayeggs);
if(trayeggs < 15)
System.out.println("Tray of eggs low, please restock");
System.out.println();
System.out.println("Bottle of milk: " + bottlemilk);
if(bottlemilk < 15)
System.out.println("Bottle of milk low, please restock");
System.out.println();
press();
}
public static void press(){
Scanner input = new Scanner(System.in);
System.out.println("Press Enter to continue...");
String enter = input.nextLine();
}
}
//Item Supplier class
import java.util.Scanner;
public class ItemSupplier {
public int z;
Scanner scan = new Scanner(System.in);
public void ricesupplier() {
System.out.println("How many sacks of rice would you like to
order?");
z = scan.nextInt();
}
public int getRice() {
return z;
}
public void feedsupplier() {
}
public void eggsupplier() {
}
public void milksupplier() {
}
}
import java.util.Scanner;
public class InventoryManager{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int x;
int y;
do {
System.out.println("Input option:\n" + "\n1. Check inventory" + "\n2. Search item supplier" + "\n3. Exit\n");
x = scan.nextInt();
switch(x) {
case 1:
InventoryItems items = new InventoryItems();
items.inventoryItem();
break;
case 2:
ItemSupplier supply = new ItemSupplier();
do {
System.out.println("\nChoose supplier:\n" + "\n1. Rice supplier\n" + "2. Animal feed supplier\n" + "3. Egg supplier\n" + "4. Milk supplier\n" + "5. Back\n");
y = scan.nextInt();
switch(y) {
case 1:
supply.ricesupplier();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Invalid option");
break;
}
break;
} while (y != 5);
break;
case 3:
System.out.println("Program closed");
System.exit(0);
default:
System.out.println("Invalid option");
break;
}
} while(x != 3);
}
}
The "z" I get from getRice() is 0. It only takes the declared but initialized z. How do I get the "z" that was inputed in ricesupplier() method? Specifically, here: System.out.println("How many sacks of rice would you like to order?") and here z = scan.nextInt().
I'm really just a beginner. A lot of parts are still incomplete. I need to finish this problem first before I can proceed.
This won't be a direct answer to your question but here's some hints in order to improve your code and eventually solve your problem.
You should not make a new InventoryItems every time the user's input is 1. This will result into printing the initial inventory items, thus making your user order an item is useless
You should not make a new ItemSupplier every time the user's input is 2.
You don't need ItemSupplier in your InventoryItems
You don't need the variable z in ItemSupplier, you can directly return the input of the user in ricesupplier() method
thus if the user's input is 2 then you can just call ricesupplier() method and add it's return to the current items.sackrice

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 ().

Exiting switch back to main method

I have a method which uses a switch statement to give the user options to select, once they have selected an option and the code in the case has been executed how do I get back into the main method which offers another menu?
Part of my code:
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
....
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
break;
....
}
public static void main(String[] args) {
while (1 == 1) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
....
}
EDIT (full code requested):
/**
* User: Colin Shewell
* Date: 26/11/13
* Time: 10:32
*/
import java.util.Scanner;
import java.util.Arrays; //REMOVE THIS!!!
public class StudentMarks {
static Scanner input = new Scanner(System.in);
static String[] studentNamesArray = new String[10];
static int[][] studentMarksArray = new int[10][3];
static int nameArrayCount, markArrayCount = 0;
static int markOne, markTwo, markThree;
static String studentName;
static void printArrays(){
System.out.println(Arrays.toString(studentNamesArray));
for (int index=0;index<10;index++)
{
System.out.println(studentMarksArray[index][0]);
System.out.println(studentMarksArray[index][1]);
System.out.println(studentMarksArray[index][2]);
}
}
static void addStudent() {
if (nameArrayCount < 10) {
System.out.println("Enter the student's name in the following format - surname, forename: ");
studentName = input.next();
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
if (markArrayCount < 10){
System.out.println("Enter the first mark: ");
markOne = input.nextInt();
System.out.println("Enter the second mark: ");
markTwo = input.nextInt();
System.out.println("Enter the third mark: ");
markThree = input.nextInt();
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
}
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
System.out.println("2: Change first mark.");
System.out.println("3: Change second mark.");
System.out.println("4: Change third mark.");
System.out.println("5: Change all marks.");
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
System.out.println("Enter the new student name.");
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return;
case 2:
System.out.println("Enter the new mark for mark one.");
int newMarkOne = input.nextInt();
studentMarksArray[studentChoice][0] = newMarkOne;
return;
case 3:
//two
break;
case 4:
//three
break;
case 5:
//all
break;
default:
System.exit(0);
break;
}
}
public static void main(String[] args) {
while (true) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
System.out.println("2: Modify the details of an existing student.");
System.out.println("3: Delete an existing student.");
System.out.println("4: Sort in alphabetical order by name.");
System.out.println("5: Output the student name and corresponding marks in ascending name order.");
System.out.println("6: Output the student name and corresponding marks in descending name order.");
System.out.println("7: Display the student with the highest average mark.");
System.out.println("8: Display the student with the lowest average mark.");
System.out.println("9: Display the average score of all students recorded.");
System.out.println("10: Exit.");
int choice = input.nextInt();
switch (choice) {
case 1:
addStudent();
System.out.println(Arrays.toString(studentNamesArray));
break;
case 2:
modifyStudent();
break;
case 3:
printArrays();
break;
/* case 4:
sortAlphabetical();
break;
case 5:
outputNameMarksAsc();
break;
case 6:
outputNameMarksDsc();
break;
case 7:
highestStudentAvgMark();
break;
case 8:
lowestStudentAvgMark();
break;
case 9:
displayAvgScore();
break; */
case 10:
System.exit(0);
break;
default:
System.exit(0);
break;
}
}
}
}
Just return to the main method. return just exits the method and continues executing code from the line it was called.
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return; //exits this method
//break; <-- not needed after a return!
Your code will run in an infinite loop, you can make it run with a conditional flag like this
boolean isRunning = true;
while (isRunning) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
isRunning = false;
//your code for case 1
....
}
//rest of the code in main executes now
This will exit the while loop back to the main method

Need assistence displaying value from a different private class

Okay, first off I am very, very new to java. For this project I need to design a program that takes a product number, an amoutn sold, calculates the total, and then displays it. However, I need to to display when I select option 2, which is a seperate private class, to be honest I don't even know where to begin. Any help would be appreciated.
import java.util.Scanner;
public class Attempt1
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main(String[] args)
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println("\n--------------");
System.out.println("Retail Sales\n");
System.out.println("1. Enter Products Sold");
System.out.println("2. Display Total Retail Sales");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
enterProducts();
break;
case '2':
displaySales();
break;
case '3':
//recognize as valid selection but do nothing
break;
default :
//System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '3');
}//end main()
private static void enterProducts()
{
Scanner inp = new Scanner(System.in);
int product,quantity;
double total = 0.00;
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
while(product !=0)
{
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
switch( product ){
case 1:total+=quantity*2.98;
break;
case 2:total+=quantity*4.50;
break;
case 3:total+=quantity*3.98;
break;
case 4:total+=quantity*4.49;
break;
case 5:total+=quantity*6.87;
break;
default:System.out.println("Invalid Product Number");
System.out.println("Product Number Does not Exist");
if(product<0 && product>=6)
{
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
}
break;
}
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
}
pause();
}
private static void displaySales()
{
System.out.println( "The total retail value was: " + total );
pause();
}
}//end MenuDemo
Here is an algorithm for improving your code:
At the beginning of your your main add a variable total and initialize it with 0: double total=0;
Change the enterProducts method's return type to double: private static double enterProducts() and return the local variable total at the end from this method after the call to pause: return total;
In the case for the input of 1 add the returned value from enterProducts to the current value of total (it's the total inside your main): total += enterProducts();
Add to the method displaySales an double argument: private static void displaySales(double total) and change the call to it in the main's case for 2 to displaySales(total);
I think you mean private method. You could pass the total like so:
private static void displaySales(double total) {
...
total is defined in enterProducts but not in the main method where the loop is displayed, so you could return this:
double enterProducts() {
...
return total;
}
so that you can pass it to displaySales.
The problem with the code is that you're trying to access a local variable, declared in the static enterProducts() method, inside of the static displaySales() method.
The code below solves that "problem".
With that being said, I recommend that you work through some Java tutorials to understand why the code now works... Have a look at Variable Scope.
public class Attempt1
{
//use a static variable to store the total
static double total = 0.00;
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main(String[] args)
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println("\n--------------");
System.out.println("Retail Sales\n");
System.out.println("1. Enter Products Sold");
System.out.println("2. Display Total Retail Sales");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
enterProducts();
break;
case '2':
displaySales();
break;
case '3':
//recognize as valid selection but do nothing
break;
default :
//System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '3');
}//end main()
private static void enterProducts()
{
Scanner inp = new Scanner(System.in);
int product,quantity;
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
while(product !=0)
{
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
switch( product ){
case 1:total+=quantity*2.98;
break;
case 2:total+=quantity*4.50;
break;
case 3:total+=quantity*3.98;
break;
case 4:total+=quantity*4.49;
break;
case 5:total+=quantity*6.87;
break;
default:System.out.println("Invalid Product Number");
System.out.println("Product Number Does not Exist");
if(product<0 && product>=6)
{
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
}
break;
}
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
}
pause();
}
private static void displaySales()
{
System.out.println( "The total retail value was: " + total );
pause();
}
}//end MenuDemo

Categories

Resources