I am doing an exercise that asks me to read a file in csv format, and ask user`s input about the word he wants the program to look for. This is the format of the document, index 0 and 1 are name of teams therefore Strings and index 2 and 3 are the scores of the games:
ENCE,Vitality,9,16
ENCE,Vitality,16,12
ENCE,Vitality,9,16
ENCE,Heroic,10,16
SJ,ENCE,0,16
SJ,ENCE,3,16
FURIA,NRG,7,16
FURIA,Prospects,16,1
At first the exercise asked me to write a program that reads the document and print how many games certain team played. Now it wants me to write one that will compare scores and print the total number of wins and losses of that specific team. I tried to do it in a million different ways, is there an effective way to compare Strings and integers at the same time ?
My code below:
import java.nio.file.Paths;
import java.util.Scanner;
public class SportStatistics {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("File:");
String file = scan.nextLine();
System.out.println("Team:");
String team = scan.nextLine();
try ( Scanner reader = new Scanner(Paths.get(file))) {
int totalGames = 0;
int teamPoints = 0;
int otherPoints = 0;
int wins = 0;
int losses = 0;
while (reader.hasNextLine()) {
String info = reader.nextLine();
if (info.isEmpty()) {
continue;
}
String[] parts = info.split(",");
String homeN = parts[0];
String visitorN = parts[1];
int homeP = Integer.valueOf(parts[2]);
int visitorP = Integer.valueOf(parts[3]);
for (String part : parts) {
if (part.equals(team)) {
totalGames++;
}
if(homeN.equals(team)){
teamPoints = homeP;
otherPoints = visitorP;
if(teamPoints > otherPoints){
wins ++;
}else{
losses ++;
}
}
if(visitorN.equals(team)){
teamPoints = visitorP;
otherPoints = homeP;
if(teamPoints > otherPoints){
wins ++;
}else{
losses ++;
}
}
}
}
System.out.println("Games: " + totalGames);
System.out.println(wins);
} catch (Exception e) {
}
}
}
(This is the kind of problem where using a database would make more sense)
So first, what you want is a Game class
public class Game {
String team1;
String team2;
int team1Score, team2Score;
public Game(String t1, String t2, int score1, int score2);
}
Now you want to make a collection (probably a list) of games
List<Game> games = new ArrayList<>();
Then you want to add all the games to the list
Then you have a choice. You could create a Map<String, List> and create lists for all your teams that include all the games they played. Or you could make a method, like
public List<Game> getGamesForTeam(String teamName, List allGames) {
...
}
That extracts a list of games that included team teamName
Hopefully this makes sense to you and will get you started
Related
Hello in my monopoly game i need to make sure no inputted player names are the same to avoid confusion using an arraylist in java any way how to do it so only one player can have one name
public class Player {
private ArrayList<Property> properties = new ArrayList<Property>();
private final String name;
private int position;
private int money = 0;
public boolean inJail = false;
public int outOfJailCards = 0;
public int turnsInJail = 0;
public Player(String name){
this.name = name;
position = 0;
}
public String getName() {
return name;
}
// in monopoly.java
static ArrayList<Player> createPlayers(int numPlayers){
ArrayList<Player> players = new ArrayList<>();
for(int i = 1; i <= numPlayers; i++){
System.out.print("Player " + i + " name: ");
players.add(new Player(Input.read()));
}
return players;
}
}
import java.util.List;
import java.util.Scanner;
public class Input {
public static String read(){
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
Instead of directly adding the player to the array list, check with .contains() first. If not, ask for re-input. You will not be able to do this directly with a for loop, you will need to restructure your code.
PS: This sounds very much like homework in a programming course.
you can save the input from the user into a variable and check if the name already exists in the list:
String input = Input.read();
if(!list.stream().findAny(s -> s.getName().equals(input)).isPresent()({
players.add(new Player(input));
}
Stream API were used to check if name already exists in the list, but you could also use the .contains method, but first you need to override the equals method in your Player class.
I have been assigned a task that requires me to utilise a 2D Array. I have to read in a file and export it to a 2D array. I can only have a single method but I am unable to sort the array correctly. I am supposed to sort the data in 3 ways (alphabetically by name and with scores highest to lowest; highest to lowest scores for each student and highest to lowest by the average of 3 scores.) So far I have
import java.util.*;
import java.io.*;
public class ScoreSorter {
public static void main(String[] args) {
int student_num = 30;
String[][] DataInTableArr = new String[30][6];
try {
BufferedReader ReadIn = new BufferedReader(new FileReader("classZ.csv"));
for (int i = 0; i < 30; i++) {
String DataIn = ReadIn.readLine();
String[] DataInArr = DataIn.split(",");
DataInTableArr[i][0] = DataInArr[0];
DataInTableArr[i][1] = DataInArr[1];
DataInTableArr[i][2] = DataInArr[2];
DataInTableArr[i][3] = DataInArr[3];
int temptest1 = Integer.parseInt(DataInArr[1]);
int temptest2 = Integer.parseInt(DataInArr[2]);
int temptest3 = Integer.parseInt(DataInArr[3]);
}
} catch (Exception e) {
System.out.println("Whoops, you messed up, RESTART THE PROGRAM!!!!!");
}
}
}
I have no idea as to how to solve the rest of the task... I would appreciate if someone could tell me of the most efficient way and perhaps an example...
One plausible way is to create a Student class which implements Comparable interface, with the following members:
String name;
int scoreOne;
int scoreTwo;
int scoreThree;
compareTo(Student s) { //implement the comparison following 3 criteria you mentioned }
And, read the files row by row, for each row we create a Student object, and put all rows in a TreeSet. In this way, the TreeSet together with the compareTo method will help us sort the Students automatically.
Finally, iterate the sorted TreeSet to fill up the 2D array.
import java.util.*;
import java.io.*;
public class ScoreSorter {
public static void main(String[] args) {
int student_num = 30;
String[][] DataInTableArr = new String[30][6];
try {
BufferedReader ReadIn = new BufferedReader(new FileReader("classZ.csv"));
for (int i = 0; i < 30; i++) {
String DataIn = ReadIn.readLine();
String[] DataInArr = DataIn.split(",");
DataInTableArr[i][0] = DataInArr[0];
DataInTableArr[i][1] = DataInArr[1];
DataInTableArr[i][2] = DataInArr[2];
DataInTableArr[i][3] = DataInArr[3];
int temptest1 = Integer.parseInt(DataInArr[1]);
int temptest2 = Integer.parseInt(DataInArr[2]);
int temptest3 = Integer.parseInt(DataInArr[3]);
}
/*Code To be Inserted Here*/
} catch (Exception e) {
System.out.println("Whoops, you messed up, RESTART THE PROGRAM!!!!!");
}
}
}
If there are 6 columns such that First is name and the other 3 are scores then what does other 2 columns contain?? I ignore your array declaration :
String[][] DataInTableArr = new String[30][6];
and assume it to be 30x4 array
String[][] DataInTableArr = new String[30][4];
Logic for sorting Alphabetically
if(DataInTableArr[i][0].compareTo(DataInTableArr[i+1][0])){
/* Sorting Name of adjacent rows*/
String temp = DataInTableArr[i][0];
DataInTableArr[i][0] = DataInTableArr[i+1][0];
DataInTableArr[i+1][0] = temp;
/*Sorting the three marks similarly*/
temp = DataInTableArr[i][1];
DataInTableArr[i][1] = DataInTableArr[i+1][1];
DataInTableArr[i+1][1] = temp;
temp = DataInTableArr[i][2];
DataInTableArr[i][2] = DataInTableArr[i+1][2];
DataInTableArr[i+1][2] = temp;
temp = DataInTableArr[i][3];
DataInTableArr[i][3] = DataInTableArr[i+1][3];
DataInTableArr[i+1][3] = temp;
}
Put the above code in bubble sorting algorithm i.e. 2 loops.
Logic for sorting according to highest marks
In this case you have to find the highest marks in all three subjects of each DataInTableArr[i] and then compare the highest marks with that of next row.
Logic for sorting according to Average marks
Calculate the average of each i'th row as
(Integer.parseInt(DataInTableArr[i][1]) + Integer.parseInt(DataInTableArr[i][2]) + Integer.parseInt(DataInTableArr[i][3]))/3
and compare it with [i+1] th rows average.(same formula just replace [i] with [i+1])
I'm making a number guessing game for a school project in Java, which I'm extremely bad at. I've got everything to work with classes and the guessing part, but now I'm going to create a top players list and sort it and I have no idea how.
This is the code I use for guessing and creating objects of the player.
public static void spela() {
int nummer= ((int) (1+Math.random()*100));
Scanner input = new Scanner(System.in);
Scanner s_input = new Scanner(System.in);
boolean ratt = false;
int forsok = 1;
int gissning;
String namn;
while(ratt==false) {
System.out.println("Gissa nummer: ");
gissning = input.nextInt();
if(gissning == nummer) {
System.out.println("Grattis du gissade rätt! Tog: " + forsok + " försök att gissa rätt!");
System.out.println("Skriv in namn: ");
namn = s_input.nextLine();
for(int i=0;i<cr;i++) {
if(namn.equals(allaspelare[i].namn)) {
allaspelare[i].setpoang(forsok);
ratt=true;
menu();
}
}
allaspelare[cr] = new spelare(namn);
allaspelare[cr].setpoang(forsok);
cr++;
ratt=true;
menu();
}
if(gissning > nummer) {
System.out.println("Du gissade: " + gissning + " och det var för mycket!");
}
if(gissning < nummer) {
System.out.println("Du gissade: " + gissning + " och det var för lite!");
}
forsok++;
}
}
this is the "spelare" class:
public class spelare {
int[] poang = new int[100];
int antal;
String namn;
public spelare(String innamn) {
namn = innamn;
}
public void setpoang(int inpoang) {
poang[antal] = inpoang;
antal++;
}
}
as you see one player can have multiple scores so that's the problem I can't get it right in my mind how I'm going to sort it so the output if I wan't to get out the score chart will come like:
testplayer1: 9
testplayer2: 11
testplayer3: 34
So basically I need help to code a method that goes through the class and sort it and output it as above! Any help/sources is extremely appreciated!
And commented code would be extremely appreciated so I can learn!
EDIT:
I've been searching for hours, and the only thing that I found was this:
public static void sortera(int[] lista, int plats) {
int i;
if (lista.length < 2) return;
int temp;
for(int n=1; n<lista.length; n++) {
temp=lista[n];
i = n - 1;
while(i >=0 && lista[i] > temp) {
lista[i+1] = lista[i];
}
lista[i+1] = temp;
}
allaspelare[plats].poang = lista;
}
And this is how I called it:
case 5:
sortera(allaspelare[0].poang, 0);
break;
but this doesn't do anything..
The structure you use is simply bad. Instead you should use pairs of names and scores. This way multiple scorepairs with the same name exist, but you can easily sort them.
public class Score implements Comparable<Score>{
private int score;
private String name;
public Score(String name , int score){
this.score = score;
this.name = name;
}
//getters and setters as required
public int compareTo(Score s){
return score - s.score;
}
}
This aswell allows you to directly compare Scoreobjects to eachother. This way a list of Score objects can easily be sorted via Collections.sort(someList).
I am trying to go through a list of names with amounts.
One array has the name of the person , the other has the amount the person gave i.e. john, 55 sally 40 john 33 sarah 55.
My objective is to total the like names and print out the name of the person and the total amount that was given.
John gave twice so he should total 88. But I am getting the total right but my program is printing the name twice. So john 88 is printing twice... I know its likely because I put it in the first for loop its iterating the entire length of the array.
But I am unsure how to solve this?
import java.util.*;
public class chapterfive {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
String[]names = new String[4];
int[] scores = new int[4];
for (int i = 0; i<names.length; i++) {
names[i] = in.next();
scores[i] = in.nextInt();
}
int amount = 0;
String firstname = "";
for (int i = 0; i < names.length; i++) {
for (int j=0; j < names.length; j++) {
if (names[j].equals(names[i]))
amount += scores[j];
}
System.out.println(names[i] + " " + amount);
amount = 0;
}
}
}
You can see that they have a relationship like Name -> Score , so if you think more abstract this is a dictionary with Key (Name) and Value (Score) , so you can use another data-structure like a Map or you can use an array and make a class Person , have the arrayOrderer and when you add a new person check if that person exist in the array..
Example :
Map <String , Integer> people = new HashMap<>();
for (int i=0; i<lengthYouWant; i++)
{
String name=in.next();
int score=in.nextInt();
if(people.contains(name)){
score= people.get(name)+score;
}
people.put(name,score);
}
Should be using a Map to simplify things, rather than keeping track of two arrays. But heres a fix that may work (haven't tested it)
String firstname = "";
for (int i = 0; i < names.length; i++) {
int amount = 0;
boolean skip = false;
for (int j=0; j < names.length; j++) {
//need to skip because we have already processed it
if(names[j].equals(names[i]) && i > j) {
skip = true;
break;
}
else if (names[j].equals(names[i])) {
amount += scores[j];
}
}
if(!skip) {
System.out.println(names[i] + " " + amount);
}
}
If you make an array or list of the Person class you can implement Comparable and add a method to help in sorting.
Java is an object-oriented language, which means, among other things, that you can make your own data structures. Using parallel arrays is error prone, and it separates data you want to keep together. So, what do you need to organize this?
First is a way of storing a name and an amount. Call it Donation.
class Donation {
private final String name;
private final int amount;
public Donation(String name, String amount) {
this.name = name;
this.amount = amount;
// EXERCISE: Add error checking.
}
public String getName() { return name; }
public int getAmount() { return amount; }
public String toString() {
return "Name: " + name +", amount: " + amount;
}
}
Notice that this class's variables are final; they can't be changed once set. They are set in the constructor, and there are get methods and a toString method that replaces what you have in your System.out.println statement.
Next, you need a way of storing the data. Don't use arrays. Lists are more flexible.
private static List<Donation> donations = new ArrayList<Donation>();
// and in main:
while (true) {
String name = null;
int amount = 0;
if (in.hasNext()) {
name = in.next();
} else {
break;
}
if (in.hasNextInt()) {
amount = in.nextInt();
} else {
break;
}
donations.add(new Donation(name, amount));
} See -- no 4s.
Next, you need to consolidate the repeated donations. I mean, some people give to their church every Sunday. We'll use the appropriate structure, a Map.
// Also in main:
Map<String, Integer> totals = new HashMap<>();
for(Donation d: donations) {
String name = d.getName();
int amount = d.getAmount();
if (!totals.containsKey(name)) {
totals.put(name, 0);
}
int currentDonation = totals.get(name);
totals.put(name, currentDonation + amount);
}
And then finally, you iterate through the map and print each entry.
for ( Map.Entry<String, Integer> entry: totals.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
And now, another exercise and strategy: stop doing everything in main. Give your ChapterFive class instance variables and methods. Then, write tests for these. Try to find improvements to what I suggested. Then, see if there are libraries that can help you.
I am having a problem in this code. what i am trying to do is read a file and store a studentID and score into an array of scores into the scores property of a student object, but I keep getting the last scores only when I print. Here is the code. can you tell me if my setter property is a correct way of assigning an array in the student class? the problem is the last line of the score file is stored in every array even though when I debug it I see the score array being passed and the studentID array works fine.
import lab6.*;//importing the necessary classes
public class Main
{
public static void main(String[] args)
{
Student lab6 [] = new Student[40];
//Populate the student array
lab6 = Util.readFile("studentScores.txt", lab6);
lab6[4].printStudent();
}
}
The student class------------------------------------
package lab6;
public class Student
{
private int SID;
private int scores[] = new int[5];
//write public get and set methods for SID and scores
public int getSID()
{
return SID;
}
public void setSID(int SID)
{
this.SID = SID;
}
public int[] getScores()
{
return scores;
}
public void setScores(int scores[])
{
this.scores = scores;
}
//add methods to print values of instance variables.
public void printStudent()
{
System.out.print(SID);
System.out.printf("\t");
for(int i = 0; i < scores.length; i++)
{
System.out.printf("%d\t", scores[i]);
}
}
}
the util class --------------------------------------------------------------------
import java.io.*;
import java.util.StringTokenizer;
//Reads the file and builds student array.
//Open the file using FileReader Object.
//In a loop read a line using readLine method.
//Tokenize each line using StringTokenizer Object
//Each token is converted from String to Integer using parseInt method
//Value is then saved in the right property of Student Object.
public class Util
{
public static Student [] readFile(String filename, Student [] stu)
{
try {
String line[] = new String[40];//one line of the file to be stored in here
StringTokenizer stringToken;
int studentID;//for storing the student id
int[] studentScoreArray = new int[5];//for storing the student score
FileReader file = new FileReader(filename);
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
int i = 0;
buff.readLine();//used this to skip the first line
while (!eof) //operation of one line
{
line[i] = buff.readLine();
if (line[i] == null)
eof = true;
else //tokenize and store
{
stringToken = new StringTokenizer(line[i]);
String tokenID = stringToken.nextToken().toString();//for storing the student id
studentID = Integer.parseInt(tokenID);
stu[i] = new Student();//creating student objects
stu[i].setSID(studentID);//stored in student object
//now storing the score-------------------------------------------------
int quizNumberCounter = 0;
while (stringToken.hasMoreTokens())
{
String tokens = stringToken.nextToken().toString();
studentScoreArray[quizNumberCounter] = Integer.parseInt(tokens);//converting and storing the scores in an array
quizNumberCounter++;//array progression
}
stu[i].setScores(studentScoreArray);//setting the score(passing it as an array)
//-----------------------------------------------------------------------
}
i++;
}
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
return stu;
}
/*
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
//How to convert a String to an Integer
int x = Integer.parseInt(String) ;*/
}
Sample file Structure -------------------------------------------------------
4532 011 017 081 032 077
The issue lies within the line
int[] studentScoreArray = new int[5];
You'll have to move this one inside your student loop and initialize the array per student. Otherwise you are reusing the same array (i.e. memory) for all students and you are overwriting scores over and over again.
// int[] studentScoreArray = new int[5]; // <= line removed here!!!
...
while (!eof) //operation of one line
{
line[i] = buff.readLine();
if (line[i] == null)
eof = true;
else //tokenize and store
{
int[] studentScoreArray = new int[5]; // <= line moved over to here!!!
...
}
}
I havent tested the code with my suggestion, but take a look at:
int[] studentScoreArray = new int[5];
You create this once and once only for the whole file.
A simple and easy fix is to do it for every new line read instead.
like this :
int[] studentScoreArray = new int[5];
int quizNumberCounter = 0;
while(..) { ...}
One reason you may only being seeing one line of results is that you are only printing one line of results:
lab6[4].printStudent();
You will need to change this to loop through the array if you want to see all the results:
foreach (Student student : lab6)
{
student.printStudent();
}
On a side note, your array should probably be called something like students instead of lab6. Also it is idiomatic in java to declare arrays using Type[] identifier rather than Type identifier [].
DISCLAIMER: There may be other stuff wrong, I didn't read all the hundreds of lines posted!