Java Soccer Fixture Algorithm - java

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

Related

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

Replace a int or long with a string in for loop?

I needed to print the Fibonacci Sequence up to 50 numbers, which I eventually figured out, but I also need to replace certain numbers that are divisible by some number with certain words. I kind of figured this out. I got the words to come up, but I could not replace the number. I tried using String.valueOf and replaceAll, but the number still keeps showing up. I left that part of the code in comments because it was not working. I am going to post my code below:
public static void main(String[] args) {
long n = 50;
System.out.print("1 ");
long x = 0;
long y = 1;
String mult3 = "cheese";
String mult5 = "cake";
String mult7 = "factory";
String mult2 = "blah";
for (long i = 1; i < n; i++) {
long forSum = x + y;
x = y;
y = forSum;
if(forSum==89){
System.out.println("");
}
if(forSum==10946){
System.out.println("");
}
if(forSum==1346269){
System.out.println("");
}
if(forSum==165580141){
System.out.println("");
}
if(forSum %3 == 0){
//String mult3 = String.valueOf(forSum);
//String mult4 = "cheese";
//String mult3cheese = mult3.replaceAll(mult3, mult4);
//System.out.print(mult3cheese);
System.out.print(mult3);
}
if(forSum %5 == 0){
System.out.print(mult5);
}
if(forSum %7 == 0){
System.out.print(mult7);
}
if(forSum %2 == 0){
System.out.print(mult2);
}
System.out.print(forSum + " ");
}//for loop for forSum
}//public static void main
You need to place some "continue" statements to skip past the line that prints the number, if you have matched a "replace the number" condition:
public static void main(String[] args) {
long n = 50;
System.out.print("1 ");
long x = 0;
long y = 1;
String mult3 = "cheese";
String mult5 = "cake";
String mult7 = "factory";
String mult2 = "blah";
for (long i = 1; i < n; i++) {
long forSum = x + y;
x = y;
y = forSum;
if(forSum==89){
continue;
}
if(forSum==10946){
continue;
}
if(forSum==1346269){
continue;
}
if(forSum==165580141){
continue;
}
if(forSum %3 == 0){
//String mult3 = String.valueOf(forSum);
//String mult4 = "cheese";
//String mult3cheese = mult3.replaceAll(mult3, mult4);
//System.out.print(mult3cheese);
System.out.print(mult3 + " ");
continue
}
if(forSum %5 == 0){
System.out.print(mult5 + " ");
continue;
}
if(forSum %7 == 0){
System.out.print(mult7 + " ");
continue;
}
if(forSum %2 == 0){
System.out.print(mult2 + " ");
continue;
}
System.out.print(forSum + " ");
}//for loop for forSum
}//public static void main
"continue" means "skip the rest of the code inside this loop and do the next iteration of the loop"

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.

Pulling multiple elements out of an array and labeling them specifically

I need to program an array that functions as horses in a race. Everytime the user presses enter the horses will "run" or the array will add random numbers to them and update their position. The console is printing their position after every button press. I need to label the 1st 2nd and 3rd horses after the race is over (when the horses hit 15). I cannot figure out how to do this.
Right now I am searching through the array and if an element of the array is greater than or equal to 15 I have it set to print the first place horse. How do I make it so that it will print the 2nd and 3rd place as the next highest positions (ex. 1st = 15, 2nd = 13, 3rd = 12)?
Also, it appears that my program will not stop. How do I get it to stop after 15 or higher is reached? Thank you!
import java.util.*;
public class HorseRace2{
public static void main(String[ ] arg){
Scanner reader = new Scanner(System.in);
int range = 3;
int win = 15;
final int SIZE = 3;
Random ran = new Random( );
boolean winner = false;
int[ ] arrRan = new int[SIZE];
System.out.print("Off to the races! Press enter to make the horses run.");
String readString = reader.nextLine();
while(readString!=null){
System.out.print(readString);
if(readString.equals("")){
for(int i = 0; i<arrRan.length; i++){
arrRan[i] = arrRan[i] + (ran.nextInt(3) + 1);
System.out.println("Horse " + (i+1) + ":" + arrRan[i]);
}
}//end if
if(reader.hasNextLine()){
readString = reader.nextLine();
System.out.println("Please press enter to make the horses run.");
}
for(int i = 0; i<arrRan.length; i++){
if(arrRan[i]>=win){
System.out.println("1st place: Horse " + (i+1));
}
}
}//end while
}//close main
}//close class
It's not stopping because the condition readString != null isn't being violated.
For it to print the non-1st place horses, sort the array and assign places as applicable.
For it to stop, try replacing while( readString != null ) with while( nobodyHasWon ). Make a boolean boolean nobodyHasWon = true and set it to false when a horse has won (i.e., after System.out.println("1st place: Horse " + (i+1));).
Alternatively, you could do this:
// assumptions made: there is only one winner at 15, the rest are below 15, there are no ties, and the first ranked horse has been found
int second, third, secondValue, thirdValue;
secondValue = 0; thirdValue = 0;
for( int i = 0; i < arrRan.length; i++ ) {
if( i != <indexOfFirstPlaceHorse> )
{
if( arrRan[ i ] > secondValue ) {
second = i;
secondValue = arrRan[ i ];
}
}
}
for( int i = 0; i < arrRan.length; i++ ) {
if( i != <indexOfFirstPlaceHorse> && i != second ) {
if( arrRan[ i ] > thirdValue ) {
third = i;
thirdValue = arrRan[ i ];
}
}
}
Try this one I updated the code.
SEE DEMO
Scanner reader = new Scanner(System.in);
int range = 3;
int win = 15;
final int SIZE = 3;
Random ran = new Random( );
boolean winner = false;
int[ ] arrRan = new int[SIZE];
System.out.print("Off to the races! Press enter to make the horses run.");
String readString = reader.nextLine();
while(readString!=null){
if(!winner){
System.out.print(readString);
if(readString.equals("")){
for(int i = 0; i<arrRan.length; i++){
arrRan[i] = arrRan[i] + (ran.nextInt(3) + 1);
System.out.println("Horse " + (i+1) + ":" + arrRan[i]);
}
}//end if
for(int j = 0; j<arrRan.length; j++){
if(arrRan[j]>=win){
winner =true;
}
}
if(reader.hasNextLine()){
readString = reader.nextLine();
System.out.println("Please press enter to make the horses run.");
}
}else{
int[] arrClone = new int[arrRan.length];
for(int i=0;i<arrRan.length;i++){
arrClone[i] = arrRan[i];
}
arrRan = sortArray(arrRan);
int[] arrRank = new int[arrRan.length];
int prevNum = arrRan.length;
for(int i=0;i<arrRan.length;i++){
boolean flag = true;
for(int j=0;j<arrRan.length;j++){
if(arrRan[i]==arrClone[j]){
if(j!=prevNum && flag){
prevNum = j;
arrRank[i] = j+1;
flag=false;
}
}
}
}
System.out.println("1st place: Horse " + (arrRank[0]));
System.out.println("2nd place: Horse " + (arrRank[1]));
System.out.println("3rd place: Horse " + (arrRank[2]));
break;
}
}//end while
}
public static int[] sortArray (int[] inArray)
{
//Construct the array we're using here
int[] newArray = inArray;
for(int x = 0; x < newArray.length; x++) //a.length = # of indices in the array
{
for(int y = 0; y < newArray.length; y++)
{
if(newArray[x] > newArray [y]) {
int tempValue = newArray[y];
newArray[y] = newArray[x];
newArray[x] = tempValue;
}
}
}
return newArray;
}

Java count longest possible array

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

Categories