//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
Related
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...
edit:
adding the one of the methods called below, just in case the problem is with the method, not the loop.
Below is a switch menu, there are several cases in the switch. Each case calls a a public void method form another class, and completes successfully, is supposed to displays the menu method (method that prints menu options) and allow the user to select another option. Currently, after completing one case, the program showMenu() again, then breaks at instantly:
String menu = in.nextLine();
on the second iteration of the menu and sends back
java.util.NoSuchElementException: No line found
Question: I need the program to pause or something similar after showMenu(); to let the user input a menu selection, currently the menu displays and the program crashes instantly
Cheers
public class Menu {
public static char selection;
public static String quitting = "you dun son";
public static String errorMessage = "THAAAAATSS A menu WRRRAAAAAPPP";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
do {
showMenu();
String menu = in.nextLine();
if (menu.length() > 0) {
selection = menu.toLowerCase().charAt(0); // extract the first char of the line read
} else {
selection = '\0';
System.out.println("invalid input:\t" + selection);
System.out.println("Press enter to continue...");
}
switch (selection) {
case 'f':
FuelConsole fuelObject = new FuelConsole();
fuelObject.fuelCalc();
break;
case 'g':
GameConsole gameObject = new GameConsole();
gameObject.gameCalc();
break;
case 'q':
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
{
System.out.println(quitting);
System.exit(0);
}
}catch (Exception e) {
System.out.println(errorMessage);
}
}
a test method:
public class FuelConsole {
public static String errorMessage = "THAAAAATSS A fuel calc WRRRRAAAAAPPPPPPPPPPPP";
public static Double acceptableCentsPerLitre = 16.00;
Scanner scan = new Scanner(System.in);
public void fuelCalc() {
try {
System.out.println("\nyou selected option 'f' --- here you will enter some information and find average fuel for ONE trip. ");
System.out.println("please enter the amount of fuel in litres:\n ");
float fuel = scan.nextFloat();
System.out.println("please enter the price of fuel in cents (not dollars and cents, only CENTS (lulz)):\n ");
int cent = scan.nextInt();
System.out.println("please enter the number of kilometers travelled on the tank:\n ");
float kilo = scan.nextFloat();
float returnAFC = afc(fuel, kilo);
float returnAC = ac(returnAFC, cent);
System.out.println("average consumption: \t" + returnAFC);
System.out.println("average cost: \t\t" + returnAC);
if (returnAC > acceptableCentsPerLitre) {
System.out.println("Average fuel is above 16c per litre");
} else {
System.out.println("Average fuel is below 16c per litre");
}
} catch (Exception e) {
System.out.println(errorMessage);
e.printStackTrace();
} finally {
scan.close();
}
}
public static float afc(float x, float z) {
float result = x / z;
return result;
}
public static float ac(float x, int y) {
float result = x * y;
return result;
}
}
I think the problem is that you create a new Scanner in the FuelConsole Class.
And you also close it in the finally block.
But when you call close() on scanner it also closes the underlaying InputStream too. (System.in in this case) And because your top-level Scanner uses the same InputStream, it cannot catch any more input from it.
The solution could be if you pass the top level scanner as an argument to other objects:
case 'f':
FuelConsole fuelObject = new FuelConsole();
fuelObject.fuelCalc(in);
break;
case 'g':
GameConsole gameObject = new GameConsole();
gameObject.gameCalc(in);
break;
and
public void fuelCalc(Scanner scan) {
try {
...
and delete the finally block
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);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I haven't asked many questions on here so sorry if I have laid this question out wrongly.
I am trying to call the variable AmountOfTickets in the main class. So I can update it with each loop of the while loop. I don't know how to properly call the variable without eclipse showing an error.
This is the class where I have created the variable AmountOfTickets which
I am trying to update
public class TicketHandler {
public int TicketCost;
public static int AmountOfTickets;
public TicketHandler(int TicketCost, int AmountOfTickets){
this.TicketCost = TicketCost;
this.AmountOfTickets = AmountOfTickets;
}
public TicketHandler() {
TicketCost = 200;
AmountOfTickets = 50;
}
public int getTicketCost() {
return TicketCost;
}
public void setTicketCost(int ticketCost) {
TicketCost = ticketCost;
}
public static int getAmountOfTickets() {
return AmountOfTickets;
}
public void setAmountOfTickets(int amountOfTickets) {
AmountOfTickets = amountOfTickets;
}
public void ReduceNoOfTickets(int TicketsSold) {
this.AmountOfTickets = this.AmountOfTickets - TicketsSold;
}
}
This is the main program code where I am trying to call the variable and used it
import java.util.Scanner;
public class ApplicationProgram {
static Scanner inKey = new Scanner(System.in);
public static void main(String[] args) {
TicketHandler Red = new TicketHandler (200,50);
TicketHandler Green = new TicketHandler (200,50);
TicketHandler Blue = new TicketHandler (200,50);
TicketHandler Yellow = new TicketHandler (200,50);
boolean running = true;
//Main menu
while (running) {
printMenu();
int KeyIn = inKey.nextInt();
//menu
switch (KeyIn) {
case 1:{
RedRoute();
break;
}
case 2:{
GreenRoute();
break;
}
case 3:{
BlueRoute();
break;
}
case 4:{
YellowRoute();
break;
}
case 5:{
ShowAvailableTicketsAndPrice();
break;
}
case 6:{
System.out.println("Do you wish to quit: type Y to confirm");
String quitYN = inKey.next ();
//System.out.println(quitYN);
if ((quitYN.matches("Y")) || (quitYN.matches("y"))) {
System.out.println("Goodbye\n\n");
running = false;
System.exit(0);
}
break;
}
default:{
System.out.println("Not a valid option, try again.");
break;
}
}
}
}
public static void printMenu(){
System.out.println("Bus Tickets");
System.out.println("---- ----");
System.out.println("1. \tRedRoute");
System.out.println("2. \tGreenRoute");
System.out.println("3. \tBlueRoute");
System.out.println("4. \tYellowRoute");
System.out.println("5. \tShowAvailableTicketsAndPrice");
System.out.println("6. \tQuit");
}
public static void RedRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200) {
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void GreenRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200){
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void BlueRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int moneyin = 200;
while (moneyin <= 200){
System.out.println("Insert £" + moneyin);
int KeyIn = Red.nextInt();
moneyin = moneyin - KeyIn;
if (moneyin == 0){
System.out.println("Enjoy");
AmountOfTickets = get.AmountOfTickets - 1
break;
}
}
}
public static void YellowRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200) {
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void ShowAvailableTicketsAndPrice(){
System.out.println("Routes available:");
System.out.println("\tRed route, Tickets left: "+ "Price: ");
System.out.println("\tBlue route, Tickets left: " + "Price: ");
System.out.println("\tGreen route, Tickets left: " + "Price: ");
System.out.println("\tYellow route, Tickets left: " + "Price: ");
}
}
Thank you.
First of all, your var called AmountOfTickets is static, it means one copy will live to all objects, also your method getAmountOfTickets.
you have a problem here
AmountOfTickets = get.AmountOfTickets - 1
you must call the variable using the ClassName.YourVar like this:
TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1;
also your method.
Also you could import a static like this:
import java.util.Scanner;
import static huh.TicketHandler.*;
so you can use:
AmountOfTickets = getAmountOfTickets() - 1;
"You could think in create an object and call the var like this"
public static void BlueRoute(){
Scanner Red = new Scanner(System.in);
TicketHandler objectOne = new TicketHandler(); //HERE I CREATED AN OBJECT
System.out.println();
int moneyin = 200;
while (moneyin <= 200)
{
System.out.println("Insert £" + moneyin);
int KeyIn = Red.nextInt();
moneyin = moneyin - KeyIn;
if (moneyin == 0){
System.out.println("Enjoy");
objectOne.AmountOfTickets = objectOne.getAmountOfTickets() - 1; //HERE I USED IT
break;
}
But as this is static it will replace objectOne to
TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1; //HERE I USED IT
So, in my humble opinion you can or use an import static (so you avoid to write the same class name before your static), or put the name of your class first then the name and method.
Using an import static could be bad if there is another class with the same name or method as yours and you imported, because compiler could say, hey which one am I suppose to use?
So, I'd rather use fullnameClass.varOrMethod
hope it helps
btw using this: TicketHandler.AmountOfTickets and this: TicketHandler.getAmountOfTickets() are avable to be used in all ApplicationProgra's class code as i said because it is static, and because you difined them public
public static int AmountOfTickets;
public static int getAmountOfTickets() {
return AmountOfTickets;
}
=) i guess that was what you asked for. c-ya
I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}