Not able to print out the Array Elements - java

This code is to get the firstName, LastName, and StudentID by reading it from a file and displaying the information in the main file. When I run my program, instead of printing the information of the students, it prints out a chain of characters and numbers.
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] students = new Student[10];
getStudentData(students);
for (int i = 0; i < students.length; i++){
System.out.println(students[i]);
}
}
public static void getStudentData(Student[] students){
String infileName = "studentlist.txt";
Scanner reader = null;
try {
reader = new Scanner (new File(infileName));
int index = 0;
while(reader.hasNext()){
String oneLine = reader.nextLine();
String[] parts = oneLine.split(" ");
long studentID = Long.parseLong(parts[2]);
students[index] = new Student(parts[0],parts[1],studentID);
index++;
}
} catch (FileNotFoundException err) {
System.out.println(err);
} finally {
if (reader != null)
reader.close();
}
}
}

Have you defined a toString() method on your Student class?
You need to do this otherwise the default toString() implementation of the superclass for all classes (class Object) will be used which returns the name of the class concatenated with # and the hashcode of the class in hexadecimal format.
Add this method to your Student class and return a meaningful String containing the attribute values of a Student object instead of my descriptive String.
#Override
public String toString() {
return "return a string here that represents the student and his/ her attribute values";
}
FYI: Many IDEs can generate an arbitrary toString() method for you.
See the this thread for more details on Object::toString().

Related

Arrays of Object test but not getting any output

I would like some guidance on this particular code that I am testing but currently it is not printing out anything and on top of that I feel as if it isn't reading the text file at all. It seems to finish right away with no errors and I only get prompted that "build is successful."
The assignment is to read from a data text file that list 20 lines of student information, each line is comprised of first name, last name, and their grade all seperated by spaces. I am put to it into an array and output their information, but for now I am testing to see if it will output the first name before I proceed.
public class studentClass {
private String studentFName, studentLName;
private int testScore;
private char grade;
//constructor
public studentClass(String stuFName, String stuLName, int stuTestScore){
studentFName = stuFName;
studentLName = stuLName;
testScore = stuTestScore;
}
public String getStudentFName(){
return studentFName;
}
public String getStudentLName(){
return studentLName;
}
public int getTestScore(){
return testScore;
}
public char getGrade(){
return grade;
}
public void setStudentFName(String f){
studentFName = f;
}
public void setStudentLName(String l){
studentLName = l;
}
public void setTestScore(int t){
if (t>=0 && t<=100){
testScore = t;
}
}
public void setGrade(char g){
grade = g;
}
}
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
for(int i = 0; i>studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
public static studentClass[] readStudentData(studentClass[] studentObject)throws IOException{
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String lines = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((lines = br.readLine()) != null){
String stuArray[] = lines.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
return studentObject;
}
You need to actually call the method to read in the data. Try the following (note I didn't handle the Exception. I leave that as an exercise to you)
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
//NOTE I CHANGED THE '>' TO '<'
for(int i = 0; i < studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
//Note that I changed the return type to void
public static void readStudentData(studentClass[] studentObject)throws IOException{
//Your code here
You'll see I changed your readStudentData to return void since you're passing the array into the method you don't need to return it. You'll need to remove the return at the end of it.
You could also leave it as a method returning a studentClass[] and have no parameters. Instead, create the studentClass array inside readStudentData. I would recommend that approach because it removes the need to create and pass the array, which complicates your main method.

Creating a program to read through Integers and Strings in Java

I am trying to create a program that will read from a .txt file that is formatted as such:
Total number of students
Name
Score1
Score2
Score3
Name
Score1
etc
My current code is this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
List<String> studentList = new ArrayList<String>();
List<Integer> studentScores = new ArrayList<Integer>();
String total = imp.nextLine();
int i = 0;
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
studentScores.add(imp.nextInt());
} else {
studentList.add(imp.nextLine());
i++;
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
System.out.println(studentList.get(2) + studentScores.subList(3, 6));
System.out.println(studentList.get(4) + studentScores.subList(6, 9));
System.out.println(studentList.get(6) + studentScores.subList(9, 12));
imp.close();
in.close();
}
}
}
The format I want to display into the console is to list the name, then the three scores that student received, and to repeat it, but right now it is hard-coded just for the amount of students that are currently there, and I need it to be able to create output regardless of how many students there are.
Current output:
Total
Name [score1 score2 score3]
etc
Desired output:
Total
Name score1 score2 score3 (rather than with the [] )
etc
Any help is greatly appreciated.
More structural way to do this :
public class Project5 {
static class Student {
private String name;
private final List<Integer> scores;
private int total;
public Student() {
scores = new ArrayList<>();
total = 0;
}
public void setName(String name) {
this.name = name;
}
public void addScore(int score) {
scores.add(score);
total += score;
}
public String getName() {
return name;
}
public List<Integer> getScores() {
return scores;
}
public int getTotal() {
return total;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(name).append('\t').append(total);
for (Integer score : scores) {
sb.append('\t').append(score);
}
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
in.close();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
int total = Integer.parseInt(imp.nextLine());
System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
for (int i = 0; i < total && imp.hasNextLine(); i++) {
Student student = new Student();
student.setName(imp.nextLine());
while (imp.hasNextInt()) {
student.addScore(imp.nextInt());
}
if (imp.hasNext()) {
imp.nextLine();
}
System.out.println(student);
}
imp.close();
}
}
The toString method of a List will return it in that format. If you want a different format, you can do this with a Stream:
System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
Health warning: if this is for a school assignment where the use of Streams may get you accused of plagiarism, you will need to concatenate the elements yourself the long way.
This is the efficient solution that uses a StringBuilder and no Lists. A StringBuilder is basically a class that helps you to build string. Pretty straightforward.
// 1024 means that the initial capacity of sb is 1024
StringBuilder sb = new StringBuilder(1024);
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
// add the scores and "tab" character to the string
sb.append("\t").append(imp.nextInt());
} else {
// add the name to the string
sb.append("\n").append(imp.nextLine());
i++; // btw.. why are you doing this i++ ??
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(sb.toString());
imp.close();
in.close();
}
If you do want to use an arraylist then I suggest iterate through the arraylist like an array and print out the scores.

Trying to utilize an input.txt file into a output.txt file in Java

I am trying to test my application by printing into an output.txt file. There is an input.txt file that already contains four honor students and at least two with the same GPA of 3.9, and three that are not honors students. The results should be sent to the output.txt file. The output.txt file should contain:
1) All of the students
2) The best student
3) Number of honors students in the list
4) Honors students
The input.txt file that I created contains the following (in order) last names, first names, id, GPA, and year.
The class TestStudents prints the input.txt file. However, I need it to utilize the input.txt file in order to print the above mentioned output.txt file. Thank you very much.
Student class -
public class Student
{
String lastName, firstName, id;
double gpa;
int year;
public Student (String lastName, String firstName, String id,
double gpa, int year)
{
this.lastName = lastName;
this.firstName = firstName;
this.id = id;
this.gpa = gpa;
this.year = year;
}
public String toString()
{
return this.lastName + ", " + this.firstName + ": " + this.id + " "
+ this.gpa + " " + this.year;
}
public double getGPA()
{
return gpa;
}
public boolean isBetter (Student s)
{
return (this.gpa > ((Student)s).getGPA());
}
public boolean isHonors()
{
if (this.gpa >= 3.5)
{
return true;
}
else
{
return false;
}
}
}
CS152 class -
import java.util.*;
import java.io.*;
public class CS152
{
public static final int MAXSIZE = 22;
private static int size = 0;
public static Student[] createList (Scanner scan) throws IOException
{
Student[] list = new Student [MAXSIZE];
return populateList (list, scan);
}
private static Student[] populateList (Student[] list, Scanner scan)
{
Student s;
if (size < MAXSIZE && scan.hasNext())
{
s = new Student (scan.next(), scan.next(), scan.next(),
scan.nextDouble(), scan.nextInt());
list[size] = s;
size++;
System.out.println (s);
return populateList (list, scan);
}
else
{
return list;
}
}
public static int getSize()
{
return size;
}
// Returns String of all students. Variable n is actual size of the list.
// Assume that n is positive. Recursive code.
public static String toString (Student[] list, int n)
{
String s = " ";
if (n == 1)
{
return s += list[0];
}
else
{
s += list[n].toString() + "\n";
s += "\n";
}
return s + toString (list, n - 1);
}
// Returns the best student. Must use method isBetter in the code.
// Variable n is actual size of the list. Assume that n is positive.
public static Student findBestStudent (Student[] list, int n)
{
if (n == 1)
{
return list[0];
}
else if (list[n].isBetter (list[n - 1]))
{
return list[n];
}
else
{
return findBestStudent (list, n - 1);
}
}
// Returns the number of honor students in the list.
// Must call the method isHonors(). Variable n is actual size of the list.
// Assume that n is positive.
public static int countHonors (Student[] list, int n)
{
if (n == 0)
{
return 0;
}
else if (list[n].isHonors())
{
return 1 + countHonors (list, n - 1);
}
else
{
return countHonors (list, n - 1);
}
}
static ArrayList<Student> studentsList = new ArrayList<Student>();
public static ArrayList <Student> honorsStuds (Student[] list, int n)
{
if (n == 0)
{
return studentsList;
}
else
{
boolean currentIsHonors = list[n - 1].isHonors();
if (currentIsHonors)
{
studentsList.add(list[n - 1]);
return honorsStuds (list, n - 1);
}
else
{
return honorsStuds (list, n - 1);
}
}
}
}
TestStudents class -
import java.io.*;
import java.util.*;
public class TestStudents
{
public static void main (String[] args) throws IOException
{
File input = new File ("input.txt");
Scanner scan = new Scanner (input);
Student[] studentArray = CS152.createList (scan);
}
}
I incorporated the FileWriter into the TestStudents class. A list of all students is now displayed. I am still having difficulties trying to call the methods findBestStudent, countHonors, and honorsStuds and implementing them into TestStudents. Here is the revised TestStudents class:
TestStudents class -
import java.io.*;
import java.util.*;
public class TestStudents
{
public static void main (String[] args) throws IOException
{
File input = new File ("input.txt");
Scanner scan = new Scanner (input);
System.out.println ("All students: ");
Student[] studentArray = CS152.createList (scan);
File output = new File ("output.txt");
FileWriter fWriter = new FileWriter (output);
PrintWriter pWriter = new PrintWriter (fWriter);
pWriter.println (input);
pWriter.close();
}
}
To write to a file, you need a FileWriter.
Using a FileWriter and Try-with-resources, usage would look something like this:
try(FileWriter w = new FileWriter(new File("output.txt"))) {
w.append("Some string");
} catch (IOException ex) {
Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null, ex);
}
If you don't use a try-with-resources, make sure to close() the Writer to make sure resources do not leak. In fact, you should also make sure to close your Scanner as well, as leaving it un-closed will leak resources.
In the future, ask one question per post.
To access your Students, you just need to read them from the array.
System.out.println(studentArray[0].getGPA()); // prints the GPA of the first student
for (int i=0; i<CS152.getSize(); i++) {
System.out.println(studentArray[i]); // prints every Student
}
[[Note that this design of having a long array with null elements at the end with CS152.class telling you how many are filled is bad design. I would have the read procedure return a List<Student>, which manages its own length. Given the name of the class is CS152, however, this is probably either given to you by the teacher of CS-152 or done previously, so I'll work with what you have.]]

Java read file for the first 3 words of certain line

I am trying to read the first 3 words of a sentence from a text file.
The text file as below shown:
No. Name Age
1 Hello 12
Performance: Good
Information for student, Class Allocated:13
No. Name Age
2 Hi 13
Performance: Very Good
Data for student, Class Allocated:1
No. Name Age
3 HelloHello 13
Information for student, Class Allocated:1
How i code to read is file is as below shown:
while (read.hasNext())
{
if (read.next().equals("No.")){
Eliminate.add(read.nextLine()); //eliminate first line
No.add(read.next());
Name.add(read.next());
Age.add(read.nextInt());
}
This is how i initially read the text file. But how i met a problem which is i need the Information part. Meanwhile i try to use back the concept for me to read the information but it seems not working.Logically i am not able to break the while loop, once i break the while loop will stop and wont get for the information.
Below shown the code i tried but not work:
while (read.hasNext())
{
if (read.next().equals("No.")){
Eliminate.add(read.nextLine()); //eliminate first line
No.add(read.next());
Name.add(read.next());
Age.add(read.nextInt());
while (read.hasNext()){
if (read.next().equals("Information")||read.next().equals("Data")){
if(read.next().equals("Allocated:")){
Classroom.add(read.nextInt());
}
}
break;
}
}
}
The output that i want is:
Name: Hello
Classroom: 13
Name: Hi
Classroom: 1
Can anyone help me on this? Help would be really appreciated.
I belive that a Scanner is what your looking for. Look at the documentation for the scanner and you might realise that you wan to reformat your output if possible.
Scanner sc = new Scanner(reader.fileName)
Scanner.useDelimiter("\\s*Hello\\s*")
while (sc.hasNext()){
sc.nextInt() \\ = 1
sc.nextInt() \\ = 12
}
As you mention in your question you are reading text from a text file , then you can use BufferedReader to read each line of file and use LinkedList to manage order of line from your file, After populating line in LinkedList you have to apply business logic to extract data from line.
In below example I have tried to show you my approach of solving problem, after applying business logic I have used a nested inner class StudentInfo to store student information.
public class StudentInfoReader {
public static void main(String[] args) throws IOException {
File file = new File("path to txt file");
BufferedReader br = null;
String line;
List<String> fileStrings = new LinkedList<>();
List<StudentInfo> studentInfoList = new LinkedList<>();
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
fileStrings.add(line);
}
StudentInfo studentInfo = null;
for (String s : fileStrings) {
if (s.startsWith("No.")) {
studentInfo = new StudentInfo();
studentInfoList.add(studentInfo);
} else {
String[] studentInfoArray = s.split(" ");
if (s.startsWith("Performance")) {
studentInfoArray = s.split(":");
studentInfo.setPerformance(studentInfoArray[1]);
} else if (s.startsWith("Information")
|| s.startsWith("Data")) {
System.out.println("s is " + s);
studentInfo.setClassroom(studentInfoArray[4].substring(studentInfoArray[4].indexOf(":") + 1, studentInfoArray[4].length()));
} else {
studentInfo.setNo(studentInfoArray[0]);
studentInfo.setName(studentInfoArray[1]);
studentInfo.setAge(studentInfoArray[2]);
}
}
}
for (StudentInfo studentInfoTemp : studentInfoList) {
System.out.println("No " + studentInfoTemp.getNo());
System.out.println("Name " + studentInfoTemp.getName());
System.out.println("Age " + studentInfoTemp.getAge());
System.out.println("class " + studentInfoTemp.getClassroom());
System.out.println("");
}
} catch (FileNotFoundException ex) {
Logger.getLogger(stack1.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static class StudentInfo {
String no;
String name;
String age;
String classroom;
String performance;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public String getPerformance() {
return performance;
}
public void setPerformance(String performance) {
this.performance = performance;
}
}
}

Calling a method from within another method of the same class

I have a number of methods which need to implement my add method, however I am not sure how to go about doing this, as all the methods are in the same class - ArrayPhoneDirectory.
Add method:
private void add(String name, String telno) {
if (size >= capacity)
{
reallocate();
}
theDirectory[size] = new DirectoryEntry(name, telno);
size = size +1;
}
The following are methods which require add to be called:
load:
public void loadData(String sourceName) {
Scanner scan = new Scanner(sourceName).useDelimiter("\\Z");
while (scan.hasNextLine()) {
String name = scan.nextLine();
String telno = scan.nextLine();
DirectoryEntry newdir = new DirectoryEntry(name, telno);
//ADD THE NEW ENTRY TO THE DIRECTORY
}
}
addChangeEntry:
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
x.setNumber(telno);
return x.getNumber();
} else {
// add a new entry to theDirectory using method add
}
}
return null;
}
It is probably something very obvious, however I am still fairly new to java so any help as to how to call these methods would be much appreciated!
You can just call add(name, telno) and it will work.
In fact your add method is private, so it can only be called from inside the class.
For example, in your load method:
public void loadData(String sourceName) {
Scanner scan = new Scanner(sourceName).useDelimiter("\\Z");
while (scan.hasNextLine()) {
String name = scan.nextLine();
String telno = scan.nextLine();
// You don't need this, add builds its own DirectoryEntry from name and telno
// DirectoryEntry newdir = new DirectoryEntry(name, telno);
add(name, telno);
}
}
And you can do exactly the same in addChangeEntry

Categories