I have a file that has the following content:
5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47
I'm trying to put the names and then numbers for the ticket in an array in my ticket constructor, however when I instantiate my ticket object and try to display it I get the following:
Tickets: lottery$Ticket#33909752
Tickets: lottery$Ticket#55f96302
Tickets: lottery$Ticket#3d4eac69
Tickets: lottery$Ticket#42a57993
Tickets: lottery$Ticket#75b84c92
Does the problem in my constructor for ticket or is it impossible to print an array without making it a string first?
int lim = scan.nextInt();
scan.nextLine();
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);
System.out.println("Ticket: " + ticket);
}
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 need to provide toString method for it. Here is sample, which you can use:
#Override
public String toString() {
return "Ticket{" +
"name='" + name + '\'' +
", tarray=" + Arrays.toString(tarray) +
'}';
}
In order to accomplish that you need to write an overiding toString method and write in there want you want.
public String toString(){
return //whatever you need goes here and will be printed when you try and
//print the object
}
You must override the toString method which is inherited from the Object class:
#Override
public String toString(){
return //Enter the format you require
}
Remember ticket is a reference variable so when you print it out, you will get the hashcode along with the name of the class of which the object is an instance.
Related
class Method{
String name ;
int Num ;
void text() {
System.out.println(" Hello this code is running coding by "+ name+" number " +Num);
}
}
public class MethodClass {
public static void main(String[] args) {
Method Object = new Method();
Object.name = " NAHIAN " ;
Object.Num = 0123 ;
Object.text();
}
}
Result show:
Hello this code is running coding by NAHIAN number 83
But the 83 should be 0123
when you add a 0 in front, it is refering to an octa (base8) value.
So 0123 is 83 in dec (base10)
To print out a number in octa. You can convert it to string using the following
String convertedString = Integer.toOctalString(0123);
System.out.println("The octa value is " + convertedString);
you can refer to https://www.javatpoint.com/java-decimal-to-octal for more information.
Use String in Num variable instead of integer.
String name ;
String Num ;
void text() {
System.out.println(" Hello this code is running coding by "+ name+" number " +Num);}
In the following code, I have taken in a list of 5 student names, and loading them in an ArrayList of type String.
import java.util.Scanner;
import java.util.ArrayList;
public class QuizAverage
{
public static void main( String[] args ) {
final int NAMELIMIT = 5 ;
final int QUIZLIMIT = 5 ;
ArrayList<String> sNames = new ArrayList<String>();
ArrayList<String> sFamily = new ArrayList<String>();
Scanner in = new Scanner(System.in);
//Load the 5 names of the students in the arraylist
for(int i = 1; i<=NAMELIMIT; i++)
{
String[] input = in.nextLine().split("\\s+");
sNames.add(input[0]);
sFamily.add(input[1]);
}
System.out.println("Name: ");
System.out.println();
for(int i=0; i<NAMELIMIT; i++)
{
System.out.println("Name: " +sNames.get(i) + " " + sFamily.get(i));
}
System.out.println();
}
}
However, now I am trying to add to the code a part that reads in marks for 5 quizes for each student and loads the quiz marks in An ArrayList of type Integer
So I know I need to use
ArrayList<Integer> quizMarks = readArrayList(readQuiz.nextLine());
and then pass it on to this code which takes the quiz marks and weights them out of 15 instead of 100
public static ArrayList<Integer> readArrayList(String input)
{
ArrayList<Integer> quiz = new ArrayList<Integer>();
int i = 1;
while (i <= QUIZLIMIT)
{
if (readQuiz.hasNextInt()) {
quiz.add(readQuiz.nextInt());
i++;
} else {
readQuiz.next(); // toss the next read token
}
}
return quiz;
}
//Computer the average of quiz marks
public static void computerAverage(ArrayList<Integer>quiz)
{
double total = 0 ;
for(Integer value : quiz)
{
total = total + value;
}
total *= MAX_SCORE/100;
System.out.println("Quiz Avg: "+ total / QUIZLIMIT );
}
}
So my current code with the input:
Sally Mae 90 80 45 60 75
Charlotte Tea 60 75 80 90 70
Oliver Cats 55 65 76 90 80
Milo Peet 90 95 85 75 80
Gavin Brown 45 65 75 55 80
Gives the output
Name: Sally Mae
Name: Charlotte Tea
Name: Oliver Cats
Name: Milo Peet
Name: Gavin Brown
when the desired output is
Name: Sally Mae Quiz Avg: 10.5
Name: Charlotte Tea Quiz Avg: 11.25
Name: Oliver Cats Quiz Avg: 10.95
Name: Milo Peet Quiz Avg: 12.75
Name: Gavin Brown Quiz Avg: 9.6
As Jim said, you should store the marks and the name of the student in the same class. The reason for doing that is say going forward you want to find the marks of a particular student named Raj.
In your implementation you would have to go through the first array for find the index of the person named Raj and then go to the same index in the marks array. If there was no problem in initializing the first array but there was some problem in creating the marks array you might end up with the wrong marks.
Also if you have to add a new attribute to a student you would have to create a new array and then add one more logic to read that data.
Having a class gives you an easy way to group all the data belonging to a student.
For your problem of averaging, I'd have a class as follows
class Student {
private String name;
private Double marks;
public Student(String name, String marks) {
this.name = name;
this.marks = marks;
}
//getters setters
}
Have a list of Student
List<Student> students = new ArrayList<Student>();
After reading you will append the object to this list
students.add(new Student(name, marks));
Computing average is as follows
Double average = 0;
for(Student student: students) {
average += student.getMarks();
}
average = average / student.size();
Checkout https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html for other ways to get the average.
Don't use parallel arrays. Use a Student class instead:
public class Student {
private String name;
private String family;
private List<Integer> marks = new ArrayList<>();
public Student(String name, String family)
{
this.name = name;
this.family = family;
}
// getters, setters
...
public void addMark(int mark)
{
this.marks.add(mark);
}
public void getAverage()
{
... // etc
}
}
Then store instances of this class in a single list in your main program
List<Student> students = new ArrayList<>();
You haven't called computerAverage() yet from what I see.
The method returns some null skipping some objects.The goal of the method is to return sorterd list of people according to their 'midterm' and 'final' ('midterm' of a person is immediately followed by his 'final') Could smb please help to fix it? Here's the code
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int index = 0;
for (int i = 0; (i < exams.length) && (index < exams.length/2); i++)
{
if (exams[i].getExamType() == 'm')
{
r[index*2] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), "midterm", exams[i].getScore());
for(int j = 0; (j < exams.length) && (index < exams.length/2); j++)
{
if((exams[j].getExamType() == 'f') && (exams[i].getID() == exams[j].getID()))
{
r[index*2 + 1] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), "final", exams[i].getScore());
}
}
}
index++;
}
return r;
here's the output:
null
null
Bill Gates 6 midterm 90
Bill Gates 6 final 90
James Gosling 3 midterm 100
James Gosling 3 final 100
Sergey Brin 22 midterm 98
null
Dennis Ritchie 5 midterm 94
Dennis Ritchie 5 final 94
Steve Jobs 9 midterm 95
Steve Jobs 9 final 95
Here's the unsorted list which is passed as a parameter:
Steve Jobs 9 final 91
Bill Gates 6 midterm 90
James Gosling 3 midterm 100
Sergey Brin 22 midterm 98
Dennis Ritchie 5 midterm 94
Steve Jobs 9 midterm 95
Dennis Ritchie 5 final 100
Jeff Dean 7 midterm 100
Bill Gates 6 final 96
Jeff Dean 7 final 100
Sergey Brin 27 final 97
James Gosling 3 final 100
Either your entire class is posting the same question, or you are Joshua mark II. Now, other variations said only one for loop and other restrictions, so I am going to ignore all of that and address the messed up double loop above. This will fix the loop above:
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int index = 0;
for (int i = 0; i < exams.length ; i++)
{
if (exams[i].getExamType() == 'm')
{
r[index*2] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), 'm', exams[i].getScore());
for(int j = 0; j < exams.length; j++)
{
if((exams[j].getExamType() == 'f') && (exams[i].getID() == exams[j].getID()))
{
r[index*2 + 1] = new Exam(exams[j].getFirstName(), exams[j].getLastName(), exams[j].getID(), 'f', exams[j].getScore());
}
}
index++;
}
}
return r;
}
Output:
Sorted list:
Exam [fn=Bill, ln=Gates, id=6, ex=m, score=90]
Exam [fn=Bill, ln=Gates, id=6, ex=f, score=96]
Exam [fn=James, ln=Gosling, id=3, ex=m, score=100]
Exam [fn=James, ln=Gosling, id=3, ex=f, score=100]
Exam [fn=Dennis, ln=Ritchie, id=5, ex=m, score=94]
Exam [fn=Dennis, ln=Ritchie, id=5, ex=f, score=100]
Exam [fn=Steve, ln=Jobs, id=9, ex=m, score=95]
Exam [fn=Steve, ln=Jobs, id=9, ex=f, score=91]
Exam [fn=Jeff, ln=Dean, id=7, ex=m, score=100]
Exam [fn=Jeff, ln=Dean, id=7, ex=f, score=100]
Exam [fn=Sergey, ln=Brin, id=22, ex=m, score=99]
Exam [fn=Sergey, ln=Brin, id=22, ex=f, score=97]
These items which show null are never initialized thats why..
public class Example2 {
String array[] = new String[15];
public Example2(){
for(int j=0; j<array.length-1; j++)
array[j]="j";
for(int j=0; j<array.length; j++)
System.out.println(array[j]);
}
public static void main(String[] args){
new Example2();
}
}
This example will print 14 ("J") and one null.Why? cause array[15] is not initialized.
So on your example with i am sure that these items show null cause are never initialized.
[EDITED] #Michael, your code is giving me this output with only one null:
Sorted list:
Bill Gates 6 midterm 90
Bill Gates 6 final 96
James Gosling 3 midterm 100
James Gosling 3 final 100
Sergey Brin 22 midterm 98
null
Dennis Ritchie 5 midterm 94
Dennis Ritchie 5 final 100
Steve Jobs 9 midterm 95
Steve Jobs 9 final 91
Jeff Dean 7 midterm 100
Jeff Dean 7 final 100
Here's the Exam class which has toString method:
class Exam {
private String firstName;
private String lastName;
private int ID;
private String examType;
private int score;
public Exam(String firstName, String lastName, int ID, String examType, int score)
{
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID;
this.examType = examType;
this.score = score;
}
public String getFirstName()
{
return this.firstName;
}
public String getLastName()
{
return this.lastName;
}
public int getID()
{
return this.ID;
}
public char getExamType()
{
char examTypeCasted = 0;
examTypeCasted = examType.charAt(0);
return Character.toUpperCase(examTypeCasted);
}
public int getScore()
{
return this.score;
}
public String toString()
{
return this.firstName + " " + this.lastName + " " + this.ID + " " + this.examType + " " + this.score;
}
public boolean equals(Exam e)
{
if(this.equals(e))
return true;
else
return false;
}
}
This question already has answers here:
Sorting a collection of objects [duplicate]
(9 answers)
Closed 8 years ago.
Almost done with this program, but when it's sorted out the weight is being arranged to from least to greatest, which is correct. The only problem is that the name and age associated with the weight are not sorted with the weight.
for example
mike 25 180
jen 36 105
sam 22 120
I should get
jen 36 105
sam 22 120
mike 25 180
but I get
mike 25 105
jen 36 120
sam 22 180
import java.util.*;
import java.util.ArrayList;
import java.util.List;
public class Lab0 {
public static void main(String[] args) {
//Scanner and variables
Scanner keyboard = new Scanner (System.in);
String name = "";
int age;
double weight;
int number;
//Creates list for name, age, and weight
ArrayList<String> Name = new ArrayList<String>();
ArrayList<Integer> Age = new ArrayList<Integer>();
ArrayList<Double> Weight = new ArrayList<Double>();
System.out.println("Enter the information needed.");
//Ask user to enter information needed
while (true){
System.out.print("Enter last name: ");
name = keyboard.nextLine();
if(name.equalsIgnoreCase("FINISHED")){
break;
}
else {
Name.add(name);
System.out.print("Enter age: ");
age = keyboard.nextInt();
Age.add(age);
System.out.print("Enter weight: ");
weight = keyboard.nextDouble();
Weight.add(weight);
keyboard.nextLine();
System.out.println("==========================================\n");
}
}
//new list to sort weight and age and name
ArrayList<String> NameList = Name;
ArrayList<Integer> AgeList = Age;
ArrayList<Double> WeightList = Weight;
Collections.sort(Weight);
for(int i=0; i<Weight.size(); i++){
for (int j=0; j<Weight.size(); j++){
if(WeightList.get(j) == Weight.get(i)){
Name.set(j, NameList.get(i));
Age.set(j, AgeList.get(i));
}
else;
}
}
//prints out information entered
for (int k=0; k<Weight.size(); k++){
System.out.println("Name: " + Name.get(k) + " Age: " + Age.get(k)
+ " weight: " + Weight.get(k));
}
while (true){
System.out.println("=============================================");
System.out.print("Enter a last name that you listed: ");
String Search = keyboard.next();
int index = Name.indexOf(Search);
if (index >=0){
System.out.println("Age: " + Age.get(index));
System.out.println("Weight: " + Weight.get(index));
}
else if(Search.equalsIgnoreCase ("DONE")){
System.exit(0);
}
else{
System.out.println("NOT FOUND");
}
}
}
}
The problem is, that the relation is loosing between the single-informations.
A person is a tripel like (name, age, weight).
You have three lists and after sorting the list with weights, you're want to concatenate the single-informations.
That is the problem-section of your code:
ArrayList<String> NameList = Name;
ArrayList<Integer> AgeList = Age;
ArrayList<Double> WeightList = Weight;
Collections.sort(Weight);
for(int i=0; i<Weight.size(); i++){
for (int j=0; j<Weight.size(); j++){
if(WeightList.get(j) == Weight.get(i)){
Name.set(j, NameList.get(i));
Age.set(j, AgeList.get(i));
}
else;
}
}
Your first problem is:
If two or more persons having the same weight, you're not find a clearly relation. (Not the topic of your question, but a problem.)
Your secound problem is:
(If all weights are different.)
Collections.sort(Weight);
This method sorts the list 'Weight'.
But it is the same list with the name 'WeightList '.
You're copy the reference.
You shold clone the list first, bevore you're use sort.
And you need to change i and j in 'Name.set(...)' and 'Age.set(...)'.
This should help:
ArrayList<String> NameList = (ArrayList<String>) Name.clone();
ArrayList<Integer> AgeList = (ArrayList<Integer>) Age.clone();
ArrayList<Double> WeightList = (ArrayList<Double>) Weight.clone();
Collections.sort(Weight);
for (int i = 0; i < Weight.size(); i++) {
for (int j = 0; j < Weight.size(); j++) {
if (WeightList.get(j) == Weight.get(i)) {
Name.set(i, NameList.get(j));
Age.set(i, AgeList.get(j));
}
else
;
}
}
I think that's the answer for your problem.
In addition:
You should think about 'ChrisForrence' comment of your qurestion.
It is better using a class for person which implements the interface 'Comparable'.
You should use comparators in my opinion.
That is the general method for getting flexibility.
The .txt file looks like this:
Gator Ali 85
Vator Ella 75
Beam James 95
Lastin Class 55
I've seen other people trying to get similar code on here, but none of that helped.
I can get the average; however, I also need to print out if the score 10 points below average.
Here is my output:
run:
Welcome to the Student Scores Application.
Ali Gator 85
Ella Vator 75
James Beam 95
Class Lastin 55
Beam, James: 95
Gator, Ali: 85
Lastin, Class: 55
Vator, Ella: 75
Your score is 10 points or more below the class average
Class Average: 77.5
Here is my code:
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader("src//chapt11//Studentdata.txt"));
System.out.println("Welcome to the Student Scores Application.\n");
int nStudent = 100;
Student[] studentArray = new Student[nStudent];
int counter = 0;
while (aScanner.hasNext()) {
String lastName = aScanner.next();
String firstName = aScanner.next();
int score = aScanner.nextInt();
System.out.println(firstName + " " + lastName + " " + score);
studentArray[counter++] = new Student(lastName, firstName, score);
Arrays.sort(studentArray, 0, counter);
}
System.out.println();
for(int j = 0; j < counter; j++){
System.out.println(studentArray[j]);
}
double sum = 0;
for(int j = 0; j < counter; j++){
sum += studentArray[j].getExamScore();
}
double average = (sum*1.0)/counter;
for(int j = 0; j < counter; j++){
int score = studentArray[j].getExamScore();
if (score <= (average - 10)){
System.out.println("Your score is 10 points or more below the class average");
}
}
System.out.println();
System.out.println("Class Average: " + average);
System.out.println();
aScanner.close();
}
class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private int score;
public Student(String firstName, String lastName, int score) {
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public int getExamScore() {
return score;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public int compareTo(Student s) {
if(!firstName.equalsIgnoreCase( s.firstName)) {
return firstName.compareToIgnoreCase(s.firstName);
}
if(!lastName.equalsIgnoreCase(s.lastName)) {
return lastName.compareToIgnoreCase(s.lastName);
}
return score - s.score;
}
#Override
public String toString(){
return firstName + ", " + lastName + ": "+ score;
}
}
I see some problems with your code.
Firstly, there is no need to call Arrays.sort every time you add a Student to the studentArray. Place this method call outside the end of while which sorts complete array with just one call to the method.
Secondly, and more importantly, how do you want the Student objects compared?
The compareTo method inside Student doesn't make sense. If you want the students to be sorted only by their scores you should have something like this:
#Override
public int compareTo(Student s) {
return this.score - s.score;
}
And as far as the expected output is concerned, this is what's happening.
The following line prints each Student as they are added to the array:
System.out.println(firstName + " " + lastName + " " + score);
This part prints each Student object again:
for (int j = 0; j < counter; j++) {
System.out.println(studentArray[j]);
}
And this line gets printed only when score <= (average - 10) evaluates to true:
System.out.println("Your score is 10 points or more below the class average");
I believe now you see the problem.