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.
Related
Problem with method repeating infinitely rather than moving on to the next method. Specifically, the group method is being repeated infinitely rather than breaking after 1 iteration.
public static void main(String[] args)
{
int time = 0;
int gearCount = 0;
int group = 0;
int total = 0;
int answer = 1;
int rent = 0;
int period = 0;
int total1 = 0;
group = group();
rent = rent();
}
start of 'group' method (method that repeats infinitely)
public static int group()
{
String input = " ";
int [] group = {0};
for(int i = 0 ; i <1 ; i++)
{
input = JOptionPane.showInputDialog(null, "Enter the number of people in your group, minimum of 5 people required: ");
group[i] = Integer.parseInt(input);
if(group[i]<5)
{
int again = 0;
again = JOptionPane.showConfirmDialog(null, "You have " +group[i]+ " people in your group, that is below the requirement, would you like to try again? " , "Error!", JOptionPane.YES_NO_OPTION);
if(again == JOptionPane.YES_OPTION)
{
group();
}
else
{
JOptionPane.showMessageDialog(null, "Ok good bye!");
}
}
else
{
JOptionPane.showMessageDialog(null, "OK! You have a total of " +group[i]+ " people on your team, you meet the requirement!");
}
}
return group();
}
Start of 'rent' method(the method that does not run even though it is being called in main
public static int rent()
{
int [] rent = {0, 5};
for(int i = 0 ; i < rent.length; i++)
{
rent[i] = JOptionPane.showConfirmDialog(null, "Would you like to rent gear for $5? ", "Rent", JOptionPane.YES_NO_OPTION);
if(rent[i] == JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "Your additional rent fee is: $" +rent[1]+ " per person!" );
}
else
{
JOptionPane.showMessageDialog(null, "Your additional rent fee is: $" +rent[0]);
}
}
return rent();
}
For what I can see on your group() method is that at the end when you end the method you return group() (making it recursive and that's the reason it loops). I imagine you want to get the number of team members on each team so instead of returning 'group()' you should return your array group and as well change your function type from int to int[] like this
public static int[] group(){
int [] group = {0};
// Do your for operation and all
return group;
}
As well you need to change on your main method group = group() to group[] = group() and make group an array of integers
import java.util.Scanner;
public class MP3
{
//this is the main code that I need to connect each method to each method.
//so that if the user press 2 it will go to snacks but even if you press two now it just continues the code and go-to meals.
//how can I make it so that the user can choose which menu he/she likes to go through?
public static void main(String[] args)
{
int Options_Snacks;
int Options_Snacks2;
int Options_Snacks3;
int Options_Drinks;
int Options_Drinks2;
int Options_Drinks3;
int diff,prod ;
int yes = 1;
int no = 2;
int End;
do {
mainmenu();
mainmeals();
mainsnacks();
Scanner myInput = new Scanner(System.in);
System.out.println("Would you like to order more: press " + yes +" for yes and " + no +" for no");
End = myInput.nextInt();
} while(End == 1);
}
// this code runs smoothly but the other menus don't run when the user press the number instead it runs all the code within the while loop.
public static void mainmenu()
{
int Orders;
int Meals = 1;
int Snacks = 2;
int Drinks = 3;
int EXIT = 4;
Scanner myInput = new Scanner(System.in);
System.out.println("=======[STRESSFOOD]=====");
System.out.println("---------[ Menu ]-------");
System.out.println("1----------Meals--------");
System.out.println("2---------Snacks--------");
System.out.println("3---------Drinks--------");
System.out.println("4--------[ EXIT ]-------");
Orders = myInput.nextInt();
}
[here's the code I didn't get all in the picture][1]
}
What about the following implementation:
public static void main(String[] args) {
openMenu();
}
With the while loop in the menu function :
private static void openMenu() {
Scanner scan = new Scanner(System.in);
do {
System.out.println("1) Meals");
System.out.println("2) Snacks");
System.out.println("3) Drinks");
System.out.println("4) Exit");
System.out.print("Your choice ? ");
switch (scan.nextInt()) {
case 1:
openMealsMenu();
break;
case 2:
openSnacksMenu();
break;
case 3:
openDrinksMenu();
break;
case 4:
scan.close();
return;
default:
System.out.println("This is not a valid choice");
}
} while (true);
}
Note that you should only use one scanner in your application. If you need your scanner in the openMealsMenu() for example, pass it as a parameter of the method, or just declare a static scanner in your MP3 class since your methods are in the same class.
By the way, by convention, variables should start with a lowercase letter and do not take a _ (ie. Options_Drinks3 becomes optionsDrinks3).
So I am working on a slot machine on Java using only the console. I have some strings with ASCII word art that must be displayed on blocks of three, horizontally, like a slot machine.
static final String pera = " ( \n / \\ \n ( ) \n `\"' \n \n";
static final String platan = " \n , \n \\`.__.\n `._,'\n \n";
static final String raim = " \\ \n ()() \n()()()\n ()() \n () \n";
static final String kiwi = " \n,=. \n(.`:) \n `-' \n";
static final String penaut = " ,+. \n((|)) \n )|( \n((|)) \n `-' ";
So right now this is the output
And I need it to look like this target output
The problem is that the strings I'm using are not just 1 line strings, so the usuall methods to print on the same line doesn't work, like using print instead of println. Is this even possible to program on java?
Complete code:
package Escurabutxaques;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Escurabutxaques {
static boolean correcte = false;
static String res1 = "";
static String res2 ="";
static String res3 = "";
static final String pera = " ( \n / \\ \n ( ) \n `\"' \n \n";
static final String platan = " \n , \n \\`.__.\n `._,'\n \n";
static final String raim = " \\ \n ()() \n()()()\n ()() \n () \n";
static final String kiwi = " \n,=. \n(.`:) \n `-' \n";
static final String penaut = " ,+. \n((|)) \n )|( \n((|)) \n `-' ";
public static void main (String[] Args){
System.out.println("Benvingut a la màquina escurabutxaques de l'Andreu!");
Random();
}
public static void Random() {
for (int i = 0; i < 3; ++i) {
String print = "";
Random r = new Random();
int randomNumber = ThreadLocalRandom.current().nextInt(1, 5 + 1);
if (randomNumber == 1) {
print = pera;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 2) {
print = raim;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 3) {
print = platan;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 4) {
print = kiwi;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 5) {
print = penaut;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
};
System.out.println(print);
Random();
}
}
}
You want to print three different things, and each thing is going to take up multiple rows, and you want the three things to appear side by side. There is a way to do this:
make sure each of your possible items to show is built of the same number of rows, and each row is of the same width
build each item as an array of strings, where each string in the array is one of the required rows of symbols:
String[] apple = new String[5];
apple[0] = ",./.,/";
apple[1] = "/dkj/!";
etc
or whatever the apple looks like.
run code to determine which three items should be displayed, e.g. apple banana apple
write an output builder which knows at the start what three things it needs to put together, in this case an apple followed by a banana followed by another apple. This output builder will return an array of Strings, where row in the array is composed of the corresponding rows from the component objects.
String[] outputToDisplay = new String[5];
outputToDisplay[0] = apple[0] + banana[0] + apple[0];
outputToDisplay[1] = apple[1] + banana[1] + apple[1];
etc
You may wish to insert a blank space between each item in each row.
print the output
I'm identifying that it seems that every fruit String object is composed of 7 characters before it goes onto the next line. What you could do is simply take out the first 7 characters of the first fruit, then go on to the next fruit and take out the next 7 characters of the next fruit and concatenate these two Strings together. Keep on continuing this until you've reached the final fruit. You can then save the String which represents the first line in an array. Then you can simply move on the next 7 characters(a.k.a the second line) and repeat the process all over again. After you've gone through all the fruits, simply print out the string array.
Try ANSI cursor movement.
Here is an example code to print two slots.
After understanding the trick, you can easily expand it to print three slots.
private static void printSlots(String slot1, String slot2) {
int m = 0;
int n = 0;
for (String line : slot1.split("\n")) {
System.out.println(line);
m = m > line.length() ? m : line.length();
n += 1;
}
System.out.print("\033[" + n + "A"); // ANSI cursor movement to up
for (String line : slot2.split("\n")) {
System.out.print("\033[" + m + "C"); // ANSI cursor movement to right
System.out.println(line);
}
}
After printing n lines, it goes back. Then, it print each line of next slot with left m paddings.
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.
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();
}
}
}