A bubble sort for string. java - java

This is my first time to write a bubble sort for string and apparently i got many errors and the program could not run. I have no idea how to solve it. my code is:
import java.util.*;
public class SortingRecord{
public static void main(String args[]){
Scanner kb = new Scanner(System.in);
System.out.println("How many people?");
int n = Integer.parseInt(kb.nextLine());
Record[] records = new Record[n];
for(int i = 0; i<n; i++){
System.out.println("Inputting record["+i+"]:");
System.out.print("Please input <First Name>:");
String firstName = kb.nextLine();
System.out.println("Please input <Last Name>:");
String lastName = kb.nextLine();
records[i] = new Record(firstName, lastName);
}
sort(records);
System.out.println("----------------");
System.out.println("Print name in dictinary order:");
for(int i = 0; i < n ; i++)
System.out.println();
}
public static void sort(Record[] records){
if (records == null || records.length <= 1) return;
int n = records.length;
for(int i = 0; i< records.length ; i++){
for(int j = i+1 ; j< records.length; j++){
The symbol method compareTo(Record) couldn't be found.
if(records[j] .compareTo(records[i]) < 0){
It said Record cannot be converted to java.lang.String
String temp = records[i];
records[i] = records[j];
records[j] = temp;
}
}
System.out.println(records[i]);
}
}
}
class Record{
public String firstName = "";
public String lastName = "";
public Record(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}

Let's take a look at the obvious error:
if (records[j].compareTo(records[i]) < 0) {
Record does not provide any compareTo method, so you can't call it - it doesn't exist.
The next error:
String temp = records[i];
Is because Record is not a type of String, so it can't be assigned, the obvious solution is to use Record instead, something like...
Record temp = records[i];
records[i] = records[j];
records[j] = temp;
Okay, but how do we fix the compareTo issue? This is more complicated than it might sound, while you implement the Comparable interface (or just implement the compareTo method directly), I'd not choose this path. Why? Because you might want to change the way in which you sort the records and implementing the method would lock you into a single use case.
Instead, I'd use a Comparator passed into the method to do the actual comparison, providing the caller with the flexibility to change how the comparison actually works
public static void sort(Record[] records, Comparator<Record> comparator) {
if (records == null || records.length <= 1) {
return;
}
int n = records.length;
for (int i = 0; i < records.length; i++) {
for (int j = i + 1; j < records.length; j++) {
if (comparator.compare(records[j], records[i]) < 0) {
Record temp = records[i];
records[i] = records[j];
records[j] = temp;
}
}
System.out.println(records[i]);
}
}
Then you could do something like...
sort(records, new Comparator<Record>() {
#Override
public int compare(Record o1, Record o2) {
return o1.firstName.compareTo(o2.firstName);
}
});
or
sort(records, new Comparator<Record>() {
#Override
public int compare(Record o1, Record o2) {
return o1.lastName.compareTo(o2.lastName);
}
});
or even
sort(records, new Comparator<Record>() {
#Override
public int compare(Record o1, Record o2) {
int compare = o1.firstName.compareTo(o2.firstName);
if (compare == 0) {
compare = o1.lastName.compareTo(o2.lastName);
}
return compare;
}
});
Or what ever else combination you might need to meet your requirements
I would suggest having a look at Comparator for more details
I should also point out that you could use Collections to also so the objects, but you'll need to convert it to List instead of array...
Collections.sort(Arrays.asList(records), new Comparator<Record>() {...});
the program fail to output the name in dictionary order;(
Works fine for me...
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
Record[] records = new Record[] {
new Record("B", "B"),
new Record("C", "B"),
new Record("D", "B"),
new Record("A", "E"),
new Record("A", "B"),
new Record("A", "C"),
new Record("A", "A"),
};
sort(records, new Comparator<Record>() {
#Override
public int compare(Record o1, Record o2) {
int compare = o1.firstName.compareTo(o2.firstName);
if (compare == 0) {
compare = o1.lastName.compareTo(o2.lastName);
}
return compare;
}
});
for (Record record : records) {
System.out.println(record);
}
}
public static void sort(Record[] records, Comparator<Record> comparator) {
if (records == null || records.length <= 1) {
return;
}
for (int i = 0; i < records.length; i++) {
for (int j = i + 1; j < records.length; j++) {
if (comparator.compare(records[j], records[i]) < 0) {
Record temp = records[i];
records[i] = records[j];
records[j] = temp;
}
}
}
}
class Record {
public String firstName = "";
public String lastName = "";
public Record(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
}
Outputs
A A
A B
A C
A E
B B
C B
D B

You don't have compareTo method in Record class so that's why it's not found :) You probably should implement Comparable interface.
As to "Record cannot be converted to java.lang.String", use toString method and you will be able to convert it, although you probably want to override toString.
Please also take a look at this example:
Why should a Java class implement comparable?

Related

How to return the Objects of an ArrayList on separate lines

I have created a program that sorts trading cards and places them in a collection that is then compared to other collections to look for duplicates. I have had no problems up until my final toString method. My issue is that I cannot seem to get the return statement to separate the various cards onto their own separate lines.
instead of Alan Turing, Grace Hopper, Ada Lovelace, I need:
Alan Turing
Grace Hopper
Ada Lovelace
Below is a copy of my code. I am fairly new to java so I apologize for any lack of knowledge pertaining to methods specific to this, but I have only found ones using System.out.println, and not mentioning return in any way. My problem lies in the method defined by **. I appreciate any and all help and am sorry if this question is not 100% clear. (I have tried my own research to no avail!)
// First Class
public class Card implements Comparable<Card> {
private String name;
private String nationality;
private int yearBorn;
private int yearDied;
public Card(String name, String nationality, int yearBorn, int yearDied) {
this.name=name;
this.nationality=nationality;
this.yearBorn=yearBorn;
this.yearDied=yearDied;
}
public int compareTo(Card c) {
if (this.name.equals(c.name)) return 0;
else if (this.name.compareTo(c.name)>0) return 1;
else return -1;
}
public String toString() {
return String.format("%s (%d - %d) - %s", name, yearBorn, yearDied, nationality);
}
}
// Second Class
import java.util.ArrayList;
import java.util.List;
public class CardCollection {
private String owner;
private List<Card> myCollection;
public CardCollection(String owner) {
this.owner = owner;
this.myCollection = new ArrayList<>();
}
public boolean addCard(Card c) {
int p = 0;
while (p < myCollection.size()) {
int q = myCollection.get(p).compareTo(c);
if (q == 0) {
return false;
} else if (q > 0) {
myCollection.add(p, c);
return true;
}
p++;
}
myCollection.add(c);
return true;
}
public void removeCard(int r) {
myCollection.remove(r);
}
public int getSize() {
return myCollection.size();
}
public ArrayList<Card> mergeCollections(CardCollection cc) {
ArrayList<Card> dupes = new ArrayList<>();
while (cc.getSize() > 0) {
Card c = cc.myCollection.remove(0);
if (myCollection.contains(c)) {
dupes.add(c);
}
else myCollection.add(c);
}
return dupes;
}
**public String toString() {
String s = "";
for (int i = 0; i < owner.length(); i++) {
s += "-";
}
return String.format("%s\n%s\n%s\n", owner, s, myCollection);**
}
}
// Runner Class
import java.util.ArrayList;
public class CCRunner {
public static void main(String[] args) {
CardCollection c1 = new CardCollection("Alan");
CardCollection c2 = new CardCollection("Grace");
Card turing = new Card("Alan Turing","British",1912,1954);
Card hopper = new Card("Grace Hopper","American",1906,1992);
Card vonneumann = new Card("John Von Neumann","Hungarian",1903,1957);
Card shannon = new Card("Claude Shannon","American",1916,2001);
Card johnson = new Card("Katherine Johnson","American",1918,-1);
Card lovelace = new Card("Ada Lovelace","British",1815,1852);
Card cerf = new Card("Vint Cerf","American",1943,-1);
Card brin = new Card("Sergey Brin","Russian",1973,-1);
c1.addCard(turing);
c1.addCard(vonneumann);
c1.addCard(shannon);
c1.addCard(johnson);
c1.addCard(cerf);
c1.addCard(brin);
c2.addCard(cerf);
c2.addCard(lovelace);
c2.addCard(johnson);
c2.addCard(vonneumann);
c2.addCard(hopper);
System.out.println(c1);
System.out.println(c2);
ArrayList<Card> dupes = c1.mergeCollections(c2);
System.out.println(c1);
System.out.println(c2);
System.out.println("Duplicates:\n-----------");
for (Card c : dupes) {
System.out.println(c);
}
}
}
This is run in a separate class, but I don't think it will elucidate my problem to include it. Let me know if I am wrong.
You can either change your implementation of toString() of your CardCollection class. Examples:
Loop again, this time over the List:
public final String toString() {
String s = "";
for (int i = 0; i < owner.length(); i++) {
s += "-";
}
for (int i = 0; i < myCollection.size(); i++) {
s += "\n" + myCollection.get(i);
}
return String.format("%s\n%s\n", owner, s);
}
Using a stream (requires an additional import java.util.stream.Collectors;):
public final String toString() {
String s = "";
for (int i = 0; i < owner.length(); i++) {
s += "-";
}
return String.format("%s\n%s\n%s\n",
owner,
s,
myCollection.stream()
.map(Card::toString)
.collect(Collectors.joining("\n")));
}
Or you can #Override the toString() method of the ArrayList, also in your CardCollection class. Example:
this.myCollection = new ArrayList<>(){
#Override
public String toString(){
String s = "";
if (size() > 0) s = get(0).toString();
for (int i = 1; i < size(); i++) {
s += "\n" + get(i).toString();
}
return s;
}
};
All examples will result in this for Alan (before the merge):
Alan
----
Alan Turing (1912 - 1954) - British
Claude Shannon (1916 - 2001) - American
John Von Neumann (1903 - 1957) - Hungarian
Katherine Johnson (1918 - -1) - American
Sergey Brin (1973 - -1) - Russian
Vint Cerf (1943 - -1) - American
Note: I'd personally go with changing the implementation of toString() of the CardCollection class. I would also perfer the way tquadrat did it in their answer. The overriding of ArrayList looks to messy in my opinion, and keeping the stringrepresentation in the toString() method makes more sense to me.
Try this as a replacement to the marked toString() implementation:
…
public final String toString()
{
var s = "-".repeat( owner.length() );
var joiner = new StringJoiner( "\n", String.format( "%s%n%s%n", owner, s ), "" );
for( var c : myCollection ) joiner.add( c.toString() );
var retValue = joiner.toString();
return retValue;
}
Basically, the output would look like this:
<owner>
-------
<collectible1>
<collectible2>
<…>
If you are using a Java version before Java 11, you may need to replace var with the respective types.

Compare Lists in ArrayList

I have a text file containing the following strings (which are versions of a software):
1_10_2_0_154
3_10_5_2_10
2_10_4_1
3_10_5_1_37
I'm trying to find the most recent version, in this case 3_10_5_2_10 is the version that I'm trying to display using java.
For the moment, here is my code:
BufferedReader br;
String version;
ArrayList<List<Integer>> array = new ArrayList<List<Integer>>();
List<Integer> liste = new ArrayList<Integer>();
try{
br = new BufferedReader(new FileReader(new File(FILEPATH)));
while((version= br.readLine()) != null)
{
liste = Arrays.asList(version.split("_")).stream().
map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
array.add(liste);
}
for(int i = 0; i < array.size(); i++)
{
for (List l: array)
{
Object z = l.get(i);
List<Object> listes = new ArrayList<Object>();
listes.add(z);
System.out.println(listes);
}
}
br.close();
System.out.println(array);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
I made a loop to save strings to ArrayList> like:
[[1,10,2,0,154] , [3,10,5,2,10], [2,10,4,1], [3,10,5,1,37]]
I want to get the elements of each list and compare them to find the most biggest one (most recent one) but I don't know to do that..
I sugguest you a object approach, define a class named Version with compareTo method, then using method sort on Collections class you can simply sort your versions.
Advantages
Clean and Clear code
Data validation
Main:
public class Main {
public static void main(String[] args){
List<Version> versions = Arrays.asList(
Version.create("1_10_2_0_154"),
Version.create("3_10_5_2_10"),
Version.create("2_10_4_1_49"),
Version.create("3_10_5_1_37"));
versions.sort(Version::compareTo);
System.out.println(versions.get(0).toString());
}
}
Version:
public class Version implements Comparable<Version> {
private final int major;
private final int minor;
private final int bug;
private final int release;
private final int build;
public Version(int major, int minor, int bug, int release, int build) {
this.major = major;
this.minor = minor;
this.bug = bug;
this.release = release;
this.build = build;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getBug() {
return bug;
}
public int getRelease() {
return release;
}
public int getBuild() {
return build;
}
#Override
public String toString() {
return "Version{" +
"major=" + major +
", minor=" + minor +
", bug=" + bug +
", release=" + release +
", build=" + build +
'}';
}
public static Version create(String value){
String[] splitRes = value.split("_");
List<Integer> intValues = new ArrayList<>();
for(String v : splitRes){
intValues.add(Integer.parseInt(v));
}
return create(intValues);
}
public static Version create(List<Integer> values){
if(Objects.requireNonNull(values).size() < 5)
throw new IllegalArgumentException();
return new Version(
values.get(0),
values.get(1),
values.get(2),
values.get(3),
values.get(4)
);
}
#Override
public int compareTo(Version that) {
if (this.major > that.major) {
return -1;
} else if (this.major < that.major) {
return 1;
}
if (this.minor > that.minor) {
return -1;
} else if (this.minor < that.minor) {
return 1;
}
if (this.bug > that.bug) {
return -1;
} else if (this.bug < that.bug) {
return 1;
}
if (this.release > that.release) {
return -1;
} else if (this.release < that.release) {
return 1;
}
if (this.build > that.build) {
return -1;
} else if (this.build < that.build) {
return 1;
}
return 0;
}
}
UPDATE 1
As suggested by #Henrik i updated the list sorting with a Java 8 approach.
UPDATE 2
I reversed the compareTo method so now you can simply do plain sort calling sort method on list and passing method reference Version::compareTo
UPDATE 3
A more dynamic solution for Version class:
public class Version implements Comparable<Version> {
private final List<Integer> values;
public Version(List<Integer> values) {
this.values = values;
}
public List<Integer> getValues() {
return values;
}
#Override
public String toString() {
return String.join("_", values
.stream()
.map(Object::toString)
.collect(Collectors.toList()));
}
#Override
public int compareTo(Version that) {
List<Integer> thatValues = that.getValues();
for(int index = 0; index < values.size(); index++){
Integer value = values.get(index);
Integer thatValue = thatValues.get(index);
if (value > thatValue) {
return -1;
} else if (value < thatValue) {
return 1;
}
}
return 0;
}
public static Version create(String value){
String[] splitRes = value.split("_");
List<Integer> intValues = new ArrayList<>();
for(String v : splitRes){
intValues.add(Integer.parseInt(v));
}
return new Version(intValues);
}
}
You can write a Comparator to compare two Lists
Comparator<List<Integer>> comparator = (list1, list2) -> {
Iterator<Integer> iteratorA = list1.iterator();
Iterator<Integer> iteratorB = list2.iterator();
//It iterates through each list looking for an int that is not equal to determine which one precedes the other
while (iteratorA.hasNext() && iteratorB.hasNext()) {
int elementA = iteratorA.next();
int elementB = iteratorB.next();
if (elementA > elementB) {
return 1;
} else if (elementA < elementB) {
return -1;
}
}
//All elements seen so far are equal. Use the list size to decide
return iteratorA.hasNext() ? 1 : iteratorB.hasNext() ? -1 : 0;
};
You can sort it as
Collections.sort(list, comparator);
EDIT: You can refer to David Geirola's answer to convert the version string as a POJO and move the comparator logic inside that. But that is highly tied/coupled to the input string format. My solution works for any List<List<Integer>>.
A simple object oriented approach would be to create object, representing version number, let's call it VersionNumber, which would have a constructor of a factory method that does the parsing of the string. This VersionNumber class should implement interface Comparable and implement method compareTo.
Here is a hint for using Comparable Why should a Java class implement comparable?
Then you can easily write an algorithm to find the max version or google some library that would do it for you.
It is not optimized but should work. You can use both of comparators.
static List<String> versions = Arrays.asList(
"1_10_2_0_154",
"3_10_5_2_10",
"2_10_4_1_49",
"3_10_5_1_37");
static Comparator<List<Integer>> c = (o1,o2) -> {
int length = o1.size()>o2.size()?o2.size():o1.size();
for (int i = 0; i < length; i++) {
int i1 = o1.get(i);
int i2 = o2.get(i);
if (i1 != i2)
return i1 - i2;
}
return 0;
};
static Comparator<List<Integer>> c2 = (o1,o2) -> {
Iterator<Integer> i1=o1.iterator();
Iterator<Integer> i2=o2.iterator();
while (i1.hasNext() && i2.hasNext()){
int i = i1.next()-i2.next();
if (i!=0) return i;
}
return 0;
};
static Optional<List<Integer>> getTheMostRecentVersion(List<String> versions) {
return versions.stream().
map(s -> Arrays.stream(s.split("_")).
map(Integer::parseInt).
collect(Collectors.toList())).max(c2);
}
I think that this text file could be very big and it is better to compare each line on the fly (instead of store all line into collection to sort it after):
public static String getMostRecentVersion(BufferedReader in) throws IOException {
final Comparator<String[]> version = (s1, s2) -> {
int res = 0;
for (int i = 0; i < 5 && res == 0; i++)
res = Integer.compare(Integer.parseInt(s1[i]), Integer.parseInt(s2[i]));
return res;
};
String str;
String resStr = null;
String[] resPparts = null;
while ((str = in.readLine()) != null) {
String[] parts = str.split("_");
if (resStr == null || version.compare(parts, resPparts) > 0) {
resStr = str;
resPparts = parts;
}
}
return resStr;
}
A general ListComparator should help.
static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
#Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.max(o1.size(), o2.size()); i++) {
int diff =
// Off the end of both - same.
i >= o1.size() && i >= o2.size() ? 0
// Off the end of 1 - the other is greater.
: i >= o1.size() ? -1
: i >= o2.size() ? 1
// Normal diff.
: o1.get(i).compareTo(o2.get(i));
if (diff != 0) {
return diff;
}
}
return 0;
}
}
private static final Comparator<List<Integer>> BY_VERSION = new ListComparator<Integer>().reversed();
public void test(String[] args) {
String[] tests = {
"1_10_2_0_154",
"3_10_5_2_10",
"2_10_4_1_49",
"3_10_5_1_37",
"3_10_5_1_37_0"
};
System.out.println("Before: " + Arrays.toString(tests));
System.out.println("After: " + Arrays.stream(tests)
// Split into parts.
.map(s -> s.split("_"))
// Map String[] to List<Integer>
.map(a -> Arrays.stream(a).map(s -> Integer.valueOf(s)).collect(Collectors.toList()))
// Sort it.
.sorted(BY_VERSION)
// Back to a new list.
.collect(Collectors.toList()));
}
slap your arrays together into a number then just do number comparison.
class Scratch
{
public static void main(String[] args)
{
List<List<Integer>> arr = new ArrayList<>();
arr.add(fromArray(new Integer[]{1,10,2,0,154}));
arr.add(fromArray(new Integer[]{3,10,5,2,10}));
arr.add(fromArray(new Integer[]{2,10,4,1,49}));
arr.add(fromArray(new Integer[]{3,10,5,1,37}));
Integer[] maxLengths = {0,0,0,0,0};
for (List<Integer> v : arr)
{
for(int idx = 0; idx < v.size(); idx++)
{
Integer n = v.get(idx);
int curMaxLen = maxLengths[idx];
maxLengths[idx] = Math.max(n.toString().length(), curMaxLen);
}
}
Long largest = arr.stream().map(v -> {
StringBuilder result = new StringBuilder();
for(int idx = 0; idx < v.size(); idx++)
{
Integer n = v.get(idx);
int maxLen = maxLengths[idx];
result.append(String.format("%-" + maxLen + 's', n).replace(' ', '0'));
}
return result.toString();
}).map(Long::valueOf).max(Comparator.naturalOrder()).get();
System.out.println(largest);
}
public static List<Integer> fromArray(Integer[] array)
{
List<Integer> list = new ArrayList<>();
Collections.addAll(list, array);
return list;
}
}

Reading from keyboard to build a relationship between objects

I want to create an object named "Course", and get the information from the keyboard. The last attribute called the "pre", which means the prerequisite courses of this course. I want to input the whole information in one line and extract the information for each attribute. But I got the problem with"pre". I run the program and the output of course.pre is null. I do not know why. Here is my Course class code:
`import java.util.HashSet;
public class Course{
private String name;
private int isFall;
private int NumPre;
private HashSet<Course> pre;
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String setName (String n){
return name = n;
}
// 1 - fall 0 - both -1 - spring
public void setType(String isFall) {
if(isFall.equals("F") || isFall.equals("f")){
this.isFall = 1;
}else if(isFall.equals("S") || isFall.equals("s")){
this.isFall = -1;
}else if(isFall.equals("B") || isFall.equals("b")){
this.isFall = 0;
}
}
public int getType(){
return isFall;
}
public void SetNumPre(int n) {
this.NumPre = n;
}
public int getNumPre() {
return NumPre;
}
public void addPre(Course c) {
pre.add(c);
}
public HashSet<Course> getPre() {
return pre;
}
}
`
And here is my main method here:
import java.util.*;
public class TimeToGraduate {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
//System.out.print("Input first two integers here: ");
String globalInfo = scanner.nextLine();
String[] numOfCourse = globalInfo.split(" ");//[0] num of total course [1] max num per semester
int totalNum = Integer.parseInt(numOfCourse[0]);
int maxPre = Integer.parseInt(numOfCourse[1]);
Course courses[] = new Course[totalNum];
//System.out.print("Please input course list here: ");
String coursesList = scanner.nextLine();
String[] nameOfCourse = coursesList.split(" ");
for(int i = 0;i < totalNum; i++){
courses[i] = new Course(nameOfCourse[i]);
}
//System.out.print("Please input course info here: ");
for(int i = 0;i < totalNum; i++){
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
courses[i].setName(infoOfCourse[0]);
courses[i].setType(infoOfCourse[1]);
courses[i].SetNumPre(Integer.parseInt(infoOfCourse[2]));
if(courses[i].getNumPre() > 0){
for(int j = 3; j < 3+(courses[i].getNumPre()); j++){
for(int k = 0; k < totalNum; k++){
if(infoOfCourse[j] == courses[k].getName()){
courses[i].addPre(courses[k]);
}
}
}
}
}
scanner.close();
for(int m = 0; m < totalNum; m++){
System.out.print(courses[m].getName()+" ");
System.out.print(courses[m].getType()+" ");
System.out.print(courses[m].getNumPre()+" ");
System.out.print(courses[m].getPre()+" ");
System.out.println();
}
}
}
Notice that you did not initilize the pre attribute. That is why it is null.
It would be a good practise if you initilize the pre inside a constructor for the Course class. Otherwise, do it when you start filling the Course attributes.
Update:
Your constructor should be like this:
public Course() { this.pre = new HashSet()}
As you can see the constructor does not have any arguements, because you will be filling its attribute from the main function.
You can define a constructor with arguments too:
public Course(String name, HashSet<Course> pre)
{ this.name = name; this.pre = pre; }
But you will need to initilize pre and name when you call it from the main:
...
HashSet hs = new HashSet();
course[i] = new Course('course_name', hs);
....

Iterate through ArrayList

I'm currently trying to iterate through an ArrayList and see if it contains the following numbers I input into the winners array. However, the ticket object won't allow me to utilize the .contains() method which is where I'm getting the error. Any idea on how to work around this?
int[] winners = new int[6];
for(int i = 0; i < winners.length; i++)
{
winners[i] = in.nextInt();
}
in.close();
Scanner scan = new Scanner(file);
ArrayList<Ticket> info = new ArrayList<Ticket>();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
info.add(ticket);
}
**for(Ticket t : info)
{
if(t.contains(winners))
{
System.out.println("Yes");
}
}**
scan.close();
}
**public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}**
You can't use a method that doesn't exist for that class. Since you don't have contains defined for Ticket, I'm not surprised that it isn't working.
From inference, winners is an int[]. In that case, you'd define a new method contains inside of Ticket.
public boolean contains(int[] winningNumbers) {
// logic here
}
Depending on how the winning numbers for a given ticket are stored, and given how you define different conditions of winning, you'd handle your logic here.
If they're stored as an array and you want an exact match, then you can use Arrays.equals for that.
public boolean contains(int[] winningNumbers) {
return Arrays.equals(numbers, winningNumbers);
}
Try this Ticket class with and added contains method:
public class Ticket {
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
public boolean contains(int[] winners) {
for (int i = 0; i < winners.length; i++) {
for (int j = 0; j < tarray.length; j++) {
if (winners[i] == tarray[j])
return true;
}
}
return false;
}
}

how to initialize an array list of type Person

I have created a container List which holds an array of type Person[] . The class SimplepersonDatabase performs add, remove, find, and delete persons. I understand my question might be off topic, but I have spent more than a week on this and I seem not to be getting anywhere.
my question is how can I initialize the container I have just created? I want to be able to perform the functions implemented in SimplePersonDataBase. Thanks for your time. I am really really stuck. Other implement such as an array of type int and type String is very understandable, but I cannot apply the knowledge in creating this
Thanks
class List { // seperate List.java class
int size;
Person[] person;
int next;
public List(){
this.size=100;
this.person = new Person[size];
this.next=0;
}
}
public class Person { // Seperate Person.java class
public String fn;
public String ln;
public Date dob;
public int id;
}
public class SimplePersonDataBase {//Seperate SimplePersonDataBase.java class
public static void go(){
Person person[] = new Person[4];
String[] firstname = { "denis", "cyprian", "ben", "albert" };
String[] lastname = { "Ayuk", "Bisong", "Agbor", "Arrey" };
int[] id = {120, 154, 547, 563 };
for (int i = 0; i < firstname.length; i++) {
person[i] = new Person();
person[i].fn= firstname[i];
person[i].ln= lastname[i];
person[i].dob= new Date();
}
person[3] = new Person();
person[3].fn= firstname[1];
person[3].ln= lastname[1];
person[3].dob= new Date();
person[3].dob= DateFunctions.makeDate(1990, 10, 17);
}
public static boolean add(Person[] person, Person personadd){
}
/*
* This function sorts an array of persons. The sort-criterion is specified by the int
argument and is analogous to the meaning of the int argument in
int compareTo(Person, Person, int)
*/
public static void sort(Person[] a, int opt){
for(int i=1; i<a.length; i++){
for(int j = 0; j < i; j++){
Person temp = new Person();
if(PersonFunctions.compareTo(a[j-1], a[j],opt)> 0){
temp = a[j];
a[j] = a[j+1];
a[j + 1] = temp;
}
}
}
}
public static void swap(Person[] person, int i, int j){
Person tmp = new Person();
if ((j>=0 && j<person.length) && (i>=0 && i<person.length))
tmp = person[j];
person[j] = person[i];
person[i] = tmp;
}
public static int find(Person[] a, String b){
int keyIndex = -1;
for(int i = 0; i<a.length; i++){
if(a[i].ln==b){
keyIndex = i;
}
}
return keyIndex;
}
/*
* Removes the Person with index idx from the list. and returns the removed Person,
or null if idx is out of range.
This function is tricky, because It is not allowed to leave a gap in the array. That
means you have to shift all elements after the removed one.
*/
public static Person remove (Person[] person, int idx){
Person removed = new Person();
if(idx<0 || idx>=person.length){
removed = null;
}
if(person[idx]==null){
removed=null;
}
for (int i = 0; i<person.length; i++){
if(i==idx){
removed = person[i];
}
}
for (int k=idx; k<person.length; k++){
person[k] = person[k+1];
}
return removed;
}
public static void display(Person[] p) {
for (int i = 0; i < p.length; i++)
if (p[i] == null)
System.out.printf(null);
else
TextIO.putf("%s %s %s %s %s\n", i, p[i].id, p[i].fn, p[i].ln, p[i].dob);
TextIO.putln();
}
// public static void display(Person[] p, int personFormat, int dateFormat){
// display(p);
// switch(personFormat){
// case 1: PersonFunctions.display(p, 1); break;
// case 2: PersonFunctions.display(p,2); break;
// default: display(p);break;
// }
// }
public static void main(String[] args) {
go();
}
TextIO.put("Welcome to the SimplePersonDatabase.\n");
TextIO.putln();
int option;
do{
TextIO.put("available options:\n1) list\n2) add\n3) remove\n4) sort\n5) find\n6) settings\n0) quit\nyour choice:");
option = TextIO.getInt();
switch(option){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
TextIO.putln("sort by:\n1) Firstname\n2) Birth\nall other values: lastname");
switch(TextIO.getInt()){
case 1:
break;
case 2:
break;
default :
break;
}
break;
case 5:
break;
case 6:
break;
case 0:
TextIO.put("Thank you for using the SimplePersonDatabase.");
break;
case 99:
break;
default :
TextIO.put("illegal option.");
break;
}
}while(option !=0);
}
Unlikely to be needed, but maybe you meant how to deal with Person constructors.
Made the List complete (add, remove, numberOfPersons) and without redundancy (size, next).
In SimplePersonDataBasse one should use List, not Person[] especially as only part of the array is filled.
Rests to say there are java collection classes like java.util.List, ArrayList and others, that offer built-in functionality for dynamic lists instead of fixed-size arrays.
class List {
Person[] persons;
int count;
public List() {
this(100);
}
public List(int initialCapacity) {
persons = new Person[initialCapacity];
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
}
public class Person {
public String fn;
public String ln;
public Date dob;
public int id; // Must be unique
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
public class SimplePersonDataBase {
private List list;
private int nextPersonId;
public boolean add(Person personadd) {
personadd.id = nextPersonId;
++nextPersonId;
list.add(personadd);
}
}

Categories

Resources