EDIT: To test these cases, change sort and filter methods to the following:
EXAMPLE SORT METHOD:
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
}
EXAMPLE FILTER METHOD (FOR STRING INPUT):
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
EXAMPLE FILTER METHOD (FOR INT INPUT):
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
TEST CASES:
Input strings should be like the following examples:
sort:title
This input runs successfully until
the line System.setOut(out); in the main class, where it begins to print spaces and does not successfully print the collection. This may be because of a problem with the toString method in the SongCollection class.
artist:Paramore
or
title:Misery Business
This input runs successfully through the entire program (the program does not terminate because the while loop does not terminate), except instead of printing the collection, a blank space is printed.
ADDITIONAL DETAILS:
This question is a followup to a previous question I asked, since I have short time constraints on this project (it is due tomorrow).
The primary problem I am experiencing with this is that the program is failing to output correctly, even though the methods and code in the main for printing seems logically sound.
Printing arraylist into output file?
For some reason, it takes an extraordinary amount of time for the ArrayLists to be printed to the output file, usually 20-30 minutes. However, this only happens with the sort methods or the filterTitle or filterArtist methods (methods that concern String inputs).
When I run filterRank or filterYear, it runs perfectly fine.
When I print the song2 ArrayList directly from the filter methods, the only thing that is printed is [], which means the ArrayList is empty, but it shouldn't be? And the filterRank and filterYear methods still work regardless of this.
Somehow I think it's related, though.
Input file can be found here: http://staff.rentonschools.us/hhs/ap-comp-science/projects/download/agazillionsongs.txt?id=223098
Full code for compilation:
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.Comparator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class GazillionSongs {
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Welcome to Java Song Collection!"); // greets the user
System.out
.println("This program sorts and filters large databases of popular songs."); // explains purpose of program
System.out
.println("This program is able to filter and sort by year, artist, title and rank.");
System.out
.println("Please enter a file that contains a database you wish to filter or sort. (i.e, alistofsongs.txt)"); // sample file = agazillionsongs.txt
Scanner fileInput = new Scanner(System.in); //Scanner which accepts filename
String filename = fileInput.nextLine();
File f = new File(filename); //creates file from input
/*error check for file here*/
Scanner fileScanner = new Scanner(f); //inputs data from file
ArrayList<Song> songs = new ArrayList<Song>();
while ((fileScanner.hasNextLine())) {
songs.add(Song.parse(fileScanner.nextLine()));
}
System.out
.println("Please select which commands you would like to use for the program.");
System.out
.println("Please format your command like the following example: year:<year(s)> rank:<rank(s)> artist:<artist> title:<title> sortBy:<field>");
System.out.println();
System.out.println("You may pick any number of commands you want.");
System.out
.println("For years and rank, you may select a range of years or ranks.");
System.out
.println("For artists and titles, you may enter a partial name or title.");
System.out.println("i.e, year:1983 rank:1");
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = input.nextLine();
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
System.out.println(collection.toString());
System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();
}
}// end of main
}// end of class
class Song{
public enum Order {Year, Rank, Title, Artist}
public int year;
public int rank;
public String artist;
public String title;
public static Song parse(String s) {
Song instance = new Song();
StringTokenizer tokenizer = new StringTokenizer(s, "\t");
instance.year = Integer.parseInt(tokenizer.nextToken());
instance.rank = Integer.parseInt(tokenizer.nextToken());
instance.artist = (tokenizer.nextToken());
instance.title = (tokenizer.nextToken());
return instance;
}
public int getYear() {
return year;
}
public int getRank() {
return rank;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String toString() {
String output = "\n\nYear = " + year + "\nRank = " + rank + "\nArtist = "
+ artist + "\nTitle = " + title;
return output;
}
}
class Range {
private int min;
private int max;
public Range() {
System.out.println("Please wait.");
}
public static Range parse(String s) {
Range instance = new Range(); // instance is created here so object
// variables may be accessed
String field; // String to contain deleted part of user input
StringTokenizer tokenizer = new StringTokenizer(s, "-");
StringTokenizer tokenizer2 = new StringTokenizer(s, ":");// for separating "field:" from the
// other part of the String
if (s.contains(":")) { // this deletes the "field:" of the user input so
// it does not interfere with the parsing
field = (tokenizer2.nextToken());
s = s.replace(field, "");
s = s.replace(":", "");
}
if (s.contains("-")) {
instance.min = Integer.parseInt(tokenizer.nextToken());
instance.max = Integer.parseInt(tokenizer.nextToken());
} else if (!(s.contains("-"))) {
{
instance.min = Integer.parseInt(s);
instance.max = Integer.parseInt(s);
}
}
System.out.println("Range max = " + instance.max);
System.out.println("Range min = " + instance.min);
return instance;
}
public boolean contains(int n) {
if (n > min && n < max) { //if the number is contained in the range, method returns true.
return true;
} else if (n == min && n == max) {
return true;
} else {
return false;
}
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
class SongCollection {
ArrayList<Song> songs2;
ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(ArrayList<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
System.out.println(songs2);
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
System.out.println(songs2);
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
System.out.println(songs2);
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
System.out.println(songs2);
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
class SongComparator implements Comparator<Song> {
public enum Order{
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy){
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
I tried to run this code and it works fine and fast. I am using file you posted and as you can see, test value for searching is "year:1983 sort:title". I also simplified it by removing while-cycle and user-input filename and filter string, so anyone can easily reproduce it.
If you want to help, I need to know, how to reproduce that 20-30 minute outputing to file.
:
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.Comparator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class GazillionSongs {
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Java Song Collection!"); // greets the user
System.out
.println("This program sorts and filters large databases of popular songs."); // explains purpose of program
System.out
.println("This program is able to filter and sort by year, artist, title and rank.");
System.out
.println("Please enter a file that contains a database you wish to filter or sort. (i.e, alistofsongs.txt)"); // sample file = agazillionsongs.txt
File f = new File("agazillionsongs.txt"); //creates file from input
/*error check for file here*/
Scanner fileScanner = new Scanner(f); //inputs data from file
List<Song> songs = new ArrayList<Song>();
while ((fileScanner.hasNextLine())) {
Song song = Song.parse(fileScanner.nextLine());
songs.add(song);
}
System.out
.println("Please select which commands you would like to use for the program.");
System.out
.println("Please format your command like the following example: year:<year(s)> rank:<rank(s)> artist:<artist> title:<title> sortBy:<field>");
System.out.println();
System.out.println("You may pick any number of commands you want.");
System.out
.println("For years and rank, you may select a range of years or ranks.");
System.out
.println("For artists and titles, you may enter a partial name or title.");
System.out.println("i.e, year:1983 rank:1");
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = "year:1983 sort:title";
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
System.out.println(collection.toString());
System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();
}
}// end of main
class Song {
public enum Order {
Year, Rank, Title, Artist
}
public int year;
public int rank;
public String artist;
public String title;
public static Song parse(String s) {
Song instance = new Song();
StringTokenizer tokenizer = new StringTokenizer(s, "\t");
instance.year = Integer.parseInt(tokenizer.nextToken());
instance.rank = Integer.parseInt(tokenizer.nextToken());
instance.artist = (tokenizer.nextToken());
instance.title = (tokenizer.nextToken());
return instance;
}
public int getYear() {
return year;
}
public int getRank() {
return rank;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String toString() {
String output = "\n\nYear = " + year + "\nRank = " + rank + "\nArtist = "
+ artist + "\nTitle = " + title;
return output;
}
}
class Range {
private int min;
private int max;
public Range() {
System.out.println("Please wait.");
}
public static Range parse(String s) {
Range instance = new Range(); // instance is created here so object
// variables may be accessed
String field; // String to contain deleted part of user input
StringTokenizer tokenizer = new StringTokenizer(s, "-");
StringTokenizer tokenizer2 = new StringTokenizer(s, ":");// for separating "field:" from the
// other part of the String
if (s.contains(":")) { // this deletes the "field:" of the user input so
// it does not interfere with the parsing
field = (tokenizer2.nextToken());
s = s.replace(field, "");
s = s.replace(":", "");
}
if (s.contains("-")) {
instance.min = Integer.parseInt(tokenizer.nextToken());
instance.max = Integer.parseInt(tokenizer.nextToken());
} else if (!(s.contains("-"))) {
{
instance.min = Integer.parseInt(s);
instance.max = Integer.parseInt(s);
}
}
System.out.println("Range max = " + instance.max);
System.out.println("Range min = " + instance.min);
return instance;
}
public boolean contains(int n) {
if (n > min && n < max) { //if the number is contained in the range, method returns true.
return true;
} else if (n == min && n == max) {
return true;
} else {
return false;
}
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
class SongCollection {
List<Song> songs2;
List<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(List<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
System.out.println(songs2);
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
System.out.println(songs2);
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
System.out.println(songs2);
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
System.out.println(songs2);
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
class SongComparator implements Comparator<Song> {
public enum Order {
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy) {
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
EDIT :
Question:
title:Misery Business
This input runs successfully through the entire program (the program does not terminate because the while loop does not terminate), except instead of printing the collection, a blank space is printed.
Yes, because in your method, you are testing, if it contains title:Misery Business not Misery Business.
First of all, you cant use that tokenizer for anything, that contains space. But for one-word only, you can change it as following :
Tested and working for title:Misery :
public void filterTitle(String s) {
int n = 0;
s = s.split(":")[1];
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.title.contains(s) == false) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
Related
in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}
my task is to read a file and then print out the most 10 frequent words in the text file.
I have used the following comparator and it gives me correctly the first 3 most frequent words but then it kind of gets it all wrong and it only prints out 9 instead of 10.
Here is my comparator
import java.util.*;
class CompareFreq implements Comparator<HashElement>
{
public int compare(HashElement x, HashElement y)
{
if (y.getCounter() > x.getCounter())
{
return 1;
}
else
{
return -1;
}
}
}
And here is my main:
String[] temp = new String[100000];
Scanner obj = new Scanner(new File("file.txt"));
while (obj.hasNext())
{
String text = obj.nextLine();
for (String t : text.split(" "))
{
set.insert(t);
}
}
System.out.println("All words and the frequency:");
set.printTableInOrderAndFreq();
System.out.println();
System.out.println("Most 10 frequent words:");
set.getMaxWordsFrequency(10);
Here is the output that I am getting
Most 10 frequent words:
to
the
of
their
they
caused
with
companions
great
The first 3 (to, the, of) words are correct, they are the most frequent in my text but then the calculations are wrong. On top of that I believe it is deleting on of the 10 words where you can see there's a blank row between the word 'they' and 'caused'
I forgot to post my HashElement class, here it is
public class HashElement
{
private String word; // ordet
public int counter; // antalet förekomst av ordet
private boolean isActive; // behövs eventuellt för remove
public HashElement(String theword)
{
word = theword;
isActive = true;
}
public void increment()
{
counter++;
}
public int getCounter()
{
counter++;
return counter;
}
public String getWord()
{
return word;
}
public boolean getStatus()
{
return isActive;
}
public boolean changeStatus()
{
isActive = false;
return isActive;
}
}
Thanks for the help in advance
I am a newbie to Java. I have an array which includes sports IDs in int type. These IDs have sports name and calorie which burns if you do sport 1 hour. I want to add these attributes(name and calorie) through this array's elements. I am also reading a file that includes sports ID, name, and calorie information. I am splitting them by \t. It is splitting but the problem is, my implementation does not assign the attributes. I need to do this on Sports class not Main class. And I have to access this array and its attributes in other classes. If I give an example when I call array[2].name this must give me like Basketball. Or, array[2].calorie must give me 200. I have tried in for loop and assign them like:
for ( int i = 0; i < array.length; i++ ) {
array[i].name = nameOfSport;
array[i].calorie = calorieOfSport;
}
import java.io.*;
import java.util.*;
public class Sport {
private int sportID;
private String sportName;
private int sportCalorie;
public int[] sportArray = new int[0];
public void readFileSport() {
File file = new File("src/sport.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int i = 0;
String str;
try {
while ((str = br.readLine()) != null) {
int j = 0;
for ( String retval: str.split("\t")) {
if ( j == 0 ) {
System.out.println(retval);
sportArray = addElementArray(sportArray, Integer.parseInt(retval));
System.out.println(sportArray[i]);
j++;
} else {
if (j == 1) {
// System.out.println(retval);
setSportName(sportArray, retval, i);
System.out.println(sportArray[i].sportName);
j++;
} else if (j == 2) {
//System.out.println(retval);
setSportCalorie(Integer.parseInt(retval));
j++;
}
}
}
i++;
}
} catch (FileNotFoundException e) {
System.out.println("Sport File could not find");
}
} catch (IOException e) {
System.out.println("Sport file could not read!");
}
}
public void assignFields () {
}
public void setSportID (int sportID) {
this.sportID = sportID;
}
public void setSportName (int[] array, String name, int e) {
array[e].sportName = name;
}
public void setSportCalorie (int sportCalorie) {
this.sportCalorie = sportCalorie;
}
public void print() {
int k = 0;
while ( k < sportArray.length ) {
System.out.println(sportID);
k++;
}
}
public static int[] addElementArray(int[] array, int newInt) {
int[] newArray = new int[array.length + 1];
for ( int i = 0 ; i < array.length ; i++ ) {
newArray[i] = array[i];
}
newArray[newArray.length - 1] = newInt;
return newArray;
}
public int[] getSportArray() {
return sportArray;
}
}
So let's say you have a class called Sports with
public class Sport{
public String name;
public int calorie;
}
Then you initiate them with
Sport[] sports = new Sport[] // or your own split() to specify length
Arrays.setAll(sports, i->new Sport())
And this should be able to solve the problem.
You can also use ArrayList in which you could just add new elements while looping through the lines.
public static void readFileSport() {
File file = new File("src/sport.txt");
try {
Scanner br = new Scanner(file);
int i = 0;
String str;
try {
while (br.hasNextLine()) {
String[] info=str.split("\t");
System.out.println(info[0]);
sportArray = addElementArray(sportArray, Integer.parseInt(info[0]));
System.out.println(sportArray[i]);
// System.out.println(info[1]);
setSportName(sportArray, info[1], i);
System.out.println(sportArray[i].sportName);
//System.out.println(info[2]);
setSportCalorie(Integer.parseInt(info[2]));
i++;
}
} catch (FileNotFoundException e) {
System.out.println("Sport File could not find");
}
} catch (IOException e) {
System.out.println("Sport file could not read!");
}
}
When you only has 3 objects per line, it is actually easier this way.
I'm working on a program that supports inserting into a string, deleting a substring from a string, and an undo method. My professor provided the driver, which shouldn't be changed. I've written my own relevant SmartString and UndoMethod classes (there's also ADT and Test classes, but don't worry about those). But whenever I try to insert a string, I keep getting an IndexOutofBoundsException. I've accounted for the offset in StringBuilder, but I still can't quite get my code to work. The output that I got is below as well. Here is the SmartString class:
import java.util.Stack;
public class SmartString implements SmartStringADT{
StringBuilder stringBuild = new StringBuilder();
Stack<UndoMethod> undoStack = new Stack<>();
private String newString;
boolean undo = false;
public SmartString(){
newString = "";
}
public SmartString(String newString){
StringBuilder stringBuild = new StringBuilder(newString);
}
public void insert(int pos, String sstring) {
// TODO Auto-generated method stub
stringBuild.insert(pos+1, sstring);
if(!undo){
undoStack.push(new UndoMethod(sstring, sstring.length(), pos+1, 2));
}
}
public void delete(int pos, int count) {
// TODO Auto-generated method stub
stringBuild.delete(pos, (pos+count));
if(!undo){
undoStack.push(new UndoMethod(stringBuild.substring(pos, pos+count), count, pos-1,1));
}
}
public void undo() {
// TODO Auto-generated method stub
UndoMethod temp = undoStack.pop();
undo = true;
if(temp.getAction() == 1){
insert(temp.getPos(), temp.getString());
}
if(temp.getAction() == 2){
delete(temp.getPos(), temp.getCount());
}
undo = false;
}
}
My UndoMethod class:
public class UndoMethod {
private String ssString;
int count;
int pos;
int action;
public UndoMethod(){
ssString = "";
count = 0;
pos = 0;
action = 0;
}
public UndoMethod(String SSString, int Count, int Position, int Action){
ssString = SSString;
count = Count;
pos = Position;
action = Action;
}
public String getString(){
return ssString;
}
public void setString(String SSString){
ssString = SSString;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
}
My output:
Enter an action
1
Enter the position (begin counting at 0) of the letter after which to insert
19
Enter the string to insert
I am doing great!
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String >index out of range: 20
at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:1005)
at java.lang.StringBuilder.insert(StringBuilder.java:291)
at SmartString.insert(SmartString.java:20)
at SmartStringDriver.main(SmartStringDriver.java:38)
And for reference, the driver class, which should be good:
public static void main(String[] args) {
//Declare variables and objects
Scanner scan = new Scanner(System.in);
int action = 1, start = 0, count = 0;
String menu = "\n(1) insert\n(2) delete\n(3) Undo\n(4) Quit";
SmartString str;
String insertS = "";
System.out.println("Enter your initial Smart String:");
str = new SmartString(scan.nextLine());
try{
do{
//Prompt for an action - Insert, Delete, Undo, Quit
System.out.println("Your smart string is: \n\t" + str + " \n\t(indexing from 0 to " + (str.toString().length()-1) + " - length of " + str.toString().length() + ")");
System.out.println(menu);
System.out.println("Enter an action");
action = scan.nextInt();
scan.nextLine();
//Determine which action and prompt for necessary input
switch (action) {
case 1:
System.out.println("Enter the position (begin counting at 0) of the letter after which to insert " + insertS);
start = scan.nextInt();
scan.nextLine();
System.out.println("Enter the string to insert");
insertS = scan.nextLine();
//Invoke SmartString insert method
str.insert(start, insertS);
break;
case 2:
System.out.println("Enter the position (begin counting at 0) of the first letter to delete");
start = scan.nextInt();
System.out.println("Enter the number of letters to delete (count)");
count = scan.nextInt();
//Invoke SmartString delete method
str.delete(start, count);
break;
case 3:
//Invoke SmartString undo method
str.undo();
break;
}
}while (action != 4);
}
catch(InputMismatchException e) {
System.out.println("Entry must be numeric!");
}
System.out.println("\n Your final Smart String is " + str);
}
}
EDIT: Also, here's the SmartStringADT:
public interface SmartStringADT {
public void insert(int pos, String sstring);
public void delete(int pos, int count);
public void undo();
public String toString();
}
Question:
How do I update numberOfWins in the db as the program runs(rounds of poker are played), & at the end of program execution, display the data in/from my db?
Background:
This is a fairly standard console based poker game. Table is a dealer(creates hands) & executes rounds. PokerGameMain, the main. I also have classes for Card, Deck, Player, Wallet. 3 players are dealt cards, creating a hand, the hands are played, there is a winner & looser, this is a round. I have included my current code on these classes for context.
My questions are about two database/JDBC/SQLite classes(SQLiteJDBC, Database) I am attempting to implement. I've added these solely for learning purposes. I'm attempting to gain knowledge of database/JDBC/SQLite & maven(which I have used to manage my SQLite dependency).
I've working pretty diligently at this program but I'm having a little trouble seeing how to pull it together.
Question Again:
Primary) How do I:
Create a db(poker)...done I think.
Create a table(players), with 2 columns(palyerName, numberOfWins)...done I think.
Create 3 rows(player1-3)...done I think.
Update numberOfWins in the db as the program runs(rounds of poker are played), & at the end of program execution, display the data in my db
Secondary) Suggestions regarding:
My exception handling & design in SQLiteJDBC & Database
SQLiteJDBC
Note:
The only errors in the program that I know of are an unchecked exception & a can not resolve method. Both in SQLiteJDBC, here & here:
try {
db.execute(dropTable);
db.execute(createTable);
db.execute(insertInto1);
db.execute(insertInto2);
db.execute(insertInto3);
ResultSet resultSets = db.executeQuery(selectFrom);
try {
while (resultSets.next()) {
// read the result set
System.out.println("player = " + resultSets.getString("playerName"));
System.out.println("number of wins = " + resultSets.getInt("numberOfWins"));
}
}
try {
db.close();
}
package com.craigreedwilliams.utilities;
import java.sql.*;
/**
* Created by Reed on 7/10/2015.
*/
public class SQLiteJDBC {
public static void passQuery() {
String dropTable = "DROP TABLE if EXISTS players";
String createTable = "CREATE TABLE players(VARCHAR(25) playerName, INTEGER numberOfWins)";
String insertInto1 = "INSERT INTO player1 VALUES ('player1', 0)";
String insertInto2 = "INSERT INTO player2 VALUES ('player2', 0)";
String insertInto3 = "INSERT INTO player3 VALUES ('player3', 0)";
String selectFrom = "SELECT * FROM players";
// Url for SqlLite
String jdbcDbType = "jdbc:sqlite";
String dbName = "poker.db";
String dbUrl = jdbcDbType + ":" + dbName;
Database db = new Database(dbUrl);
try {
db.execute(dropTable);
db.execute(createTable);
db.execute(insertInto1);
db.execute(insertInto2);
db.execute(insertInto3);
ResultSet resultSets = db.executeQuery(selectFrom);
try {
while (resultSets.next()) {
// read the result set
System.out.println("player = " + resultSets.getString("playerName"));
System.out.println("number of wins = " + resultSets.getInt("numberOfWins"));
}
}
finally {
try {
resultSets.close();
}
catch (Exception ignore) {
}
}
}
finally {
try {
db.close();
}
catch (Exception ignore) {
}
}
}
}
Database
package com.craigreedwilliams.utilities;
import java.sql.*;
/**
* Created by Reed on 7/10/2015.
*/
public class Database {
public String dbUrl;
private String sqliteDriver = "org.sqlite.JDBC";
private String driver;
private Connection connection = null;
private Statement statement = null;
public Database() {
}
public Database(String dbUrl) {
this.dbUrl = dbUrl;
// sqliteDriver = getDriverString(dbUrl);
try {
setConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setConnection() throws Exception {
try {
// registered DriverName using the current class loader
Class.forName(sqliteDriver);
}
catch (Exception e) {
// connection failed
System.out.println("DriverName: " + driver + " was not available");
System.err.println(e);
throw e;
}
// create a database connection
connection = DriverManager.getConnection(dbUrl);
try {
statement = connection.createStatement();
}
catch (Exception e) {
try {
connection.close();
}
catch (Exception ignore) {
}
connection = null;
}
}
// this method should undoubtedly be public as we'll want to call this
// to close connections externally to the class
public void closeConnection() {
if (statement!=null) {
try {
statement.close();
}
catch (Exception ignore) {
}
}
if (connection!=null) {
try {
connection.close();
}
catch (Exception ignore) {
}
}
}
// and we will definitely want to be able to call the following two
// functions externally since they expose the database
// behaviour which we are trying to access
public ResultSet executeQuery(String query) throws SQLException {
return statement.executeQuery(query);
}
public void execute(String query) throws SQLException {
statement.executeUpdate(query);
}
}
PokerGameMain
package com.craigreedwilliams.game;
import java.util.Scanner;
/**
* Hello world!
*
*/
public class PokerGameMain
{
public static void main(String[] args) {
//Input Object of the scanner class
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to Poker Table! May the odds forever be in your favor :)");
do {
printMainGameWelcomeMenu();
choice = input.nextInt();
switch (choice){
case 1:
//call start game method or class here
startGame();
break;
case 2:
//end game here
printMainGameGoodbyeMessage();
break;
default:
System.out.println("The value you entered is outside of the range required for this application...");
}
} while (choice != 2);
}
public static void printMainGameWelcomeMenu(){
System.out.println("This is the poker game's menu: \n"
+ "To start the game enter: 1\n"
+ "To end game enter: 2\n");
}
public static void printMainGameGoodbyeMessage(){
System.out.println("Thank you for playing the poker game! Hope you enjoyed your experience. Have a great day! :D");
}
public static void startGame(){
int count = 1;
Table table = new Table();
getUserInput(table);
while (count < 4) {
System.out.println("Round : " + count + "...\n");
table.dealCards();
table.showCards();
count++;
}
}
public static void getUserInput(Table table){
Scanner usrInput = new Scanner(System.in);
boolean anteSet = false;
System.out.println("Before the game starts, I will need some information...\n");
System.out.println("What is your name?");
String name = usrInput.nextLine();
//set player name
table.getPlayerAt(0).setPlayerName(name);
// set ante
do {
System.out.println("How much are you willing to bet for every round? Keep in mind there will have to be at least three rounds...");
Double ante = usrInput.nextDouble();
if(checkAnte(ante, table.getPlayerAt(0).getWallet())) {
table.getPlayerAt(0).setAnteValue(ante);
anteSet = true;
}
}while (!(anteSet));
}
public static boolean checkAnte(double ante, Wallet wallet){
if (ante * 3.0 > wallet.getBalance()) {
System.out.println("Sorry your wallet balance is less than you think...Please reconsider the ante value");
return false;
}
else
{
wallet.deductFromBalance(ante);
System.out.println("Your ante for each round is set to be: " + ante + ". Good luck!");
return true;
}
}
}
Table
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Table {
// two private attributes
private Player[] players;
private Deck deck;
private double pot;
private Player winner;
/******************************************
** The array is set in the following way:
******************************************
** pairs are each given 1 point **
** three of a kind are given 3 points **
** straights are given 5 points **
** flush are given 7 points **
** four of a kind are given 8 points **
** royal straights are given 10 points **
** royal flush are given 12 points **
******************************************
*/
private int[][] game = new int [7][2];
// constructor initializes the deck and cards
public Table() {
deck = new Deck();
players = new Player[3];
players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
deck.shuffle();
}
// getter for player at the given index
public Player getPlayerAt(int index){
return players[index];
}
// deals the card to each player
public void dealCards() {
int count = 0;
for (int i = 0; i < players[0].getCards().length; i++) {
for (int j = 0; j < players.length; j++) {
players[j].setCardAtIndex(deck.getCard(count++), i);
}
}
}
// simulates the game and shows the result
public void showCards() {
for (int i = 0; i < players.length; i++) {
System.out.print("Player " + (i + 1) + ": \n");
for (int j = 0; j < players[0].getCards().length; j++) {
System.out.println("{" + players[i].getCardAtIndex(j).toString() + "} ");
}
if(players[i].countPair() > 0) {
System.out.println("Pair(S):" + players[i].countPair() + "! \n");
game[0][i] += players[i].countPair();
}
if(players[i].isFlush()) {
System.out.println("Flush! ");
}
if(players[i].isRoyalFlush())
System.out.println("Royal Flush!!\n");
if(players[i].isThreeOfAkind())
System.out.println("Three of a kind! ");
if(players[i].isFourOfAkind())
System.out.println("Four of a kind!!\n");
if(players[i].isStraight())
System.out.println("Straight! \n");
if(players[i].isRoyalStraight())
System.out.println("Royal Straight!!\n");
else
System.out.print("\n");
}
}
}
Wallet
package com.craigreedwilliams.game;
import java.util.Random;
/**
* Created by Reed on 7/11/2015.
*/
public class Wallet {
private double balance;
/**
* default Wallet constructor
*/
public Wallet() {
setRandomStartingBalance(50.0, 500.0);
}
private void setRandomStartingBalance(double minimum, double maximum) {
Random random = new Random();
double randomStartingBalance = minimum + (maximum - minimum) * random.nextDouble();
balance = randomStartingBalance;
}
public double getBalance() {
return balance;
}
public void deductFromBalance(double price) {
this.balance = balance - price;
}
}
Player
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Player {
private final static int MAX = 5;
private Card cards[]; //hand
private Deck tempDeck = new Deck();
private Double anteValue = 0.0;
private Wallet wallet;
private String playerName = "";
int gamesWon = 0;
// private bools for checks
private boolean pair = false;
private boolean threeOfAkind = false;
private boolean fourOfAkind = false;
private boolean royalStraight = false;
private boolean royalFlush = false;
//constructor initializes 5 cards in each hand
public Player() {
cards = new Card[MAX];
wallet = new Wallet();
}
// getters are setters for name and ante value
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public Double getAnteValue() {
return anteValue;
}
public void setAnteValue(Double anteValue) {
this.anteValue = anteValue;
}
// getter for wallet for player object
public Wallet getWallet() {
return wallet;
}
// getter and setter for games won so far...
public int getGamesWon() {
return gamesWon;
}
public void setGamesWon(int gamesWon) {
this.gamesWon = gamesWon;
}
//returns all the cards in hand
public Card[] getCards() {
return cards;
}
//get the cards at a particular position
public Card getCardAtIndex(int index) {
return (index >= 0 && index < MAX) ? cards[index] : null;
}
//sets the card at particular position
public void setCardAtIndex(Card c, int index) {
if(index >= 0 && index < MAX)
cards[index] = c;
}
// basic bool return functions
public boolean isRoyalStraight() {
return royalStraight;
}
public boolean isThreeOfAkind() {
return threeOfAkind;
}
public boolean isFourOfAkind() {
return fourOfAkind;
}
public boolean isRoyalFlush() {
return royalFlush;
}
//Main Logic here : public functions that check for all winning hands and change private boolean variables
// appropriately
//counts number of matched pair
public int countPair() {
int count = 0;
//boolean pairCheck = ((!(threeOfAkind) && (!(fourOfAkind))));
for (int i = 0; i < cards.length; i++) {
for (int j = i + 1; j < cards.length; j++)
{
if (cards[i].getRank().equals(cards[j].getRank())){
count++;
if (count == 1)
pair = true;
else if ((pair) && (count == 3)) {
threeOfAkind = true;
pair = false;
}
else if ((threeOfAkind) && (count == 4)) {
fourOfAkind = true;
threeOfAkind = false;
}
}
}
}
return (pair) ? count : 0;
}
//checks if it is a flush or not i.e all five cards of same suit also checks for royal flush
public boolean isFlush()
{
int count = 0;
for (int i = 0; i < cards.length; i++) {
for (int j = i + 1; j < cards.length; j++) {
if (cards[i].getSuit().equals(cards[j].getSuit())) {
count++;
}
}
if (count == 5){
if (cards[i].getRankInt() == tempDeck.getRankInt(12))
royalFlush = true;
}
}
return ((count == 5) && (!(royalFlush))) ? true : false;
}
//checks to see if it is a straight or royal straight or neither
public boolean isStraight(){
int count = 0;
for (int i = 0; i < cards.length - 1; i++){
if ((cards[i].getRankInt() + 1 == cards[i + 1].getRankInt()) && (count < 4)){
count++;
}
else if (count == 4){
if (cards[i].getRankInt() == tempDeck.getRankInt(13)){
royalStraight = true;
}
}
}
return ((count == 4) && (!(royalStraight))) ? true : false;
}
}
Deck
package com.craigreedwilliams.game;
import java.util.Calendar;
import java.util.Random;
/**
* Created by Reed on 7/10/2015.
*/
public class Deck {
private final String rank[] = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King", "Ace"};
private final String suits[]={"Hearts","Diamonds","Clubs","Spades"};
private final int rankInt[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
private final int suitsInt[] = {1, 2, 3, 4};
private Card deck[];
private final int MAX = 52;
private Random randNum;
//makes the deck, constructor - no arguments
public Deck() {
deck = new Card[MAX];
//uses calendar object to get time stamp
Calendar cal = Calendar.getInstance();
long seed = cal.getTimeInMillis();
randNum = new Random(seed); // random generated using time seed
// uses modulus operator
for(int i = 0; i < deck.length; i++ ){
deck[i] = new Card( rank[i % 13], suits[i / 13], rankInt[i % 13], suitsInt[i / 13]);
}
}
//shuffles the deck
public void shuffle(){
for(int i = 0; i < deck.length; i++ ){
int j = randNum.nextInt(MAX);
Card c = deck[i];
deck[i] = deck[j];
deck[j] = c;
}
}
//returns the individual card in the deck
public Card getCard(int index){
return deck[index];
}
//returns rankInt from the deck object at the given index value
public int getRankInt(int index) {
return rankInt[index];
}
}
Card
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Card {
private String rank;
private String suit;
private int rankInt;
// TODO: remove this if actually never used
private int suitInt;
//four argument constructor initializes Cards rank and suit (stings and ints)
public Card(String rank, String suit, int rankInt, int suitInt) {
super();
this.rank = rank;
this.suit = suit;
this.rankInt = rankInt;
this.suitInt = suitInt;
}
//getter method to return the rank value
public String getRank() {
return rank;
}
//getter method to return the suit value
public String getSuit() {
return suit;
}
//setter method to initialize the suit
public int getRankInt() {
return rankInt;
}
//return String representation of Card object
public String toString() {
return rank + " : " + suit;
}
}
Your SQL query should look like this:
Select Player,Wins From yourtable Set Wins=Wins + 1 Where Player=playerid
The columns are just examples because I don't know how you called them ;)
And at the end of each round you just need to query your SQL-Server.