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

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)

Related

Trading Card Deck Generatior

I'm trying to make a random deck generator for HearthStone and something is wrong with card[] array. It gives me null pointer exception and the first time it occurs is in the readFile() method, the debugger says the problem is with this line (well it starts there anyway) card[a].setName(name);. I know that it isn't the String variable "name" because I can reference that in a System.out.print().
p.s. my compiler is netbeans IDE 8.0.2
HearthStoneDeckMaker
package hearthstone.deck.maker;
import java.io.*;
import java.lang.*;
import java.util.*;
public class HearthStoneDeckMaker {
static createfile save = new createfile();
public static double manaAVG = 5;
public static int maxTaunt = 30;
public static int maxSpell = 30;
public static int maxMinions = 30;
public static int minTaunt = 0;
public static int minSpell = 0;
public static int minMinions = 0;
static Scanner input = new Scanner(System.in);
public static int numberOfCards = 0;
static Card[] card = new Card[9999];
static int i;
static int usedMinions = 0;
static int usedSpells = 0;
static int usedTaunts = 0;
static String cls = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
private static Scanner x;
public static void addcards(){
for (i = numberOfCards; i <= numberOfCards; i++) {
boolean DoneWithCard = false;
while(DoneWithCard == false){
card[i] = new Card();
System.out.print("Name of Card >> ");
card[i].setName(input.nextLine());
System.out.print(card[i].getName()+"'s Class >> ");
card[i].setCharacter(input.nextLine());
boolean isValid = false;
String message = "";
String cardtype = "";
while(isValid == false){
System.out.println(message +"Is " + card[i].getName() + " a minion or a spell >>");
if(input.nextLine().equalsIgnoreCase("minion")){
card[i].setIsMinion(true);
isValid = true;
cardtype = "minion";
}
else if(input.nextLine().equalsIgnoreCase("spell")){
card[i].setIsSpell(true);
isValid = true;
cardtype = "spell";
}
else{
message = "<INVALID ENTRY TRY AGAIN> ";
}
}
String hastaunt = "";
System.out.print("Does "+ card[i].getName() + " have Taunt (Y/N) >>");
if(input.nextLine().equalsIgnoreCase("Y")) {
card[i].setHasTaunt(true);
hastaunt = "Does";
}
else{
card[i].setHasTaunt(false);
hastaunt = "Does not";
}
System.out.print("What is " +card[i].getName() +"'s mana cost >>");
card[i].setMana(input.nextInt());
if(card[i].getIsSpell() == false){
System.out.print("What is " +card[i].getName() +"'s health >>");
card[i].setHealth(input.nextInt());
}
else{
card[i].setHealth(0);
}
System.out.print("What is " +card[i].getName() +"'s damage >>");
card[i].setDamage(input.nextInt());
System.out.println("would you like to add a desription (Y/N)");
String ADesc = input.nextLine();
if(input.nextLine().equalsIgnoreCase("y")){
System.out.println("What is "+ card[i].getName() + "'s description >>");
card[i].setDescription(input.nextLine());
}
else{
System.out.println("Alright next");
}
System.out.println(card[i].getName() + " is a(n) " + cardtype + " with " +card[i].getDamage() + ""
+ "/" + card[i].getHealth() + "\nand " + hastaunt + " have taunt");
System.out.print("is this correct? (Y/N)");
if(input.nextLine().equalsIgnoreCase("Y")){
DoneWithCard = true;
}
else{
DoneWithCard = false;
}
}
System.out.print("Do you want to enter another card? (Y/N)");
if(input.nextLine().equalsIgnoreCase("n")){
numberOfCards = i+1;
save.OpenFile();
save.addRecords();
save.closeFile();
numberOfCards++;
parameters();
}
else{
numberOfCards++;
}
}
}
public static void setup(){
int counter = 0;
boolean add = false;
System.out.println("Current Cards >>");
openFile();
}
public static void openFile(){
try{
x = new Scanner(new File("HearthCards.txt"));
}
catch(Exception e){
System.out.println("Load Failure");
}
readFile();
}
public static void readFile(){
Card[] cardie = new Card[numberOfCards];
while(x.hasNext()){
numberOfCards++;
int a = 0;
String name = x.next();
String Character= x.next();
int Health = Integer.parseInt(x.next());
int Damage = Integer.parseInt(x.next());
int Mana = Integer.parseInt(x.next());
int TimesUsed = Integer.parseInt(x.next());
boolean hasTaunt = Boolean.parseBoolean(x.next());
boolean isMinion = Boolean.parseBoolean(x.next());
boolean isSpell = Boolean.parseBoolean(x.next());
card[a].setName(name);
card[a].setCharacter(Character);
card[a].setHealth(Health);
card[a].setDamage(Damage);
card[a].setMana(Mana);
card[a].setTimesUsed(0);
card[a].setHasTaunt(hasTaunt);
card[a].setIsMinion(isMinion);
card[a].setIsSpell(isSpell);
a++;
}
closeFile();
}
public static void closeFile(){
x.close();
setupcont();
}
public static void setupcont(){
for (int j = 0; j <= 30; j++) {
String type = "oof";
String taunts = "oofer";
if(card[j].getIsMinion() == true){
type = "minion";
}
else if(card[j].getIsSpell() == true){
type = "spell";
}
if(card[j].getHasTaunt() == true){
taunts = "has";
}
else{
taunts = "doesnt have";
}
System.out.println(cls);
System.out.println(card[j].getName() + " >> " + card[j].getName() + " is a " + type + " that "+ taunts + " taunt");
}
System.out.print("would you like to add any new Cards (Y/N)");
if(input.nextLine().equalsIgnoreCase("y")){
addcards();
}
else{
makedeck();
}
}
public static void parameters(){
System.out.print("Would you like to use default max and mins, or custom >> ");
if(input.nextLine().equalsIgnoreCase("default")){
makedeck();
}
else{
System.out.print("What should the mana average be?");
manaAVG = input.nextInt();
System.out.println("What is the max taunt minions ?");
maxTaunt = input.nextInt();
System.out.print("What is max minions (1-30) >> ");
maxMinions = input.nextInt();
System.out.print("What is the max spells (1-30) >> ");
maxSpell = input.nextInt();
if(maxMinions + maxSpell < 30){
System.out.println("<INVALID ENTRY TRY AGAIN> What is the max spells (1-30 >> ");
maxSpell = input.nextInt();
}
}
}
public static void makedeck(){
Card deck[] = new Card[30];
for(int a = 0; a <= 30; a++){
Random ran = new Random(i);
int rand = ran.nextInt();
if(card[rand].getTimesUsed() <= 2){
deck[a] = card[rand];
String hastaunt = "does not";
if(card[rand].getHasTaunt() == true){
hastaunt = "does";
usedTaunts++;
}
String cardtype = "";
if(card[rand].getIsMinion() == true && usedMinions < maxMinions){
usedMinions++;
cardtype = "minion";
}
System.out.println(deck[rand].getName() + " is a(n) " + cardtype + " with " +deck[rand].getDamage() + ""
+ "/" + deck[rand].getHealth() + "\nand " + hastaunt + " have taunt");
}
}
boolean isDone = false;
Random ran = new Random(i);
int rand = ran.nextInt();
boolean minMinDone = false;
boolean maxMinDone = false;
boolean minSpellDone = false;
boolean maxSpellDone = false;
boolean minTauntDone = false;
boolean maxTauntDone = false;
boolean correctClass = false;
System.out.println("What Class would you like to use");
String usedClass = input.nextLine();
while(isDone == false){
Random R = new Random(i);
int Ran = R.nextInt();
if(usedMinions < minMinions){
Ran = R.nextInt();
if(deck[Ran].getIsMinion() == false){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
minMinDone = true;
}
if(usedMinions > maxMinions){
Ran = R.nextInt();
if(deck[Ran].getIsMinion() == true){
int random = R.nextInt();
deck[Ran] = card[random];
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
maxMinDone = true;
}
if(usedSpells < minSpell){
Ran = R.nextInt();
if(deck[Ran].getIsSpell() == false){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
minSpellDone = true;
}
if(usedSpells > maxSpell){
Ran = R.nextInt();
if(deck[Ran].getIsMinion() == true){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
maxSpellDone = true;
}
if(usedTaunts < minTaunt){
Ran = R.nextInt();
if(deck[Ran].getHasTaunt() == false){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
card[Ran].setTimesUsed(card[Ran].getTimesUsed() + 1);
}
}
}
else{
minTauntDone = true;
}
if(usedTaunts > maxTaunt){
Ran = R.nextInt();
if(deck[Ran].getHasTaunt() == true){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
maxTauntDone = true;
}
correctClass = false;
for (int j = 0; j <= 30; j++) {
while(!deck[j].getCharacter().equalsIgnoreCase(usedClass)){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2 && card[random].getCharacter().equalsIgnoreCase(usedClass)){
deck[j] = card[random];
}
}
}
correctClass = true;
if(minMinDone == true && maxMinDone == true && minSpellDone == true && maxSpellDone == true && minTauntDone == true && maxTauntDone == true && correctClass == true){
isDone = true;
}
else{
isDone = false;
}
}
for (int j = 0; j <= 30; j++) {
String type = "oof";
String taunts = "oofer";
if(deck[j].getIsMinion() == true){
type = "minion";
}
else if(deck[j].getIsSpell() == true){
type = "spell";
}
if(deck[j].getHasTaunt() == true){
taunts = "has";
}
else{
taunts = "doesnt have";
}
System.out.println(cls);
if(!deck[j].getDescription().equals("")){
System.out.println(deck[j].getName() + " >> " + deck[j].getName() + " is a " + type + " that "+ taunts + " taunt >>> \n\t" + deck[j].getDescription());
}
else{
System.out.println(deck[j].getName() + " >> " + deck[j].getName() + " is a " + type + " that "+ taunts + " taunt");
}
}
}
public static void main(String[] args) {
setup();
}
}
Card
package hearthstone.deck.maker;
public class Card {
private String Name;
private String Class;
private boolean HasTaunt;
private int Mana;
private int Damage;
private int Health;
private boolean isMinion = false;
private boolean isSpell = false;
private boolean isElemental = false;
private int TimesUsed = 0;
private String Description = " no description ";
//Omitted getters and setters
public Card(){
}
}
createFile
package hearthstone.deck.maker;
import java.io.*;
import java.lang.*;
import java.util.*;
public class createfile {
int numCards = HearthStoneDeckMaker.numberOfCards;
private Formatter x;
public void OpenFile(){
try{
x = new Formatter("HearthCards.txt");
}
catch(Exception e){
System.out.println("Save Failed");
}
}
public void addRecords(){
for (int j = 0; j < HearthStoneDeckMaker.numberOfCards; j++) {
x.format("%s %s %x %x %x %x %b %b %b %n", HearthStoneDeckMaker.card[j].getName(), HearthStoneDeckMaker.card[j].getCharacter(), HearthStoneDeckMaker.card[j].getHealth(), HearthStoneDeckMaker.card[j].getDamage(), HearthStoneDeckMaker.card[j].getMana(), HearthStoneDeckMaker.card[j].getTimesUsed(), HearthStoneDeckMaker.card[j].getHasTaunt(), HearthStoneDeckMaker.card[j].getIsMinion(), HearthStoneDeckMaker.card[j].getIsSpell());
}
}
public void closeFile(){
x.close();
}
}

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.

In my shop project, my method "checkout" runs several times before stopping when it should only run once when called upon form direct

import java.util.*;
public class Shop {
protected String name;
protected double price;
protected int amount;
protected double discountAmt;
protected double discount;
protected boolean setupComp = false;
protected boolean buyComp = false;
public static void main(String[] args) {
Shop direct = new Shop();
direct.direct();
}
public void direct(){
println("This program supports 4 functions:");
println("\t*Setup Shop");
println("\t*Buy Items");
println("\t*List of items purchased");
println("\t*Checkout");
print("Please choose the function you want: ");
Scanner input = new Scanner(System.in);
int func = input.nextInt();
if (func == 1){
setup();
}
if (func == 2){
buy();
}
if (func == 3){
listItems();
}
1. Everything seems to run fine up to this point, then checkout repeatedly runs a couple of times.
2. I don't know if the problem is how I'm calling upon checkout() or if it is within checkout itself:
if (func == 4);{
checkout();
}
if (func >= 5){
println("Error: do not know " + func);
direct();
}
}
public Shop(){
name = "";
price = 0;
amount = 0;
}
public Shop[] product;
private static void println(String string) {
System.out.println(string);
}
private static void print(String string) {
System.out.print(string);
}
public void setup(){
print("Please enter the number of items: ");
Scanner input = new Scanner(System.in);
int max = input.nextInt();
product = new Shop[max];
for (int i = 0; i < max; i++){
product[i] = new Shop();
print("Enter name of product " + i + ": ");
product[i].setName(name = input.next());
print("Enter the price of the product: ");
product[i].setPrice(price = input.nextDouble());
}
print("Please enter the amount to qualify for discount: ");
this.discountAmt = input.nextDouble();
print("Please enter the discount rate(0.1 for 10%): ");
this.discount = input.nextDouble();
setupComp = true;
direct();
}
public void buy(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true){
Scanner input = new Scanner(System.in);
for (int i = 0; i < product.length; i++){
print("Enter the amount of " + product[i].name + ": ");
product[i].setAmount(amount = input.nextInt());
buyComp = true;
}
direct();
}
}
public void listItems(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true && buyComp == false){
println("Try again: You have not bought anything");
direct();
}
for (int i = 0; i < product.length; i++){
if (product[i].amount == 0)
continue;
else println(product[i].amount + " count of " + product[i].name + " # " + product[i].price
+ " = " + (product[i].amount * product[i].price));
}
direct();
}
public void checkout(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true && buyComp == false){
println("Try again: You have not bought anything");
direct();
}
double subtotal = 0;
double total = 0;
double disc = 0;
for (int i = 0; i < product.length; i++){
subtotal += (product[i].amount * product[i].price);
}
if (subtotal >= discountAmt){
disc =(discount * subtotal);
total = subtotal - (disc);
}
3. These printline statements are what are running repeatedly. My method not these println statements are contained within a loop so I don't know what could be causing this issue.:
println("Thank you for coming!");
println("Sub Total: $" + subtotal);
println("-Discount: $" + (disc));
println("total\t: $" + total);
}
public void setName(String name){
this.name = name;
}
private void setPrice(double price) {
this.price = price;
}
private void setAmount(int amount) {
this.amount = amount;
}
}
Actually the if statement is an empty control flow. The checkout method is not getting called as intended by you. Please remove the first semicolon.
if (func == 4);{
checkout();
}

Java - Returning constructor method with array

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;
}

Loop back the beginning of the code

So my code works completely; the only thing now is a very simple problem that I cannot figure out. I have to make the program loop back to the beginning if the user type restart and I cannot think how to that.
import java.util.Scanner;
public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
}
}
there are two solutions.
1. wrap your code in "while" loop. but it will be difficult for you because your code is so messy :(
change the code as follow
import java.util.Scanner; public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
main();
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
} }

Categories