Sorting objects aplhabetically in an Array - java

import java.io.File;
import java.util.Scanner;
public class MainClass {
public static Winner [] listOfWinners;
public static void loadFromFile()
{
try{
//Create instance of Scanner and provide instance of File pointing to the txt file
Scanner input = new Scanner(new File("WorldSeriesWinners.txt"));
//Get the number of teams
int years = input.nextInt();
input.nextLine();//move to the next line
//Create the array
listOfWinners = new Winner[years];
//for every year in the text file
for(int index = 0; index<years; index++)
{
//Get the year
int year = input.nextInt();
input.skip(" ");
//Get the team
String team = input.nextLine();
//Create an instance of Winner and add it to the next spot in the array
listOfWinners[index] = new Winner(team,year);
}
}catch(Exception e)
{
System.out.println("Something went wrong when loading the file!");
System.out.println(e.toString());
System.exit(0);
}
}
public static void sortByTeamName()
{
}
I've been searching online for a few hours but cannot figure out a way to properly sort the array alphabetically

You could use the following snippet for sorting by Team name, by taking advantage of the comparator feature of the Arrays.sort(arr[],comparator)
Arrays.sort(listOfWinners, new Comparator<Winner>() {
#Override
public int compare(Winner o1, Winner o2) {
return o1.team.compareTo(o2.team);
}
});

Related

Comparing Strings and Integers in an Array at the same time

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

java - read file and create array

I have to follow a specific format and use scanner. I know there are better methods, but this is a requirement and I am new to java and trying to figure this out. There is a file with customer name, birth date, and other information. I need to count the number of entries in the file, then the file needs to create an array based on the number of file entries and convert the array to a string array. There is more code I need to do, but I am stuck on this part. The try/catch has to be used.
public class Customers {
//////// MAIN ////////
public static void main(String[] args) {
File file = new File("customers.txt");
int numEntries = countCustomers(file);
Person[] customers = readIntoArray(file, numCustomers);
int min = locateBirthdate(customers);
System.out.println("Birthdays this month: " + customer[mon].getBirthdate());
}
//* Counts customers in the file.//
public static int countCustomers(File f) {
int i = 0;
try {
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
i++;
scan.nextLine();
}
} catch (Exception e) {
System.out.println("Check filename.");
}
return i;
}
//read data into array and convert into string array
public static Customer[] readIntoArray(File f, int num) {
//num = countCustomers(f);
num = 0;
try {
Scanner input = new Scanner(f);
Customer[] birth = new Customer[num];
String[] strBirth = new String[num];
while (num < countCustomers(f)) {
strBirth[num] = input.nextLine();
birth[num] = makeCustomer(strBirth[num]);
num++;
System.out.println(num);
}
} catch (Exception e) {
System.out.println("Error");
}
return null;
Ok. I have several comments.
First - do you really need 'strBirth' array? Looks like you only write elements but not read from the array.
Second - 'readIntoArray' method always returns null.
Also, you count customers twice, but only one is enough.
Then, do you really need an array with customers? Since you use an array, you need to know exactly the count of customers and therefore you need to scan the file twice. If you use ArrayList, you need to scan file only one time.
I have fixed the issues in the code below.
public class Customers {
//////// MAIN ////////
public static void main(String[] args) {
File file = new File("customers.txt");
Person[] customers = readIntoArray(file, numCustomers);
int numEntries = customers.length;
int min = locateBirthdate(customers);
System.out.println("Birthdays this month: " + customer[mon].getBirthdate());
}
public static Person[] readIntoArray(File f, int num) {
List<Customer> customers = new ArraList<>();
try {
Scanner input = new Scanner(f);
String[] strBirth = new String[num];
while (scan.hasNextLine()) {
customers.add(makeCustomer(scan.nextLine()));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return customers.toArray(Person[]::new);
}

How read and print a two column text file containing integers and look for a specific value in the first column?

I'm new to Java and would appreciate any assistance to solve the following problem.
I would like the java program to read and print a two column (integer or double) text file and search for a value in the first column that matches with another parameter within the java code. If the match is found, to print out the corresponding value on the second column. I wrote the following code which can read and print the data in console but I'm unable to use this data in the next code to search for a value in the first column that matches with another parameter. please help,here is my code:
import java.io.File;
import java.util.Scanner;
public class readfile {
private Scanner s;
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
public void openFile() {
try {
s = new Scanner (new File("filename.txt"));
}catch(Exception e) {
System.out.println("file not found ");
}
}
public void readFile() {
while(s.hasNext()) {
String a = s.next();
String b = s.next();
System.out.printf("%s %s\n",a, b);
}
}
public void closeFile() {
s.close();
}
}
// here is the problem!
double a = 0;
double b = 0;
if (para == a[i]) {
System.out.println("param =" + a[j]);
}else {
System.out.println("It is out of range ");
}

Cant figure out the null pointer exception

Please help me figure out the null pointer exception. I am not able to understand which variable or object is null.and hoe do i fix it ?
package coll.org;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
public class SnakeAndladder1 {
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
public int throwdice() //to calculate the dice value
{
return (int)(Math.random()*6)+1;
}
public int ladder(int curscore)
{
Hashtable ld = new Hashtable();
ld.put(15,30);
ld.put(45,71);
ld.put(25,62);
ld.put(81,91);
ld.put(9,39);
Object v=ld.get(curscore);
return (int)v;
}
public int snake(int curscore)
{
Hashtable ld = new Hashtable();
ld.put(29,11);
ld.put(81,48);
ld.put(30,6);
ld.put(92,71);
ld.put(58,19);
Object v=ld.get(curscore);
return (int)v;
}
public boolean Game (String name1){
int score=0;
String name;
int v=0;
name=name1.toString();
System.out.println("Click y to roll dice");
Scanner in2=new Scanner(System.in);
String yes=in2.nextLine();
if(yes.equalsIgnoreCase("y"))
{
v=throwdice();
System.out.println("dice value:"+v);
}
score=score+v;
if(score==100)
{
System.out.println("User:"+name+"got"+v+".Winner!!!");
return false;
}
if (score>100)
{
score=score-v;
System.out.println("Current score of"+name+"is"+score);
return true;
}
int s1=ladder(score);
if(s1==score)
{
score=snake(score);
System.out.println("Current score of"+name+"is"+score);
return true;
}
else
{
score=s1;
System.out.println("Current score of"+name+"is"+score);
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int l=0;
boolean flag=true;
System.out.println("Enter the number of players:");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
System.out.println("Enter Players names in order:");
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
for (int i=0;i<n;i++)
{
Scanner in1=new Scanner(System.in);
String name2=in1.nextLine();
name1.add(name2);
}
SnakeAndladder1 players[];
players = new SnakeAndladder1[n];
while(flag)
{
while(l<n)
{
flag = players[l].Game(name1.get(l)); //----Error occuring here.Its a null pointer
} exception
}
}
}
the stack trace is :
Enter the number of players:
3
Enter Players names in order:
raghav
kishan
sr
Exception in thread "main" java.lang.NullPointerException
at coll.org.SnakeAndladder1.main(SnakeAndladder1.java:107)
The following initializes the array with n nulls:
players = new SnakeAndladder1[n];
To avoid the NPE, you need to create the objects before calling Game() on them.
SnakeAndladder1 players[];
players = new SnakeAndladder1[n];
Add this after above:
for(int i = 0; i < players.length; i++)
{
players[i] = new SnakeAndladder1();
}
This will initialize an object at each element of the array.
The n in your case is a null, since you're getting the value from the user. So it won't create the array as a finite array. They're all nulls.
Try to initialize the number first from the user and then initialize the array.

java array passing, I keep getting the last array everywhere

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!

Categories

Resources