Java - Returning constructor method with array - java

I have 2 files, one of which request user input, and one of which returns array values based on user input. I'm having an issue returning my array. I'm only receiving specific elements within each array, although I'd like to return the whole thing. Do you see what I'm missing? Thanks.
// Filename SalonReport.java
import java.util.*;
import javax.swing.*;
import java.util.Scanner;
import java.util.Arrays;
public class SalonReport {
public static void main(String[] args) {
int x, y, sortSelect, view;
boolean repeat = false;
boolean loop = false;
int z = 1;
Scanner input = new Scanner(System.in);
System.out.print("Welcome to Erik's Hair Salon");
System.out.println();
//Using do-while to assign selection
do
if(z > 0)
{
//Welcoming message
Service description = new Service();
Service price = new Service();
Service minutes = new Service();
System.out.println();
System.out.println("We offer the following services at our salon:");
System.out.println();
System.out.println("Service" + "\t" + "\t" + "Price" + "\t" + "Minutes");
System.out.println("************************************");
for (x = 0; x < 6; x++) {
for (y = 0; y < 3; y++) {
System.out.print(description.getService() + "\t" + "\t");
}
System.out.println();
}
//User input message
System.out.println("How do you wish to sort our table of services?");
System.out.println();
System.out.println("To sort by Service Description, enter 1 >>");
System.out.println("To sort by Price, enter 2 >>");
System.out.println("To sort by Minutes, enter 3 >>");
System.out.println();
System.out.print("To exit, enter 0 >> ");
sortSelect = input.nextInt();
if(sortSelect == 1)
{
System.out.println();
System.out.println("Service" + "\t" + "\t" + "Price" + "\t" + "Minutes");
System.out.println("************************************");
for (x = 0; x < 6; x++) {
for (y = 0; y < 3; y++) {
System.out.print(description.getService() + "\t" + "\t");
}
System.out.println();
repeat = true;
}
}
else if(sortSelect == 2)
{
System.out.println();
System.out.println("Price" + "\t" + "\t" + "Service" + "\t" + "Minutes");
System.out.println("************************************");
for (x = 0; x < 6; x++) {
for (y = 0; y < 3; y++) {
System.out.print(price.getPrice() + "\t" + "\t");
}
System.out.println();
repeat = true;
}
}
else if(sortSelect == 3)
{
System.out.println();
System.out.println("Minutes" + "\t" + "\t" + "Service" + "\t" + "Price");
System.out.println("************************************");
for (x = 0; x < 6; x++) {
for (y = 0; y < 3; y++) {
System.out.print(minutes.getTime() + "\t" + "\t");
}
System.out.println();
repeat = true;
}
}
else if(sortSelect == 0)
{
System.out.println();
System.out.println("Goodbye!");
break;
}
System.out.println();
System.out.println("Do you wish to view our services again?");
System.out.println("Enter 1 for Yes >>");
System.out.print("Enter 0 for No >> ");
view = input.nextInt();
if(view == 1)
{
loop = true;
repeat = true;
}
else if(view == 0)
{
loop = false;
repeat = false;
System.out.println();
System.out.println("Goodbye!");
break;
}
}
else
{
repeat = false;
System.out.println();
System.out.println("Goodbye!");
break;
}
while(repeat = true);
}
}
// Filename Service.java
import java.util.*;
import javax.swing.*;
import java.util.Scanner;
public class Service {
private String[][] sortByDesc = {{"Cut", "$8.00", "15"}, {"Mani.", "$18.00", "30"}, {"Perm.",
"$18.00", "35"}, {"Shampoo", "$4.00", "10"}, {"Style", "$48.00", "55"}, {"Trim", "$6.00",
"5"}};
private String[][] sortByPrice = {{"$4.00", "Shampoo", "10"}, {"$6.00", "Trim", "5"},
{"$8.00", "Cut", "15"}, {"$18.00", "Mani.", "30"}, {"$18.00","Perm", "35"}, {"$48.00",
"Style", "55"}};
private String[][] sortByTime = {{"5", "Trim", "$6.00"}, {"10", "Shampoo", "$4.00"}, {"15",
"Cut", "$8.00"}, {"30", "Mani.", "$18.00"}, {"35","Perm", "$18.00"}, {"55", "Style",
"$48.00"}};
public String getService() {
return sortByDesc[5][2];
}
public String getPrice() {
return sortByPrice[5][2];
}
public String getTime() {
return sortByTime[5][2];
}
}

public String getService() {
return sortByDesc[5][2];
}
does only return the element on position 5/2. If you want to return the whole Array it should be like
public String [][] getService() {
return sortByDesc;
}

Related

How can I fix this variable error in my 2D Array program?

I am writing a penny pitch program in java and it is a carnival game. Prizes are randomly generated on a board and 10 coins are thrown. In the "randSelector" method I have written, I am getting an error from "prize" because it says I cant return a String to String []. Any Suggestions? This is my code:
import java.util.Arrays;
import java.util.Random;
public class PennyPitch {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
String[][] board = new String[25][25];
int puzzle = 0;
int poster = 0;
int doll = 0;
int ball = 0;
int game = 0;
int misses = 0;
//Create empty board
Arrays.fill(board, "[ ]");
String[] prizes = {"[ puzzle ]", "[ poster ]", "[ doll ]", "[ ball ]", "[ game ]"};
for (int i = 0; i < prizes.length; i++) {
randSelecter(board, prizes[i], rand);
}
//Simulates 10 pennies thrown
for ( int i = 0; i < 10; i++) {
for ( int j = 0; j < 10; j++){
int box = rand.nextInt(24);
if (board[box][j] == "[ puzzle ]"){
puzzle += 1;
} else if (board[box][j] == "[ poster ]"){
poster += 1;
} else if (board[box][j] == "[ doll ]"){
doll += 1;
} else if (board[box][j] == "[ ball ]"){
ball += 1;
} else if (board[box][j] == "[ game ]"){
game += 1;
}else {
misses += 1;
}
}
System.out.println("Welcome to Penny Pitch!");
System.out.println("Land on three of a kind and win the prize!");
System.out.println("You've thrown 10 pennies on the board below,\n");
//Prints 5 x 5 board
System.out.println(board[0][0] + board[1][1] + board[2][2] + board[3][3] + board[4][4]);
System.out.println(board[5][5] + board[6][6] + board[7][7] + board[8][8] + board[9][9]);
System.out.println(board[10][10] + board[11][11] + board[12][12] + board[13][13] + board[14][14]);
System.out.println(board[15][15] + board[16][16] + board[17][17] + board[18][18] + board[19][19]);
System.out.println(board[20][20] + board[21][21] + board[22][22] + board[23][23] + board[24][24] + "\n");
System.out.println("Here is your outcome:" );
System.out.println("Puzzle: " + puzzle );
System.out.println("Poster: " + poster );
System.out.println("Doll: " + doll );
System.out.println("Ball: " + ball );
System.out.println("Game: " + game );
System.out.println("Misses: " + misses );
//Checks for a win
if ( puzzle == 3){
System.out.println("You won a puzzle!");
} else if ( poster == 3) {
System.out.println("You won a poster!");
} else if ( doll == 3) {
System.out.println("You won a doll!");
} else if ( ball == 3) {
System.out.println("You won a ball!");
} else if ( game == 3) {
System.out.println("You won a game!");
} else {
System.out.println("Sorry, you lost.");
}
}
}
//Randomly place prizes
public static String[] randSelecter(String[][] board, String prize, Random rand) {
for (int i = 0; i < 3; i++) {
int pick = rand.nextInt(24);
int anotherNum = rand.nextInt(24);
if (board[pick][anotherNum] != "[ ]" && board[pick + 1][anotherNum+1] == "[ ]" && pick != 24) {
board[pick + 1] = prize;
} else if (board[pick][anotherNum] != "[ ]" && pick != 0 && board[pick - 1][anotherNum-1] == "[ ]") {
board[pick - 1] = prize;
} else if (board[pick][pick] != "[ ]") {
for (int k = 0; k < board.length; ) {
if (board[k][anotherNum] == "[ ]") {
board[k][anotherNum] = prize;
break;
} else {
k++;
}
}
} else {
board[pick] = prize;
}
}
for(int x = 0;x<30;x++) {
for(int p = 0;p<30;p++) {
return board[x][p];
}
}
}
}
Your return type in randSelecter is String[] but you're returning a String by doing return board[x][p]. Change your return type to String:
public static String randSelecter(String[][] board, String prize, Random rand) {
...
or alternatively change what you're returning

Using variables form other classes in java

I am trying to use two int variables from other classes in another class and then add them together into another variable and print the result. When I try this though, I always get a result of zero like the values are not being brought over into the new class and I can't figure out what the problem is.
Here is some example code:
class1
public static int finished = (match2.totalpoints + match3.iq);
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
EDIT: class2
public class match2 {
public static int totalpoints;
int a;
int b;
int c;
int d;
int e;
int f;
String guess;
String group;
String countdown[] = {
"3...",
"2...",
"1...",
""
};
String memorize[] = {
""
};
public match2() throws InterruptedException
{
int x = set2();
int y = set3();
int z = set4();
total(x, y, z);
System.out.println("For the next part of your IQ ASSesment\njust type back the words in CAPSLOCK in CAPSLOCK");
System.out.println("");
match3 n = new match3();
}
public void set1() throws InterruptedException
{
//Scanner s = new Scanner(System.in);
for (int i = 0; i < countdown.length; i++)
{
Thread.sleep(750);
System.out.println(countdown[i]);
}
}
public int set2() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
group = "" + a + b + c + d;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(guess.equals(group))
{
System.out.println("nice +1 bruh");
rv = 1;
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set3() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your next set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("good");
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set4() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your final set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
e = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f + e;
System.out.println(group);
System.out.println("");
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("great");
}
else if(!group.equals(guess))
{
System.out.println("eeeh buzer sound");
}
return rv;
}
public int total(int x, int y, int z)
{
System.out.println("");
int totalpoints = (x + y + z);
if(totalpoints == 3)
{
System.out.println("YOU GOT THEM ALL");
}
if(totalpoints <= 2 && totalpoints >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalpoints));
}
if(totalpoints == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
return totalpoints;
}
}
EDIT: class3
public class match3 {
public static int iq;
String countupdown [] = {
"READY...",
"SET.....",
""
};
String memorize [] = {
""
};
public match3() throws InterruptedException
{
int mem1 = memory1();
int mem2 = memory2();
int mem3 = memory3();
totalMemory(mem1, mem2, mem3);
}
public void methodCountdown() throws InterruptedException
{
for(int i = 0; i < countupdown.length; i++)
{
Thread.sleep(1000);
System.out.println(countupdown[i]);
}
}
public int memory1() throws InterruptedException
{
int rv = 1;
Scanner s = new Scanner(System.in);
System.out.println("Press ENTER when ready");
s.nextLine();
methodCountdown();
String a = word1();
String b = word2();
System.out.println("The " + a + " ate the " + b);
String wordgroup = "" + a + " " + b;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory2() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String c = word3();
System.out.println("The " + a + " drove the " + c);
String wordgroup = "" + a + " " + c;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory3() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String d = word4();
System.out.println("The " + a + " visited the " + d);
String wordgroup = "" + a + " " + d;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public static String word1()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "DOG";
}
else if(cv == 2)
{
word = "CAT";
}
else if(cv == 3)
{
word = "BIRD";
}
return word;
}
public static String word2()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "FOOD";
}
else if(cv == 2)
{
word = "MUD";
}
else if(cv == 3)
{
word = "GRAINS";
}
return word;
}
public static String word3()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "TRAM";
}
else if(cv == 2)
{
word = "BUS";
}
else if(cv == 3)
{
word = "BICYCLE";
}
return word;
}
public static String word4()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "MALL";
}
else if(cv == 2)
{
word = "PARK";
}
else if(cv == 3)
{
word = "POOL";
}
return word;
}
public void totalMemory(int mem1, int mem2, int mem3)
{
int iq = (mem1 + mem2 + mem3);
System.out.println("");
if(iq == 3)
{
System.out.println("YOU GOT THEM ALL");
}
else if(iq <= 2 || iq >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
}
else if(iq == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
}
}
total points is a variable from match2 class and iq from match3 class. Any help with any methods I could use to make this happen would be much appreciated. Thank You
Well ... besides the fact you are not following any code convention, Like class names should start with a capital letter and public static final fields (like totalpoints and iq) should be all Uppercase (code conventions, you are not sharring match2 and match3 codes, without it we can't understand what is happening inside those classes.
But you can do a simple test and assign a value to match2.totalpoints and match3.iq and you are going to see the summing of these two values being printed by the last system.out you put.
good luck and good Java studies!
Are the int variables you're trying to use inside child classes of your main parent class? Did you extend the child classes in your main parent class?
Class #1:
public int firstVar(int someNum) {
//code here
return someNum;
}
Class #2:
public int secondVar(int otherNum) {
//code here
return otherNum;
}
Class #3 Class with Main Method -
public class mainClass extends class#1; //etc
//code here and finally print out the finished number
You could try extending one of the classes that has an int you need into another one of the classes with the other int you need and then just extending that second class into your main, OR you could try completely redefining your classes and just placing all the ints you need into one separate class and then extending that single one into your main.
So I finally got it to work. The problem, I guess, was that I was trying to add together the variables from the other classes(match2 and match3) outside the main function within the class(match1) I was trying to add them together. All I did was move the expression adding the variables together from the top to inside the main function like this:
public static int finished;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
finished = (match2.totalpoints + match3.iq);
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
Thanks for all the help from everyone.
Smth. like this. You have lot's of code duplication
public class MatchRunner {
public static void main(String... args) throws InterruptedException {
new MatchRunner().start();
}
public void start() throws InterruptedException {
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println();
System.out.println("When taking the quiztest you have only two seconds before making each guess");
int totalPoints = new Match2().getTotalPoints();
System.out.println("For the next part of your IQ Assesment");
System.out.println("just type back the words in CAPSLOCK in CAPSLOCK");
int iq = new Match3().getIQ();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + (totalPoints + iq) + " POINTS");
}
}
public class Match2 {
public int getTotalPoints() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
int totalPoints = calc(scan, "first", "nice +1 try", "almost");
totalPoints += calc(scan, "next", "good", "almost");
totalPoints += calc(scan, "final", "great", "eeeh buzer sound");
printTotalPoints(totalPoints);
return totalPoints;
}
}
private static void countdown() throws InterruptedException {
for (int i = 5; i > 0; i--) {
Thread.sleep(750);
System.out.println(i + "...");
}
}
private static int calc(Scanner scan, String strSet, String strEqual, String strNotEqual) throws InterruptedException {
System.out.println("press ENTER for your " + strSet + " set...");
Random random = new Random();
scan.nextLine();
countdown();
int sum = 0;
for (int i = 0; i < 4; i++)
sum += random.nextInt(9) + 1;
System.out.println(sum);
for (int i = 0; i < 10; i++)
System.out.println();
int guess = scan.nextInt();
System.out.println(guess == sum ? strEqual : strNotEqual);
return guess == sum ? 1 : 0;
}
private static void printTotalPoints(int totalPoints) {
System.out.println();
if (totalPoints == 3)
System.out.println("YOU GOT THEM ALL");
else if (totalPoints <= 2 && totalPoints >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalPoints));
else if (totalPoints == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}
public class Match3 {
public int getIQ() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
Random random = new Random();
Supplier<String> getWord1 = () -> getWord(random, "DOG", "CAT", "BIRD");
Supplier<String> getWord2 = () -> getWord(random, "FOOD", "MUD", "GRAINS");
Supplier<String> getWord3 = () -> getWord(random, "TRAM", "BUS", "BICYCLE");
Supplier<String> getWord4 = () -> getWord(random, "MALL", "PARK", "POOL");
int iq = calc(scan, getWord1, getWord2, "ate the");
iq += calc(scan, getWord1, getWord3, "drove the");
iq += calc(scan, getWord1, getWord4, "visited the");
printIq(iq);
return iq;
}
}
private static void countdown() throws InterruptedException {
System.out.println("READY...");
Thread.sleep(1000);
System.out.println("SET...");
Thread.sleep(1000);
}
public int calc(Scanner scan, Supplier<String> wordOne, Supplier<String> wordTwo, String strMsq) throws InterruptedException {
System.out.println("Press ENTER when ready");
scan.nextLine();
countdown();
String a = wordOne.get();
String b = wordTwo.get();
System.out.println("The " + a + ' ' + strMsq + ' ' + b);
String wordGroup = a + ' ' + b;
for (int i = 0; i <= 10; i++)
System.out.println();
String wordGuess = scan.nextLine();
System.out.println(wordGroup.equals(wordGuess) ? "awesome cock muncher a match" : "nope");
return wordGroup.equals(wordGuess) ? 1 : 0;
}
private static String getWord(Random random, String one, String two, String three) {
int cv = random.nextInt(3) + 1;
if (cv == 1)
return one;
if (cv == 2)
return two;
if (cv == 3)
return three;
return "";
}
public void printIq(int iq) {
System.out.println();
if (iq == 3)
System.out.println("YOU GOT THEM ALL");
else if (iq <= 2 || iq >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
else if (iq == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}

How can I put the item order in a different class?

package project;
import java.util.ArrayList;
import java.util.Scanner;
public class project {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Setting up scanner
Scanner input = new Scanner(System.in);
//Variable to allow user to quit input
String quit = "done";
//Constants
double salesTax = 0.11;
double spagPrice = 7;
double ramenPrice = 4;
double pepperPrice = 9;
double steakPrice = 12;
double tunaPrice = 6;
//Constants for loop
double listTime = 1;
double listMax = 10;
//Variable for loop
double itemEntry = 0;
//Keeps running total of item prices
double priceAdd = 0;
//Initializes array lists
ArrayList<String> itemList = new ArrayList<String>();
ArrayList<Integer> priceList = new ArrayList<Integer>();
ArrayList<Integer> buyList = new ArrayList<Integer>();
ArrayList<String> buyitemList = new ArrayList<String>();
//Adds food names to the correct array
itemList.add("Spaghetti Tacos");
itemList.add("Ramen Pizza");
itemList.add("Stuffed Bell Pepper");
itemList.add("Mushroom Steak");
itemList.add("Tuna Suprise");
//Adds prices to the price array
priceList.add(7);
priceList.add(4);
priceList.add(9);
priceList.add(12);
priceList.add(6);
System.out.println("Please enter a number to indicate your desired item.
Type 'done' when you are done or enter up to 10 items.");
System.out.println(" " + "1" + " " + " " + " " + "2" + " " + " " + " " +
"3" + " " + " " + " " + "4" + " " + " " + " " + "5");
System.out.println(itemList);
System.out.println("Prices: " + priceList);
orderEntry (quit, listTime, listMax, priceAdd, buyitemList);
/** while (quit != "done" || listTime <= listMax)
{
System.out.println("Please enter item " + listTime + " :");
itemEntry = input.nextInt();
if (itemEntry == 1){
priceAdd = spagPrice;
buyitemList.add("Spaghetti Tacos");
}
else if (itemEntry == 2){
priceAdd = ramenPrice;
buyitemList.add("Ramen Pizza");
}
else if (itemEntry == 3){
priceAdd = pepperPrice;
buyitemList.add("Stuffed Bell Pepper");
}
else if (itemEntry == 4){
priceAdd = steakPrice;
buyitemList.add("Mushroom Steak");
}
else if (itemEntry == 5){
priceAdd = tunaPrice;
buyitemList.add("Tuna Suprise");
}
else {
priceAdd = 0;
}
buyList.add((int) priceAdd);
listTime += listTime;
}
*/
double amntTacos = 0;
double amntPizza = 0;
double amntPepper = 0;
double amntSteak = 0;
double amntTuna = 0;
double tacoPrice = 0;
double pizzaPrice = 0;
double belPrice = 0;
double mushPrice = 0;
double suprisePrice = 0;
public orderEntry(speTacos)
{
this.orderEntry = amntTacos;
}
public orderEntry(ramPizza)
{
this.orderEntry = amntPizza;
}
public orderEntry(belPepper)
{
this.orderEntry = amntPepper;
}
public orderEntry(musSteak)
{
this.orderEntry = amntSteak;
}
public orderEntry(tunSup)
{
this.orderEntry = amntTuna;
}
tacoPrice = spagPrice * amntTacos;
pizzaPrice = ramenPrice * amntPizza;
belPrice = pepperPrice * amntPepper;
mushPrice = steakPrice * amntSteak;
suprisePrice = tunaPrice * amntTuna;
System.out.println("---------------------");
System.out.println("---------------------");
double subTotal = 0;
double taxAmount = 0;
double totalPrice = 0;
//for (int i : buyList) {
// subTotal = subTotal + i;
//}
subTotal = tacoPrice + pizzaPrice + belPrice + mushPrice + suprisePrice;
taxAmount = subTotal * salesTax;
totalPrice = subTotal + taxAmount;
System.out.println("You have chosen the following items: " +
buyitemList);
System.out.println("---------------------");
System.out.println("Your Subtotal is: $" + subTotal);
System.out.println("Your Tax amount is: $" + taxAmount);
System.out.println("Your Final Total is: $" + totalPrice);
package project;
import java.util.ArrayList;
import java.util.Scanner;
public class orderEntry (String quit, double itemEntry, double spagPrice,
double
ramenPrice, double pepperPrice, double steakPrice, double tunaPrice, double
listTime, double listMax, Scanner input, double priceAdd, ArrayList buyList)
{
Scanner input = new Scanner(System.in);
double speTacos = 0;
double ramPizza = 0;
double belPepper = 0;
double musSteak = 0;
double tunSup = 0;
while (quit != "done" || listTime <= listMax)
{
System.out.println("Please enter item " + listTime + " :");
itemEntry = input.nextInt();
if (itemEntry == 1){
priceAdd = spagPrice;
speTacos = speTacos + 1;
}
else if (itemEntry == 2){
priceAdd = ramenPrice;
ramPizza = ramPizza + 1;
}
else if (itemEntry == 3){
priceAdd = pepperPrice;
belPepper = belPepper + 1;
}
else if (itemEntry == 4){
priceAdd = steakPrice;
musSteak = musSteak + 1;
}
else if (itemEntry == 5){
priceAdd = tunaPrice;
tunSup = tunSup + 1;
}
else {
priceAdd = 0;
}
buyList.add((int) priceAdd);
listTime += listTime;
}
public void getSpagetti(){
return speTacos;
}
public void getRamen(){
return ramPizza;
}
public void getPepper(){
return belPepper;
}
public void getSteak(){
return musSteak;
}
public void getTuna(){
return tunSup;
}
}
OK, trying this now. Still not quite right....
The instructions were:
A class named orderEntry should also be created with the appropriate
constructor, accessor and mutator methods. As the user is entering the
items they wish to order, these items should be placed into a separate
array as they are ordered. Once the user is done entering items, the
program should use the array to output all items that were ordered to
the screen, with their prices.
This is not a solution i would recommend, but for the sake of learning how to use methods:
just put it in another class and call the method from there. Give the methods the parameters needed.
public class whileMethod(String quit, double listTime, double listMax, Scanner input, double priceAdd, ArrayList<String> buyItemList, ) {
while (quit != "done" || listTime <= listMax)
{
System.out.println("Please enter item " + listTime + " :");
itemEntry = input.nextInt();
if (itemEntry == 1){
priceAdd = spagPrice;
buyitemList.add("Spaghetti Tacos");
}
else if (itemEntry == 2){
priceAdd = ramenPrice;
buyitemList.add("Ramen Pizza");
}
else if (itemEntry == 3){
priceAdd = pepperPrice;
buyitemList.add("Stuffed Bell Pepper");
}
else if (itemEntry == 4){
priceAdd = steakPrice;
buyitemList.add("Mushroom Steak");
}
else if (itemEntry == 5){
priceAdd = tunaPrice;
buyitemList.add("Tuna Suprise");
}
else {
priceAdd = 0;
}
buyList.add((int) priceAdd);
listTime += listTime;
}
From here u can call the method in the class:
whileMethod(and all the attributtes needed)

How to print out information from data used in arrays?

My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?
Code:
package SMKTeamStandings;
import java.util.Scanner;
public class SMKTeamStandings {
public static Scanner in = new Scanner(System.in);
public static int number(int max, int min) {
int teamchoice = 0;
for (boolean valid = false; valid == false;) {
teamchoice = in.nextInt();
if (teamchoice >= min && teamchoice <= max) {
valid = true;
} else {
System.out.println("Please enter a different value.");
}
}
return teamchoice;
}
public static boolean finished(boolean[] completedArray) {
int i = 0;
boolean done;
for (done = true; done == true;) {
if (completedArray[i++] == false) {
done = false;
}
}
return done;
}
public static void main(String[] args) {
int teamChoice = 0, gamesNum;
String[] sportteams = {"Basketball", "Football",
"Hockey", "Rugby",
"Soccer", "Volleyball"};
boolean[] completed = new boolean[sportteams.length];
int[][] Outcome = new int[64][sportteams.length];
for (boolean done = false; done == false;) {
for (int i = 0; i < sportteams.length; i++) {
System.out.print(i + 1 + " - " + sportteams[i]);
if (completed[i] == true) {
System.out.println(" - Finished");
} else {
System.out.println();
}
}
System.out.print("\nChoose a team from the list above:");
teamChoice = number(6, 1);
teamChoice--;
System.out.print("\nHow many games total did the " + sportteams[teamChoice]
+ " team play this season?: ");
gamesNum = in.nextInt();
System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
"1 - Win",
"2 - Tie",
"3 - Loss");
for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
System.out.print("\nEnter the outcome for game "
+ (wintieloss + 1) + ": ");
Outcome[wintieloss][teamChoice] = number(3, 1);
}
System.out.println("\n");
completed[teamChoice] = true;
done = finished(completed);
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.
for(int team = 0; team < sportteams.length; team++) { // for each team
System.out.println((team + 1) + " - " + sportteams[team]); // output the team
int game = 0; // index of the current game
while(Outcome[game][team] != 0) { // while there is data
System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
game++; // increment the index
}
System.out.println("Total games: " + game); // print the last index == total number of games
System.out.println();
}

Keeping a total score in Java hangman game

import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more code.

Categories