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();
}
Related
I'm trying to write a code that creates a match fixture of soccer league
Like;
`
Half round of the season
week
Team1 - Team2
Team3 - Team4
week
Team1 - Team3
Team2 - Team4
week
Team1 - Team4
Team2- Team3
...
And 2nd half round of the season right opposite
`
I'll get the 2nd half round from the homeT and awayT LinkedLists but before that for 1st half round i've got a problem with shuffle, sometimes getting right results of all weeks but sometimes it stuck before calculating all weeks like here.here calculated succesfully
Here's my code:
public void run() {
System.out.print("Enter team count: ");
Scanner scanner = new Scanner(System.in);
int teamCount = scanner.nextInt();
LinkedList<String> teams = new LinkedList<>();
for (int i = 0; i < teamCount; i++) {
System.out.print("Enter team name: ");
teams.add(scanner.next());
}
for (String i : teams) {
System.out.print(i + " ");
}
LinkedList<String> homeT = new LinkedList<>();
LinkedList<String> awayT = new LinkedList<>();
LinkedList<String> cloneList = new LinkedList<>();
int counter = 1;
boolean afterFirstWeek = false;
boolean t = false;
for (int i = 0; i < teamCount - 1; i++) {
String homeTeam;
String awayTeam;
int matchCount = 0;
String weeksMatches = "";
cloneList = (LinkedList<String>) teams.clone(); // refresh teams each week
while (matchCount < teamCount / 2) {
boolean isContinue = true;
if (afterFirstWeek) {
Collections.shuffle(cloneList);
homeTeam = cloneList.peek();
cloneList.removeFirst();
awayTeam = cloneList.peek();
cloneList.removeFirst();
for (int j = 0; j < homeT.size(); j++) {
if ((homeTeam.equals(homeT.get(j)) && awayTeam.equals(awayT.get(j))) || (awayTeam.equals(awayT.get(j)) && homeTeam.equals(homeT.get(j)))) {
isContinue = false;
}
if (homeTeam.equals(awayT.get(j)) && awayTeam.equals(homeT.get(j))) {
isContinue = false;
}
}
if (isContinue) {
homeT.add(homeTeam);
awayT.add(awayTeam);
weeksMatches += homeTeam + " vs " + awayTeam + "\n";
matchCount++;
counter++;
} else {
Collections.shuffle(cloneList);
cloneList.add(homeTeam);
cloneList.add(awayTeam);
Collections.shuffle(cloneList);
}
} else {
Collections.shuffle(cloneList);
homeTeam = cloneList.peek();
cloneList.removeFirst();
awayTeam = cloneList.peek();
cloneList.removeFirst();
homeT.add(homeTeam);
awayT.add(awayTeam);
weeksMatches += homeTeam + " vs " + awayTeam + "\n";
matchCount++;
counter++;
}
if (!afterFirstWeek && matchCount == teamCount / 2)
afterFirstWeek = true;
}
System.out.println();
System.out.println(i + 1 + ". week matches");
System.out.println(weeksMatches);
}
for (int i = 0; i < counter; i++) {
}
}
I get team count from console then put the team names into team LinkedList, then fixture matches 1st half round of the season, firstly calculate 1st week then give conditions to calculate next weeks. And probably this for loop's first if condition has issue. It calculates correct sometimes, and sometimes doesn't.
for (int j = 0; j < homeT.size(); j++) {
if ((homeTeam.equals(homeT.get(j)) && awayTeam.equals(awayT.get(j))) || (awayTeam.equals(awayT.get(j)) && homeTeam.equals(homeT.get(j)))) {
isContinue = false;
}
if (homeTeam.equals(awayT.get(j)) && awayTeam.equals(homeT.get(j))) {
isContinue = false;
}
}
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.
I'm doing a coin toss program, and am trying to determine the longest possible run of heads or tails that were tossed. I already have code for determining if toss is heads or tails, but now need to count longest possible run. Help! Here's my code for the basic program.
public static void coin_toss(char [] toss)
{
int s = 0;
try
{
for (s = 0; s <= toss.length; s++)
{
double flip;
flip = (double)(Math.random());
if (flip < 0.5)
toss[s] = 't';
else
toss[s] = 'h';
}//end of for loop to load array
}
catch (ArrayIndexOutOfBoundsException errorMessage)
{
System.out.println("\nSubscript out of bounds");
System.out.println("Subscript went past the limit of " + toss.length);
System.out.println("Last value of subscript was --> " + s);
System.out.println("-------------------------------------------------");
System.out.println(errorMessage);
System.out.println("-------------------------------------------------");
}
}//end of toss coin
public static double percent_heads (char [] toss)
{
double percent_h;
int heads = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 'h')
heads = heads + 1;
}
System.out.println("There were " + heads + " heads results");
percent_h = (double)heads / toss.length;
return (percent_h);
}//end of heads percentage function
public static double percent_tails (char [] toss)
{
double percent_t;
int tails = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 't')
tails = tails + 1;
}
System.out.println("There were " + tails + " tails results");
percent_t = (double)tails / toss.length;
return (percent_t);
}//end of tails percentage function
public static void main(String [] args)
{
int num_toss = 0;
double heads, tails;
double percent_t, percent_h;
DecimalFormat percent = new DecimalFormat ("#0.00%");
System.out.print("How many tosses would you like? --> ");
num_toss = GetInput.readLineInt();
char [] toss = new char[num_toss];
System.out.println("You chose " + toss.length + " tosses");
coin_toss(toss);
heads = percent_heads(toss);
tails = percent_tails(toss);
System.out.println("The percentage of heads was --> " + percent.format(heads));
System.out.println("The percentage of tails was --> " + percent.format(tails));
longest_toss(toss);
java.util.Date today = new java.util.Date();
System.out.println("\nProgram terminated at " + today);
System.exit(0);
}//end of main method
}//end of class
There is a method I came up with.
public static void longest_toss(char[] toss){
int longestrun = 0;
int curlongestrun = 0;
char prevrun = toss[0];
for (int s = 1; s < toss.length; s++)
{
if (toss[s] == prevrun) {
curlongestrun++;
}else {
curlongestrun=0;
}
if(curlongestrun>longestrun){
longestrun = curlongestrun;
}
prevrun = toss[s];
}
System.out.println("Longest run is : " + longestrun + " Coin side : " + prevrun);
}
You can get maximum index of the array toss[] as Integer.MAX_VALUE - 8
Here it is less by 8 because, in the source code of java.util.ArrayList class, it is clearly mentioned that, MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 provided you have sufficient memory to hold the content of array with this much data.
int getLongestHeads(char [] toss){
int longestHeads = 0;
for(char c : toss)
{
if(longestHeads > 0 && c == 'h'){
longestHeads = longestHeads + 1;
}
else{
longestHeads = 0;
}
if(c == 'h' && longestHeads == 0) {
longestHeads = 1;
}
}
return longestHeads;
}
I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!
This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);