conflict b/w string and string[] - java

Basically I have a class that has methods which use String arrays and i'm writing a method in the application class to read a file and update an array of object of class Customer. I get errors like:
Line 83: set_address(java.lang.String[]) in Customer cannot be applied to (java.lang.String)
at the line review[i].set_address(st[1]). I understand that it is looking for a string[] and it is receiving a string but is there any way to fix this? Here's the code I'm working with.
import java.io.*;
import java.util.*;
class Customer {
int account_id;
char[] ch1 = new char[20];
String name = new String (ch1);
char[] ch2 = new char[80];
String address = new String (ch2);
char[] ch3 = new char[10];
String phone_number = new String (ch3);
char[] ch4 = new char[8];
String date_of_birth = new String (ch4);
double account_balance;
public int get_accountid(){
return account_id;
}
public String get_address(){
return address;
}
public String get_phone_number(){
return phone_number;
}
public String get_date_of_birth(){
return date_of_birth;
}
public double get_balance(){
return account_balance;
}
public void set_account_id(int num){
account_id = num;
}
public void set_address(String add){
address = add;
}
public void set_phone_number(String phone){
phone_number = phone;
}
public void set_date_of_birth(String dob){
date_of_birth = dob;
}
public void set_balance(double bal){
account_balance = bal;
}
Customer(){ // default constructor
}
// parametrized constructor
Customer(int id, String name, String add, String dob, String num, double bal){
this.account_id = id;
this.name = name;
this.address = add;
this.date_of_birth = dob;
this.phone_number = num;
this.account_balance = bal;
}
}
public class lab2{
public static void main(String args[]){
System.out.println("testing this shit");
}
public static void readFile(String filename){
Customer[] review = new Customer[30];
int i=0;
Scanner scan = new Scanner (new File (filename));
while (scan.hasNext()){
while(i<30){
review[i].set_account_id(scan.nextInt());
String[] st = scan.nextLine().split("=");
review[i].set_address(st[1]);
st = scan.nextLine().spilt("=");
review[i].set_phone_number(st[1]);
st = scan.nextLine().split("=");
review[i].set_date_of_birth(st[1]);
//st = scan.nextLine().split("=");
review[i].set_balance(scan.nextDouble());
scan.nextLine();
i=i+1;
}
}
}
}

Your class Customer looks like a Java bean. I find these declaration suspicious:
String[] name = new String [20];
String[] address = new String [80];
String[] phone_number = new String [10];
String[] date_of_birth = new String [8];
Why do you want a Customer to have 20 names, 80 addresses, 10 phone numbers, and 8 date of birth? I suspect that your intention is saying that a Customer name is at most 20 characters long, his/her address is at most 80 characters long, etc. If this is the case, than you don't want a String[], you may want a char[]!
However, think about making those fields simply String: it seems more natural. I don't see reason why you may want to limit their size.

Just change your method signature:
public void set_address(String add){
address = add;
}
Or other choice: You create a new String[] object based on your String object an pass this:

Related

How to check the duplicate object in the array

I am a java beginner and I am designing a Nim game for many players to join. I've done some research but I don't know if my implementation is correct. The aim is to check the duplicate object in an array. I've already checked some articles, and I'll reference them in the last part of this article.
For the NimPlayer class. I've created some things.
I've defined the NimPlayer object type.
Using the type, I can initialize the player in the limited space.
I initialize an array for saving player's data by following the steps here: Storing object into an array - Java
public class NimPlayer {
String userName;
String familyName;
String givenName;
NimPlayer [] playerList = new NimPlayer[10]; //set an array here
int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
//create new data using NimPlayer data type
public void createPlayer(String userName, String familyName, String givenName) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
}
In the main method, I have created some features for players to use:
addplayer - let the user can add players in the game to compete.
To add the player, the Syntax like this:
$addplayer userName,familyName,givenName
to validate the input, I split the input and store them in the new object.
public static String[] splitName(String inputName) {
String [] splittedLine = inputName.split(",");
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
String [] name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
return name;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//create new object to save data
NimPlayer playerData = new NimPlayer(null, null, null);
System.out.print('$');
String commandInput = in.next();
while (true) {
if (commandInput.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
String userName = name[0];
String familyName = name [1];
String givenName = name[2];
playerData.createPlayer(userName, familyName, givenName);
for (int i = 0; i < playerData.playerList.length; i++) {
NimPlayer player = playerData.playerList[i];
System.out.println(player.getUserName()); }
}
So far, I have two questions here.
Every time I enter a set of data, it seems my "playerData" provokes the NullPointerException when looping through the object, but since my name input is multiple, I have to create a new object in the main method for saving input.
For checking if there is the duplicate "userName" in the set of the "inputName", I loop through the objects in an array. How can I access the "userName" in this situation?
for checking duplicate, I've checked:
Java - Loop through instances of a class rather than calling a method for each separate instance
What is a NullPointerException, and how do I fix it?
Java Array, Finding Duplicates
You should address then following things in your design/code:
Since you are creating a player using createPlayer(String userName, String familyName, String givenName), you should make the constructor, NimPlayer(String userName,String surName, String givenName) private so that it can not be called from outside of the class, NimPlayer. Also, declare createPlayer as static so that it doesn't need a NimPlayer object to be called on.
You need to have a static counter to keep track of the number of players and check the value of this counter before adding a new player to playerList.
You should also check the size of the resulting array after inputName.split(","). Similarly, you should check the size of the returned array from splitName before you access any element from it.
Given below is the code incorporating the points mentioned above:
import java.util.Scanner;
class NimPlayer {
private String userName;
private String familyName;
private String givenName;
//...
// public getters and setters of userName, familyName, and givenName
//...
private static int counter = 0;
private static NimPlayer[] playerList = new NimPlayer[10];
private NimPlayer(String userName, String familyName, String givenName) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
}
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < 10) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("The list is full.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer[] getPlayers() {
return playerList;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandInput = in.next();
if (commandInput.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
if (name != null && name.length == 3) {
NimPlayer.createPlayer(name[0], name[1], name[2]);
}
} else {
break;
}
}
for (int i = 0; i < NimPlayer.getCounter(); i++) {
System.out.println(NimPlayer.getPlayers()[i].getUserName());
}
}
public static String[] splitName(String inputName) {
String[] splittedLine = inputName.split(",");
String[] name = null;
if (splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
}
I didn't understand your another question:
For checking if there is the duplicate "userName" in the set of the
"inputName", I loop through the objects in an array. How can I access
the "userName" in this situation?

Storing Objects in Linked List

I am creating a simple program which reads data from a text file and displays it in the console. The data that I am displaying is information regarding a student - name, id, subject, marks etc
The program reads the text file, and creates a student object for each user found. I am running into a problem when trying to store these students in a linked list. It seems to create a new list each time and overrides the previous one, so I always just end up with one student in the list.
How can I get it store them without overriding previous lists? Here is some of my code below:
public static boolean readFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String[] words = scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to read file");
}
return true;
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
LinkedList<Student> student = new LinkedList<>();
student.add(new Student(id,firstName,lastName));
LinkedList<AssignmentMarks> mathematicsMarks = new LinkedList<>();
mathematicsMarks.add(new AssignmentMarks("Mathematics",mathsMark1,mathsMark2,mathsMark3));
LinkedList<AssignmentMarks> englishMarks = new LinkedList<>();
englishMarks.add(new AssignmentMarks("English",englishMark1,englishMark2,englishMark3));
}
This code above is in my Main class. The code below is from my Student class:
public class Student {
private int id;
private String firstName;
private String lastName;
private AssignmentMarks mathMarks;
private AssignmentMarks englishMarks;
public Student(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFullName() {
return firstName;
}
}
Any help would be appreciated thanks guys!
This variable
LinkedList<Student> student = new LinkedList<>();
needs to declared outside of the method, as a field, or within readFile and passed in as a parameter, otherwise it will be created everytime that you call addStudent
Declare your LinkedList as a member of the class, because here every time you call addStudent() you are creating a new list.
You should instead do something like :
public class Test {
private LinkedList<Student> student = new LinkedList<>();
public static boolean readFile(String filename) {
// ...
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,
englishMark1,englishMark2,englishMark3);
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
// ...
// this will now add it to the only instance of the list
student.add(new Student(id,firstName,lastName));
}
}

Separate data and store in ArrayList?

I am trying to separate a set of data. I need to store each data into a variable then create an object and put them in an ArrayList.
The dataset is in this format
lastName, firstName
ID num_courses
course1_name
grade units
course2_name
grade units
....
I have done this so far but I'm having trouble creating multiple objects, storing the data, and adding it to an ArrayList[]. Thanks for your time and help (:
public static void main (String[] args) throws FileNotFoundException {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter file name: ");
String fileName = scnr.nextLine();
Scanner inFile = new Scanner(new FileInputStream(fileName)); //importing filename
ArrayList<String> list = new ArrayList<String>(); //for list of courses
String name = "";
String id = "";
int coursesTaken = 0;
String courseName = "";
char grade;
int courseUnit = 0;
while(inFile.hasNextLine()){
name = inFile.nextLine(); //first line is name
StringTokenizer st = new StringTokenizer(inFile.nextLine()); //separting whitespace
id = st.nextToken(); //storing ID
coursesTaken = Integer.parseInt(st.nextToken()); //storing num_courses_taken
Student s1 = new Student(name, id); //FIXME (need more than 1 student object)
for(int i = 0; i < coursesTaken*2; ++i){
courseName = inFile.nextLine();
s1.addCourses(courseName); //adding to arrayList
StringTokenizer st2 = new StringTokenizer(inFile.nextLine());
grade = st2.nextToken().charAt(0);
courseUnit = Integer.parseInt(st2.nextToken());
Course ci = new Course(courseName, grade, courseUnit); //FIXME (need more than 1 course)
}
}
}
Course.java
public class Course {
private String name;
private char grade;
private int units;
//constructors
public Course(){
name = "";
grade = 0;
units = 0;
}
public Course(String name, char grade, int units){
this.name = name;
this.grade = grade;
this.units = units;
}
//getters
public String getName(){
return name;
}
public char getGrade(){
return grade;
}
public int getUnits(){
return units;
}
//setters
public void setName(String name){
this.name = name;
}
public void setGrade(char grade){
this.grade = grade;
}
public void setUnits(int units){
this.units = units;
}
}
Student.java
public class Student {
private String name;
private String id;
private ArrayList<String> listCourses = new ArrayList<String>();
//constructor
//default
public Student(){
name = "none";
id = "none";
//courses = "none";
}
public Student(String name, String id){
this.name = name;
this.id = id;
//this.courses = courses;
}
//getters
public String getName(){
return name;
}
public String getId(){
return id;
}
public ArrayList<String> getCourses(){
return listCourses;
}
//setters
public void setName(String name){
this.name = name;
}
public void setId (String id){
this.id = id;
}
public void addCourses(String courses){
listCourses.add(courses);
}
}
First, you need a List to store your students:
ArrayList<Student> students = new ArrayList<>();
You should add each created student to this list when all fields are parsed:
students.add(s1);
Second, I think, it's better to change the listCourses field from ArrayList<String> to ArrayList<Course> - to store information about all students courses inside the Student object.
Third, you don't need to multiply coursesTaken by 2 because you call inFile.nextLine() twice for each course taken.
for (int i = 0; i < coursesTaken; i++)
Finally your main method would look like this:
private ArrayList<Course> listCourses = new ArrayList<>();
ArrayList<Student> students = new ArrayList<>();
while(inFile.hasNextLine()){
name = inFile.nextLine(); //first line is name
StringTokenizer st = new StringTokenizer(inFile.nextLine()); //separting whitespace
id = st.nextToken(); //storing ID
coursesTaken = Integer.parseInt(st.nextToken()); //storing num_courses_taken
Student s1 = new Student(name, id);
ArrayList<Course> courses = new ArrayList<>();
for(int i = 0; i < coursesTaken; i++){
courseName = inFile.nextLine();
StringTokenizer st2 = new StringTokenizer(inFile.nextLine());
grade = st2.nextToken().charAt(0);
courseUnit = Integer.parseInt(st2.nextToken());
courses.add(new Course(courseName, grade, courseUnit)); //FIXED
}
s1.setListCourses(courses);
students.add(s1); //FIXED
}
UPDATE: Changes in Student class:
public class Student {
private String name;
private String id;
private ArrayList<Course> listCourses = new ArrayList<>();
...
// this is just a setter for listCourses field
public void setListCourses(ArrayList<Course> listCourses) {
this.listCourses = listCourses;
}
}
//for list of courses
That's a list of strings.
This is for a list of courses
List<Course> list = new ArrayList<>();
Then, just list.add(ci) in the loop
Sidenote: Student.addCourses should be singular, and probably accept a Course object

reading a .csv file into an array in java

I have a class called EmpQuery that I am trying to create an array of objects for my Employee class to hold data that comes from a employeedatabase.csv file.
The database appears like what is shown below. I need to use a stream-processing-algorithm..
Loop till EOF{
read in 1 record
Deal with that record completly
}
EX.
Employee ID,Full Name,Department,Start Date,Earnings
EMP001,Adele M. Fulton,Engineering,10/28/2008,"$104,000.00"
EMP002,Ali T. Herman,Engineering,2/27/2012,"$337,522.00"
EMP003,Alika C. Crawford,Engineering,6/2/2009,"$144,000.00"
So far i just have this much set up
public class EmployeeDB {
private static String[] empID = new String[300];
private static String[] empName = new String[300];
private static String[] department = new String[300];
private static String[] startDate = new String[300];
private static String [] earnings = new String[300];
private static String [] empDataBase = new String[300];
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
fillDataArray();
}
public class employee{
String empID;
String empName;
String department;
String startDate;
int earnings;
public employee(String ID,String Name,String dept,String sDate,int earn){
empName = Name;
empID = ID;
department = dept;
startDate = sDate;
earnings = earn;
}
public employee( String ID, String Name) {
empName = Name;
empID = ID;
department = "";
startDate = "";
earnings = 0;
}
public employee(){
empName = "";
empID = "";
department = "";
startDate = "";
earnings = 0;
}
}
private static String[] fillDataArray() throws FileNotFoundException {
File DatabaseFile = new File("EmpDB_lab7.csv");
Scanner inputFile = new Scanner(DatabaseFile);
String InputLine;
String [] empDBTemp = null;
int i=0;
while (inputFile.hasNextLine()) {
InputLine = inputFile.nextLine();
empDBTemp = InputLine.split("-");
empID[i] = empDBTemp[1];
empName[i] = empDBTemp[2];
department[i] = empDBTemp[3];
startDate[i] = empDBTemp[4];
earnings[i] = empDBTemp[5];
}
return empDBTemp;
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at employeedb.EmployeeDB.fillDataArray(EmployeeDB.java:76)
at employeedb.EmployeeDB.main(EmployeeDB.java:28)
Java Result: 1
CSV parsing is harder than it appears, so you should use a pre-existing library, such as Super CSV
Your CSV column names should match your bean field names (or skip the header altogether), and earnings could be a String, else you'll want to use a CellProcessor to parse it.
Reading stuff into an array and stream processing are contradictory.
ICsvBeanReader csvReader = new CsvBeanReader(new FileReader("employeedatabase.csv"), CsvPreference.STANDARD_PREFERENCE);
String[] header = csvReader.getHeader(false);
EmployeeDB employeeDB;
while((employeeDB = csvReader.read(EmployeeDB.class, header)) != null) {
System.out.println(employeeDB.getEmpName());
}
csvReader.close();
And
public class EmployeeDB {
private String empID;
private String empName;
private String department;
private String startDate;
private String earnings;
...getters/setters...
}
I changed the header to:
EmpID,EmpName,Department,StartDate,Earnings

How to create a search method for an array

My code is as follows:
import java.io.*;
import java.util.*;
public class readStudents extends Object
{
private String SName = "";
private String DoB = "";
private String Gender = "";
private String Address = "";
Student [] students = new Student[20];
public void fillStudentArray()
{
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try
{
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String getName()
{
return this.SName;
}
public void printname()
{
System.out.println("hello");
}
public Student search(String name)
{
System.out.print("Enter the name you wish to search: ");
for (int i = 0; i < this.students.length; i++)
{
Student s = this.students[i];
if (s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
} //end class students
However I am trying to create a well refined program that I can call on these methods from another main file with as minimal code as possible in that file.
The search method at the bottom is tripping me up as I am assuming I need to put something to do with the array in my getName() method but I can't figure it out.
Since I am doing this as a class for another main method, with the placement of my array initialization and declaration it allows the other methods to access it but it leaves me with no way to create this array from the main method unless I am missing something?
This is the error jCreator is throwing:
F:\University\Ass2\readStudents.java:62: error: cannot find symbol
if (s.getName().equalsIgnoreCase(name))
^
symbol: method getName()
location: variable s of type Student
You never populated the Student students[] array... You retrieved the values you would populate them with here:
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
But you never actually set those values into a Student object in the students[] array
Do something like this:
int i = 0;
while(in.hasNextLine())
{
String name = in.next();
String dateOfBirth = in.next();
String gender = in.next();
String address = in.next();
students[i] = new Student(name, dateOfBirth, gender, address);
i++
}
Also, you might consider ditching the array and using some sort of List or Hash object... If your file contains more than 20 lines, the array will be out of index when you try to define the 21st value.. With an arraylist or a List you wouldn't have that problem
I took a liberty to tweak your code as previous answer mentioned, it's better to use array list in your case. You could make a small student container class within your reader. The get name method is also kinda redundant ;s
package test;
import java.io.*;
import java.util.*;
public class readStudents{
ArrayList<Student> students = new ArrayList<Student>();
class Student {
private String name;
private String dob;
private String gender;
private String address;
public Student(String name, String dob, String gender, String address) {
this.name = name;
this.dob = dob;
this.gender = gender;
this.address = address;
}
public void fillStudentArray() {
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
students.add(new Student(SName, DoB, Gender, Address));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getName(Student student) {
return student.name;
}
public void printname() {
System.out.println("hello");
}
public Student search(String name) {
System.out.print("Enter the name you wish to search: ");
for (Student student : students) {
if (student.name.equalsIgnoreCase(name))
;
return student;
}
return null;
}
}
}
If you're not forced by your teacher to use for or for-each cycle in the search function - this is how to do a full scan the Java 8 way
public Optional<Student> findFirstByName(final String name) {
return Arrays.stream(students)
.filter(s -> s.getName().equalsIgnoreCase(name))
.findFirst();
}

Categories