Store array at runtime - java

I am an absolute beginner in programming and am facing my first big tasks.
The task is a warehouse management. All newly entered boxes should be stored in an array at runtime.
The problem is that I can create a new chest, but it will be overwritten or not saved.
My idea is that I call the run function every time an entry was successful.
import java.util.Arrays;
public class lager {
static int parser (String value) {
if (value == null) {
return -1;
} else {
return Integer.parseInt(value);
}
}
static void run (int[][]chests, int chestAmount, int maxStorage) {
//Fallunterscheidung
String option = JOptionPane.showInputDialog("What do you want to do (Type: 1-5)? \n" +
"\n" +
" 1 - Create chest \n" +
" 2 - Delete chest \n" +
" 3 - Change chest \n" +
" 4 - Show chest \n" +
" 5 - Show all");
System.out.println(chestAmount);
int optionParsed = parser(option);
if (optionParsed > 5){
System.out.println("Input incorrect or process aborted!");
run(chests, chestAmount, maxStorage);
} else if (optionParsed < 1){
System.out.println("Input incorrect or process aborted!");
return;
} else {
if (optionParsed == 1){
boolean response = create(chests, chestAmount, maxStorage);
if (!response){
System.out.println("Input incorrect or process aborted!");
} else {
System.out.println("Process successfully completed!");
}
} else if (optionParsed == 2){
boolean response = delete(chests, chestAmount, maxStorage);
if (response){
System.out.println("Input incorrect or process aborted!");
} else {
System.out.println("Process successfully completed!");
}
}
}
run(chests, chestAmount, maxStorage);
}
static boolean create (int[][]chests, int chestAmount, int maxStorage){
if (chestAmount > maxStorage - 1) {
System.out.println("The storage is already full!");
return false;
} else {
int length = Integer.parseInt(JOptionPane.showInputDialog("How long is the chest in centimeters? (e.g. 115)"));
int width = Integer.parseInt(JOptionPane.showInputDialog("How wide is the chest in centimeters? (e.g. 115)"));
int height = Integer.parseInt(JOptionPane.showInputDialog("How high is the chest in centimeters? (e.g. 115)"));
//THIS IS PROBABLY WHERE THE ERROR OCCURS
chests[chestAmount] = new int[]{length, width, height};
chestAmount++; //Count up help variable
System.out.println(chestAmount);
System.out.println("Stock " + chestAmount + " / " + maxStorage);
System.out.println(Arrays.toString(chests[chestAmount - 1]));
return true;
}
}
static boolean delete (int[][]chests, int chestAmount, int maxStorage){
String removeChest = JOptionPane.showInputDialog("Which chest do you want to delete? 1 - " + chestAmount);
int removeChestParsed = parser(removeChest);
if (removeChestParsed > chestAmount || removeChestParsed < 1){
System.out.println("Chest not available.");
return false;
} else {
chestAmount--;
chests[removeChestParsed - 1] = chests[chestAmount];
chests[chestAmount] = null;
return true;
}
}
public static void main(String[] args) {
int maxStorage = 75;
int[][] chests = new int[maxStorage][3]; //TODO: Wert 75 dynamisch anpassbar -- Fertig
//Hilfsvariable
int chestAmount = 0;
run(chests, chestAmount, maxStorage);
}
}

The problem was fixed. After I defined the variable chestAmount in the class Lager and not in the main method, everything went as desired.

Related

Setting a value for one of my instance variables isn't working

I'm trying to write a program that essentially evaluates a 5 card poker hand that is user-generated. One part of the program is that users can choose one variable to randomly change. The issue lies with setting a value for one of my instance variables, right now, my setCards, getCards, and changeOne methods are:
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
getCards();
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
changes++;
}
In a separate class, I'm using:
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
I'm not sure why but whenever I try to use the changeOne method, keeps giving me the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 3, length 0
Which I assume is because it takes cards to be an empty string. I'm not sure what is happening and why it isn't getting the proper value of cards, help would be greatly appreciated.
Entire code:
First class:
import java.util.Scanner;
public class Assignment4{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
FiveCards myCards = new FiveCards();
int position;
String choice, cards;
char charChoice;
final char NEW = 'A';
final char CHANGE = 'B';
final char DISPLAY = 'C';
final char QUIT = 'Q';
do {
System.out.println("Choose (A: Make New Cards), (B: Change One Card), (C: Display Data), or (Q: Quit)");
choice = in.next();
charChoice = choice.toUpperCase().charAt(0);
switch(charChoice) {
case NEW:
System.out.println("*** Make New FiveCards ***");
System.out.println("Type five letters without space: ");
in.next();
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case CHANGE:
System.out.println("*** Change One Card ***");
System.out.println("Type one position to change (0-4): ");
position = in.nextInt();
myCards.changeOne(position);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case DISPLAY:
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case QUIT:
System.out.println("*** End of Program ***");
break;
default:
System.out.println("Invalid input. Try Again");
break;
}
}while(charChoice!=QUIT);
}
}
Second class is:
public class FiveCards {
private String cards, history;
private int score, changes, counter;
private String allCards = "1234567890JQK";
private char randomChar;
public FiveCards() {
}
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
System.out.println(cards);
changes++;
}
public void calculateScore() {
for(int i = 0; i<cards.length(); i++) {
for(int j = 0; j<cards.length(); j++) {
if((cards.charAt(i) == cards.charAt(j)) && (i != j)) {
counter++;
}
}
}
if(counter == 2) {
score = 1;
}
else if(counter == 4) {
score = 2;
}
else if(counter == 6) {
score = 3;
}
else if(counter == 8) {
score = 4;
}
else {
score = 0;
}
}
public String displayData() {
calculateScore();
history = history + cards + score + changes;
if(cards.length()<=1) {
return cards + " " + score + " " + changes;
}
else {
return "Empty" + " " + score + " " + changes;
}
}
}
First problem:
allCards.charAt(...). In the setCards you assign string to cards, but here you pick character from allCards. What is content of allCards? When it is assigned? I it assigned at all? (your code doesn't show this).
And the second problem:
Math.random()*cards.length()
Valid indexes of characters in the String are from 0 to length() - 1 inclusive, but the way you generate random index, you can give you index from 0 to length() inclusive. Change it to the Math.random()*(cards.length() - 1).

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

Adding a loop to my game

I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.

How to pass information with a get properly in java

I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
If you have a funftion in the class, that exhibits the var, then it should be fine. You need to make PressureInput a object, with PressureInput varnamePI = new PressureInput();
Then, access the var through varnamePI.sysAvrg=0; or so...

Why doesnt the colonySize variable change?

In this program, there is a 20% chance the amoeba colony will get sick if it has vitamins, and 25% it will get sick if it does not. Does the getSick() method represent this correctly?
Also, no matter how many times I run the program, the colony never gets sick, and none of them die. which I find very peculiar. What do you suggest I change? Thanks for your help.
public class AmoebaColony {
//instance variables
private String name;
private String caretakerName;
private long colonySize;
private boolean isVitamin;
private int successfulBreeds = 0;
private boolean sickness;
//AmoebaColony constructor
public AmoebaColony(String name, String caretakerName, long colonySize,
boolean isVitamin) {
this.name = name;
this.caretakerName = caretakerName;
this.colonySize = colonySize;
this.isVitamin = isVitamin;
}
public void feed()
{
colonySize *= 2;
successfulBreeds++;
}
public void getSick()
{
Random n = new Random();
if (isVitamin)
{
int c1 = n.nextInt(19);
if (c1 == 0)
{ sickness = true; }
else
{ sickness = false; }
}
else if (isVitamin == false)
{
int c2 = n.nextInt(24);
if (c2 == 0)
{ sickness = true; }
else
{ sickness = false; }
}
}
public String isSick()
{
if (sickness == true)
{
return "did";
}
else
{
return " did not ";
}
}
public void die() {
if (sickness == true)
{
colonySize = colonySize - (colonySize/10);
}
else if (sickness == false)
colonySize = colonySize;
}
//returns how many times it successfully bred
public int getSuccess()
{
return successfulBreeds;
}
//returns size of colony
public long getSize()
{
return colonySize;
}
}
public class AmoebaColonyTester {
public static void main(String[] args) {
//Get variables
String name = JOptionPane.showInputDialog(null, "What will be the name of the colony?");
String caretakerName = JOptionPane.showInputDialog(null, "What is the name of the caretaker of the colony?");
long colonySize = Integer.parseInt(JOptionPane.showInputDialog(null, "Welcome, " + caretakerName + "! What is the starting size of the colony?"));
int feedTimes = Integer.parseInt(JOptionPane.showInputDialog(null, "How many times do you want to feed the colony?"));
int breedTimes = Integer.parseInt(JOptionPane.showInputDialog(null, "How many times do you want your colony to breed?"));
int vitamin = JOptionPane.showConfirmDialog(null,"Do you want to give vitamins to your colony?", "Please select",
JOptionPane.YES_NO_OPTION);
boolean isVitamin;
if (vitamin == 1)
isVitamin = true;
else
isVitamin = false;
int feedCounter = 0;
//create colony object
AmoebaColony amoeba = new AmoebaColony(name, caretakerName, colonySize, isVitamin);
//feed the colony so it can breed
for(int x = 1; x <= feedTimes; x++)
{
if (x <= breedTimes)
{
amoeba.feed();
feedCounter++;
}
}
//get maximum colony size
long finalColony = amoeba.getSize();
;
//amoeba get sick :/
amoeba.getSick();
amoeba.die();
System.out.println(amoeba.getSize());
//display info on the screen
JOptionPane.showMessageDialog(null, "The colony name is " + name + "\nThe caretaker name is " + caretakerName +
"\nThe starting colony size was " + colonySize + "\nThey were fed " + feedCounter
+ " times \nRequested number of times to breed: " + breedTimes
+ " \nThey successfully bred " + amoeba.getSuccess() + " times\nThe colony " + amoeba.isSick() +
" get sick and "+ (finalColony - amoeba.getSize()) + " died \n"
+ " The final size of the colony is " + amoeba.getSize());
}
}
A 20% chance of something means that 1 out of 5 times it is supposed to be true. But you actually calculate the sickness as 1 in 19 times (nextInt(19) gives you the numbers between 0 and 18 inclusive, randomly).
So for 20% you need to use n.getInt(5) and for 25% chance you need to use n.getInt(4).
Other than that, just run it enough times. I don't suppose you ran it enough times for a 1 in 19 chance, given that your program runs you through several dialogs every time you run it. But I ran it and got several "did".

Categories