Trying to access a sets of variable from string (JAVA) - java

Given this :
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
play(1);
break;
case "2":
play(2);
break;
case "3":
play(3);
break;
default:
System.out.println("invalid");
/?? means I don't know
public static void play(1??){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
// if yes ?? ++win1
// if no ?? ++loose1
// I know how to do those loops, I don't know how to make the variable choice fit the current case (++win2 and ++loose2 ans the case 2: for example)
}
My problem, for every cases, there are a set of specific variables that has to be increment (example casevar1, win1, loose1, etc.), if the case 2 is selected, I want that the variables in the play() method now automatically refer to the proper variables (example casevar2, win2, loose2, etc.). So how do I pass that information to the play() method?

You could do somthing like this
public static void play(String s){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
if("1".equals(s)) {
if("y".equals(choice)) {
win1 ++;
} else if ("n".equals(choice)) {
loose1 ++;
}
}
if("2".equals(s)) {
if("y".equals(choice)) {
win2 ++;
} else if ("n".equals(choice)) {
loose2 ++;
}
}
}

Ok, with inspiration from you guys, I've answered my question. I did it this way :
in the main, something like that
case "1":
play(1, nbEasy, easyPos, easyNeg);
break;
case "2":
play(2, nbInter, interPos, interNeg);
break;
case "3":
//same thing with hard
and in the play() method, something like that :
public static void play(int niv, int nbGames, int nbPos, int nbNeg){
++nbGames;
System.out.print("Completed? ( (y)yes or (n)o ) ");
choice = validation.nextLine();
if (choice.equals("y")){
++nbPos;
}
else if (choice.equals("n"))
++nbNeg;
switch (niv){
case 1:
nbEasy=nbGames; easyPos=nbPos; easyNeg=nbNeg;
case 2:
nbInter=nbGames; interPos=nbPos; interNeg=nbNeg;
case 3:
//same thing with hard
}
}
It’s perfect for me, because I can add a lot of lines in the first section of the play () method, working with what has been passed with the switch in the main and at the end, I’m affecting the new values to the proper variables.
I would like to thank you all, I’m new to programming and new to this community, but for having tried a bunch of places, that place looks by far the best. You’re responsive, polite, cordial, and I will read all the rules to suit better this place, prepare more my questions and when I will be able, I will help others. This place is amazing, I love you guys.

I am not sure I fully understand your question. I think part of it is how to pass parameters to a method. Please follow the code and comments :
//I used 3 integers just for demonstration purpose
int casevar1, win1, loose1,casevar2, win2, loose2;
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//assign values
casevar1 =7; win1 =9; loose1 =0;
play(casevar1, win1, loose1); //pass appropriate variables to play method
break;
case "2":
//assign values
casevar2 =17; win2 =8; loose2 = 4;
play(casevar2, win2, loose2); //pass appropriate variables to play method
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(int casevar, int win, int loose){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
EDITED: Added an example to answer your question.
Create an object warping the data, as #David Wallace suggested:
public class Test {
public static void main(String[]arghs){
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//set an object initialized to casevar =7, win =9, loose = 0
play(new DataObject(7,9, 0));
break;
case "2":
play(new DataObject(17,8, 4));
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
}
//play method receiving data object
public static void play(DataObject data){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//
casevar++;
}
//as David Wallace proposed
//an object containing the 3 parameters you mentioned
class DataObject {
private int casevar; private int win; private int loose;
DataObject(int casevar, int win, int loose){
this.casevar = casevar;
this.win = win;
this.loose = loose;
}
public int getCasevar() {
return casevar;
}
public void setCasevar(int casevar) {
this.casevar = casevar;
}
public int getWin() {
return win;
}
public void setWin(int win) {
this.win = win;
}
public int getLoose() {
return loose;
}
public void setLoose(int loose) {
this.loose = loose;
}
}
}
If it doesn't answer or not clear enough don't hesitate to ask.

Related

Trying to loop switch statement through JOptionPane input using do while loop

The switch statement manages to compute the default case if the user places an incorrect input that doesn't match any of the following cases, but after the "incorrect statement" the code crashes and doesn't continues to the next line of code where my loop supposedly happen.
import javax.swing.JOptionPane;
public class Testing {
public static void main(String[] args) {
String input;
double transportEmission;
do {
input = JOptionPane.showInputDialog("""
Which of the following do you use to commute to school everyday?
car
bus
train""");
switch(input) {
case "car": transportEmission = 12.6; //in kg
break;
case "bus": transportEmission = 11.7; //in kg
break;
case "train": transportEmission = 0.5; //in kg
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Option, please try again");
return;
}
input = JOptionPane.showInputDialog("Did you enter either car, train or bus only (Yes/No)?");
} while ("no".equals(input)); {
}
JOptionPane.showMessageDialog(null, "Transport Emission is : " + transportEmission);
}
}

Getting constructor to work initial variables

import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
StageA stageA = new StageA();
stageA.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private static void displayMenu() {
System.out.printf("\n **** Ozzey Attraction Menu ****\n");
System.out.printf("A : Add New Attraction\n");
System.out.printf("B : View Attraction\n");
System.out.printf("C : List All Attractions\n");
System.out.printf("D : Sell Ticket\n");
System.out.printf("E : Refund Ticket\n");
System.out.printf("F : Remove Attraction\n");
System.out.printf("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private static void createAttraction() {
System.out.printf("Enter attraction description : ");
String description = sc.nextLine();
System.out.printf("Enter cost of a Ticket : ");
double ticketCost = Double.parseDouble(sc.nextLine());
System.out.printf("Is this a supervised tour ? [Y/N] :\n");
char chosen = sc.nextLine().to Lowercase().charAt(0);
System.out.printf("What is maximum permitted tour group size?\n");
int maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.printf("Enter the agency contact details:\n ");
String contactDetails = sc.nextLine();
int counter = 0;
String[] storedActivities;
String guide, rating;
switch (chosen) {
case 'y':
System.out.printf("How many activity are there?\n");
int activities = Integer.parseInt(sc.nextLine());
while (activities < 1) {
System.out.printf("Please enter valid number of activities great than zero \n");
System.out.printf("How many activity are there?\n");
activities = Integer.parseInt(sc.nextLine());
}
storedActivities = new String[activities];
while (activities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
break;
case 'n':
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
break;
default:
System.out.printf("Please Enter valid answer ");
System.out.printf("Is this a supervised tour ? [Y/N] :\n");
chosen = sc.nextLine().toLowerCase().charAt(0);
break;
}
Attraction attraction = new Attraction(description, ticketCost, maxGroupSize, contactDetails, chosen, guide, rating, storedActivities[counter]);
}
private static void processSelection(char selection) {
switch (selection) {
case 'a':
createAttraction();
break;
case 'b':
System.out.println("b");
break;
case 'c':
System.out.println("c");
break;
case 'd':
break;
case 'e':
System.out.println("e");
break;
case 'f':
System.out.println("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
}
public class Attraction {
private String description, contactDetails, guide, rating;
private double ticketCost;
private int maxGroupSize;
private char chosen;
private String storedActivities;
public Attraction(String description, double ticketCost, int maxGroupSize, String contactDetails,
char chosen, String guide, String rating, String storedActivities) {
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.chosen = chosen;
this.guide = guide;
this.rating = rating;
this.activities = storedActivities;
}
}
I cannot get my constructor to work
Attraction attraction = new Attraction(description, ticketCost, maxGroupSize, contactDetails, chosen, guide, rating, storedActivities[counter]);
where every I move it to I cannot get into to work I tried while if statement and changed to a switch statement but I get the same error error I getting cannot resolve variable rating, guide and storedActivities[counter] any help would be appreciated
I can only use a single array and the questions are in order I need to ask them.
The compiler is complaining because there is a risk you will not have initialised your variables by the time you attempt to instantiate your Attraction instance.
The following lines declare your variables but at this point they have not been assigned a value:-
String[] storedActivities;
String guide, rating;
Note that if your code enters either the default or the 'n' case in your switch statement, some of these variables remain unset. You need to fix this before the compiler will be satisfied that it has all the information it needs to create your Attraction object.
Your solution is down to coding preference & needs. You could assign a default value to these parameters, use tail recursion to prevent incorrect answers from the scanner, or provide an alternative constructor if not all details are required.
Hi this would be because your variables are not intialised at the start.
Think about it: The vars rating, guide and storedActivities[] will not be intialised if the chosen = anything other than y or n. The JVM automatically senses this and throws an error automatically.
What I suggest you do is set them to a default size (the array) or a default value, so that this error will not occur. Having the default value also means you could automatically override any incorrect values given by the user.

Issue regarding Methods and Classes, Non-Static Error and more

I am trying to develop a simple program that will take inputs 1-11 from a user and digest them within a class and output a clean printed statement that will change based on these inputs.
Here is some of my current code.
public static void main(String[] args) {
mainInputMenu();
}
private static void mainInputMenu() {
System.out.println ( "=======================================\n"
+ "Welcome to the Ticket Counter\n"
+ "1. Approach first machine.\n"
+ "2. Approach Second machine\n"
+ "3. Exit." );
Scanner keyboard = new Scanner ( System.in );
String ticketCounter;
int counter = 0;
//I have a do while statement which confirms input but irrelevant
while ( counter == 1 ) {
machineOne ( counter );
}
while ( counter == 2 ) {
machineTwo ( counter );
}
while ( counter == 3 ) {
System.exit(0);
}
}
public static void machineOne(int counter) {
Scanner keyboard = new Scanner ( System.in );
String ticketInput;
int choice = 0;
TheMachine machineOne = new TheMachine();
TheMachine.writeOutput();
switch ( choice ) {
case 1:
machineOne.option = 1;
break;
case 2:
machineOne.option = 2;
break;
case 3:
machineOne.option = 3;
}
}
This is the main program with up to only 3 options at the moment. Now going into what I don't understand... I can attempt to move through this via a method I thought may possibly work being to create sub-components of this class to do the work and print those variables within the writeOutput(). Which results in non-static method cannot be referenced from static context error like below.
public class TheMachine {
public static void writeOutput() {
System.out.println ( " ------------------------------------------\n");
System.out.println ( "Adults: " + getadultSum() ); //Simplified to show the issue
public int getadultSum () {
switch ( option ) {
case 3:
adultSum = adultSum + 1;
return adultSum;
case 4:
adultSum = adultSum - 1;
return adultSum;
}
Or my first attempt solution which was to make a switch based on the option variable to change these different variables. Some include # of Adults, # of Children, Dollar Amount entered, etc.
static void writeOutput()
{
int childTickets = 0;
int adultTickets = 0;
String route = "";
int childSum = 0;
int adultSum = 0;
int creditSum = 0;
switch (choice) {
case 1:
route = "Uptown";
break;
case 2:
route = "Downtown";
break;
case 3:
adultSum = adultSum + 1;
break;
default:
break;
}
But this issue I run into with this one, I mean it works once around but every time you enter a new input the variable is reset to 0.
If anybody takes the time to read through this and can provide me with some help, bless you. I appreciate all your time and efforts.

making a custom method with an array print a value

I am trying to make this method print one of the four string messages contained within String[] strArr. I have tried doing this by calling the method in the main method, by typing many different forms of simpleArray(); and I have tried filling the parenthesis, writing it several different ways but nothing has worked. I have actually been working on it for days, and usually I give up and move on to a different part of the code.
Though it may seem impractical, I do need the method to be written similarly to the way it is because my project criteria states it must contain one argument and return void.
public static void simpleArray(String[] greetings) {
String[] strArr = {"Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card", "We value your business!"};
int i = (int)(Math.random() * strArr.length);
System.out.println(strArr[i]);
}
here is my main method, where I try to call the custom method in line 6.
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray();
printStartupMessage();
Scanner keyboard = new Scanner(System.in);
Scanner keyboardDouble = new Scanner(System.in);
saveRandomBalance = getRandomBalance();
System.out.println("CHECKING BALANCE**** $" + saveRandomBalance);
System.out.println("Would you like to withdrawl from CHECKING****? Y/N");
String proceedWithWithdrawl = keyboard.nextLine();
while (!proceedWithWithdrawl.equalsIgnoreCase("y") && !proceedWithWithdrawl.equalsIgnoreCase("n")
&& !proceedWithWithdrawl.equalsIgnoreCase("yes") && !proceedWithWithdrawl.equalsIgnoreCase("no"))
{
System.out.println("Invalid response. Enter [Y] or [N].");
proceedWithWithdrawl = keyboard.next();
}
switch(proceedWithWithdrawl)
{
case "N":
case "n":
case "nO":
case "NO":
case "No":
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
break;
case "yeS":
case "YEs":
case "yEs":
case "yES":
case "YeS":
case "YES":
case "Yes":
case "yes":
case "y":
case "Y":
System.out.println("Enter amount to withdrawl: ");
amountToWithdrawl = keyboardDouble.nextDouble();
remainingBalance = saveRandomBalance - amountToWithdrawl;
remainingBalance = Math.round(remainingBalance * 100);
remainingBalance = remainingBalance/100;
if (amountToWithdrawl % 20 == 0 && amountToWithdrawl <= saveRandomBalance)
{
System.out.println("Dispensing...");
System.out.println("ACCOUNT BALANCE: $" + remainingBalance);
System.out.println("$" + amountToWithdrawl + " has been withdrawn from CHECKING****");
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
//CallDollarBill.dollarBill();
}
else if (amountToWithdrawl > saveRandomBalance)
{
System.out.println("Insufficient Balance.");
}
else if (amountToWithdrawl % 20 != 0)
{
System.out.println("Please enter multiples of 20.");
}
//else
//{
// System.out.println("invalid input");
//}
}
}
now, the error it provides is as follows.
firstDraftFinal.java:69: error: method simpleArray in class firstDraftFinal cannot be applied to given types;
simpleArray();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand that part of the problem is probably int i (and strrArr) are integers, but I do not know what to do about this. I hired a tutor, but I ran out of time. I am also aware that the switch statement is not efficient, I will be changing that.
Thank you.
Your current code specifies a parameter that is not used; while it's unclear why you would want to do this, you can simply pass null. However, maybe what you intended was to pass the list of greetings; i.e. see second version below.
class Test {
public static void main(String[] args) {
// Per your current code.
for (int i=0; i&lt10; i++) simpleArray(null);
System.out.println("");
// What you may be looking for.
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
for (int i=0; i&lt10; i++) simpleArray2(strArr);
}
public static void simpleArray(String[] greetings) {
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
int i = (int) (Math.random() * strArr.length);
System.out.println(strArr[i]);
}
public static void simpleArray2(String[] greetings) {
int i = (int) (Math.random() * greetings.length);
System.out.println(greetings[i]);
}
}
You have compile error because you didn't pass any arguments to method that require them, just pass to your method any string array, because you don't use passed argument in this method:
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray(new String[0]);
printStartupMessage();
To continue refactor your code you may want to get rid of this argument (pay attention if other parts of code may use it) and rewrite it like this:
public static void printGreetings() {
String[] greetings = {"Welcome To CWU BANK!",
"Thank you for using CWU ATM!",
"Please insert DEBIT card",
"We value your business!"
};
int random = new Random().nextInt(greetings.length);
System.out.println(greetings[random]);
}

How to avoid an else if marathon in Java?

I am beginning Java programming, and I have written a program which tests how many moons each planet has. Here is a shortened version with only four of the planets.
import java.util.Scanner;
import java.util.Random;
public class one {
public static void main(String args[]){
//SET VARIABLES
String zero="Mercury", one="Venus", two="Earth", three="Mars";
//SET VARIABLES
for (int x=1; x<=1000; x++){
System.out.println("Moons");
Random r = new Random();
for (int y=1; y<=1; y++){
int rI = r.nextInt(4);
if (rI == 0){
question(zero,0);
}
else if (rI == 1){
question(one, 0);
}
else if (rI == 2){
question(two, 1);
}
else if (rI == 3){
question(three, 2);
}
}
}
}
public static void question(String n, int num){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + n + " have? ");
int ans = input.nextInt();
if (ans == num){
System.out.println("Correct!");
}
else if (ans != num){
System.out.println("Incorrect!");
question(n, num);
}
}
}
How would I go about not having to write "else if" so many times? This becomes very tedious with more statements. Keep in mind I am a beginner, and this code is about the limit of my current abilities.
You could use arrays like so:
String[] planets = { "Mercury", "Venus", "Earth", "Mars" };
int moons[] = { 0, 0, 1, 2 };
and call:
if (rI >= 0 && rI < planets.length) {
question(planets[rI], moons[rI]);
}
A better way to write this code. It is more readable and it is very easy to make any updates.
import java.util.Scanner;
import java.util.Random;
public class one {
public static void main(String args[]){
//SET VARIABLES
String planets []=new String[4];
planets[0]="Mercury";
planets[1]="Venus";
planets[2]="Earth";
planets[3]="Mars";
int moons []=new int[4];
moons[0]=0;
moons[1]=0;
moons[2]=1;
moons[3]=2;
//SET VARIABLES
while(true){
System.out.println("Moons");
Random r = new Random();
int rI = r.nextInt(4);
question(planets[rI],moons[rI]);
}
}
public static void question(String n, int num){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + n + " have? ");
int ans = input.nextInt();
if (ans == num){
System.out.println("Correct!");
}
else if (ans != num){
System.out.println("Incorrect!");
question(n, num);
}
}
}
You could go with switch or if-else as long as you logic does not evolve. Otherwise you need to start the object-oriented programming.
Create a class "Planet" and another class for each planet that inherits from Planet and add the planet specific information to each of it. Then you're good for the future when you may plan to add some more questions for the planets.
Take a look at the switch statement in Java. That is designed to help overcome a screwy if-elseif-elseif-elseif-else block:
switch(rI){
case 2: question(two, 1);
break;
case 3: question(three, 2);
break;
default: doSomethingClever(...);
}
There are some other cleanups you could employ, but getting that switch block in place addresses your initial comment. Good luck.
You can try using switch instead of the long if-else ladder.
For more information on switch read the java documentation
In your case it could be something like:
switch (rI) {
case 0:
question(zero, 0);
break;
case 1:
question(one, 0);
break;
case 2:
question(two, 1);
break;
case 3:
question(three, 2);
break;
default:
break;
}
You could use the switch keyword:
switch (rI) {
case 0:
question(zero, 0);
break;
case 1:
question(one, 0);
break;
case 2:
question(two, 1);
break;
case 3:
question(three, 2);
break;
default:
// do something
}
The code under default executes when no match is found.
You could also use arrays:
String[] planets = new String[]{"Mercury", "Venus", "Earth", "Mars"};
int[] nums = new int[]{0, 0, 1, 2};
...
// in the loop:
question(planets[rI], nums[rI]);
Of course, there are other ways to approach the problem, but I think for someone who is just learning these should do the trick. One thing you might want to look into, however, (once you get deeper into Java), is the concept of a Map, much like a dictionary in Python. You could maintain a map that maps a planet (string) to the number of moons it has (int).
I would prefer enums over arrays here. See this enums tutorial (especially the planets example ;) ). Add another field (just like mass and radius) for moon count.
I would start with forgetting that vector-thing and putting Planets and their Moons together in a POJO (Plain Old Java Object) and putting those objects into the Array:
class Planet {
int moons;
String name;
Planet(String name, int moons) {
this.name = name;
this.moons = moons;
}
public String getName() {
return this.name;
}
public getMoons() {
return this.moons;
}
public void question(){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + this.name + " have? ");
int ans = input.nextInt();
if (ans == this.moons){
System.out.println("Correct!");
}
else {
System.out.println("Incorrect!");
}
}
}
public class one {
public static void main(String args[]){
//SET VARIABLES
List<Planet> planets = new ArrayList<Planets>();
Planet earth = new Planet("Earth", 1);
// put other planets
//SET VARIABLES
for (int x=1; x<=1000; x++) {
System.out.println("Moons");
Random r = new Random();
int rI = r.nextInt(planets.size());
Planet p = planets.get(rI);
p.question();
}
}
}

Categories

Resources