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;
}
}
Related
EDIT SOLUTION
Based on forpas code, I move thing around little bit, and now the minimum value displays as expected. Thank you guys for all your help.
public static StudentGrade findMinIndex(StudentGrade[] studentGrades)
{
StudentGrade studentGradeMin = studentGrades[0];
for(int i=0; i < studentGrades.length; i++)
{
if(studentGradeMin.getGrade()[0] > studentGrades[i].getGrade()[i])
{
studentGradeMin.getGrade()[0] = studentGrades[i].getGrade()[i];
}
}
System.out.println(studentGradeMin.getGrade()[0]);
return studentGradeMin;
}
EDIT:
Now that I can print out the number, I have problem with finding minimum value. I keep getting error message:
"The operator > is undefined for the argument type(s) StudentGrade, StudentGrade"
I need to find minimum value for my object array, but I can't print the object correctly. The result will not display like integers.
Can someone help me please?
This is my text file
6
John 97.5
Jim 99
Kathy 34
Steve 86.5
Stacy 43
Faith 88
This is my methods
//This is the constructor class
public class StudentGrade
{
private String[] names;
private double[] grades; // instance variable
// constructor initializes grades with parameter grades
public StudentGrade(double[] grades, String[] names)
{
this.grades = grades;
this.names = names;
}
// method to set the grades
public void setGrade(double[] grades)
{
this.grades = grades;
}
// method to retrieve the grades
public double[] getGrade()
{
return grades;
}
//Set name
public void setName(String[] names)
{
this.names = names;
}
// method to retrieve the names
public String[] getName()
{
return names;
}
}
//This is my main class
public static StudentGrade[] initialize(String inputFileName) throws FileNotFoundException
{
Scanner scan = new Scanner(new FileInputStream("grade.txt"));
int size = scan.nextInt();
String[] names = new String[size];
double[] grades = new double[size];
int index = 0;
String[] col = null;
while(scan.hasNextLine())
{
names[index] = scan.next();
grades[index] = scan.nextDouble();
index++;
}
StudentGrade[] studentGrades = new StudentGrade[grades.lenght];
for(int i=0; i< studentGrades; i++)
{
studentGrades[i] = new StudentGrade(grades, names);
}
for(int i=0; i< grades.length; i++)
{
System.out.println(studentGrades[i].getGrade());
}
scan.close();
return studentGrades;
}
//This is to find minimum value
public static StudentGrade findMinIndex(StudentGrade[] studentGrades)
{
StudentGrade studentGradeMax = studentGrades[0];
for(int i=1;i<studentGrades.length;i++)
{
if(studentGrades[i] > studentGradeMax) ==> Error "The operator > is undefined for the argument type(s) StudentGrade, StudentGrade"
{
studentGradeMax = studentGrades[i];
}
}
return studentGradeMax;
}
The code return these values instead of real number
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
You are printing by:
System.out.println(studentGrades[i].getGrade());
but getGrade() returns an array, so change to this:
System.out.println(Arrays.toString(studentGrades[i].getGrade()));
or if the array contains only 1 number:
System.out.println(studentGrades[i].getGrade()[0]);
Edit
public static StudentGrade findMinGrade(StudentGrade[] studentGrades) {
StudentGrade studentGradeMin = studentGrades[0];
for(int i=1; i < studentGrades.length; i++) {
if(studentGrades[i].getGrade()[0] < studentGradeMin.getGrade()[0]) {
studentGradeMin = studentGrades[i];
}
}
return studentGradeMin;
}
Check it, I hope there are no typos.
This returns the StudentGrade object inside the array studentGrades with the min grade.
The simplest way is to override the String toString() method from the Object class since that is the default method used when printing an object
So in your StudentGrade method you would add
#Override
public String toString() {
return //your fields
}
The problem here is that your member fields in StudentGrade are arrays which is a little strange so I guess your toString would look like this for example
#Override
public String toString() {
StringBuilder out = new StringBuilder();
for (String name : names) {
out.append(name);
out.append(", ");
}
for (int i = 0; i < grades.length - 1; i++) {
out.append(grades[i]);
out.append(", ");
}
out.append(grades[grades.length - 1]);
return out.toString();
}
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?
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);
....
I'm working on a program where I'm inputting values(String and int) into arrays, putting those values into an objects which go into an array list to be sorted by the the int value. When I run the program though, it prints out:
Sorted List Entries:
Item Name:null---Quant:0
Item Name:null---Quant:0
Item Name:null---Quant:0 //etc..
I'm trying to learn on my own here but I'm not sure what to do.
My main class:
import java.io.*;
import java.util.*;
public class InputItem
{
public static void main(String args[])
{
String again;
String names[] = new String[100];
int quant[] = new int[100];
int row=0;
do{
System.out.println("Please input assignment name:");
Scanner newName = new Scanner(System.in);
String name = newNamet.next();
names[row] =name;
System.out.println("Please input assignment quant:");
Scanner quantI = new Scanner(System.in);
int quantity = quantI.nextInt();
quant[row] = quantity;
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
Scanner input = new Scanner(System.in);
again = input.next();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work.add(new Items((names[row]),(quant[row])));
}
Collections.sort(work, new MyComp());
System.out.println("Sorted List Entries: ");
for(Items e:work)
{
System.out.println(e);
}
}
}
Class with Comparator:
import java.util.*;
class MyComp implements Comparator<Items>
{
#Override
public int compare(Items e1, Items e2)
{
if((e1).getQuant()< (e2).getQuant())
{
return 1;
}
else
{
return -1;
}
}
}
public class Items
{
private String name;
private int quant;
public Items(String n, int q)
{
this.name = n;
this.quant = q;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getQuant()
{
return quant;
}
public void setQuant(int quant)
{
this.quant = quant;
}
public String toString()
{
return "Item Name:" + this.name+"---Quant:" +this.quant;
}
}
The problem is here...
for (int count = 0; count < row; count++) {
work.add(new Items((names[row]), (quant[row])));
}
You're using row, which was defined in the previous section of code to keep track of which element you were updating, but is now pointing to the next element in the array (or an empty element). This basically means you are constantly adding the same (empty) values to your Items
Instead, you should be using count
for (int count = 0; count < row; count++) {
work.add(new Items((names[count]), (quant[count])));
}
This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).