How to solve class case exception ? Using arraylist [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to make a program that capable to add new participant and save it in txt file .The program also able to read data from txt file and do processes . The program can run , but when I try to display participants by state . I get java.lang.ClassCastException : java.lang.String cannot be cast to Reading . Trying several thing but still can't figure it out
import java.util.* ;
import java.io.* ;
class KRBApp{
public static int menu(){
Scanner sc = new Scanner(System.in);
System.out.println("\n\n\n\t\t\tKRB APPLICATION MAIN MENU");
System.out.println("\t\t\t~~~~~~~~~");
System.out.println("\n\t\t\t1. Add new participant");
System.out.println("\t\t\t2. Display participants by state");
System.out.println("\t\t\t3. Search participants by name");
System.out.println("\t\t\t4. Exit");
System.out.print("\n\t\t\t>>> ");
int ch = Integer.parseInt(sc.nextLine());
return ch;
}//menu
public static void main(String []args)throws FileNotFoundException, IOException{
Scanner sc = new Scanner(System.in);
ArrayList pList = new ArrayList();
FileReader fr1 = new FileReader("data.txt");
BufferedReader br1 = new BufferedReader(fr1);
String read= br1.readLine();
while(read!= null){ //read file io
StringTokenizer st = new StringTokenizer(read,";");
String name = st.nextToken();
String phone = st.nextToken();
String ic = st.nextToken();
Reading reading = new Reading(name,phone,ic);
pList.add(read);
read = br1.readLine();
}//while
Reading reading = null;
File fi1 = new File("data.txt");
FileWriter fw1 = new FileWriter(fi1,true);
BufferedWriter bw1 = new BufferedWriter(fw1);
PrintWriter pw1 = new PrintWriter(bw1);
int ch = 0;
do{
ch = menu();
if(ch == 1){ // add new participant
System.out.print("Enter Name : ");
String name = sc.nextLine();
System.out.print("Enter Phone Number : " );
String noTel = sc.nextLine();
System.out.print("Enter IC Number : ");
String noIC = sc.nextLine();
System.out.println(); //new line for each data
Participant pt = new Participant( name,noTel,noIC);
pw1.println(pt.toFile());
}
else if(ch == 2){ // search by state
for(int i = 0; i < pList.size() ; i++){
reading = (Reading)pList.get(i); // error here
System.out.print(reading.getName());
}
}
else if(ch == 3){ //sort by name
//call method ...
}
}while(ch != 4);
System.out.print("\n\n\n\t\t\tThank You and See You Again! ");
//close
pw1.close();
}//public
}//class
Reading class to read data from file io
class Reading {
private String name;
private String phone;
private String ic;
public Reading ( String name , String phone , String ic ){
this.name = name;
this.phone = phone;
this.ic = ic;
}
public String getName() { return name;}
public String getPhone() {return phone;}
public String getIc() { return ic; }
public String displayAll(){
return "Name : "+ name + "\n" + "Phone numbers : " +phone + "\n" + "Ic : " +ic + "/n" ;
}
}//class
Here Participant class use to send data to file io
class Participant {
private String name;
private String noTel;
private String noIC;
public Participant ( String name , String noTel , String noIC ){
this.name = name;
this.noTel = noTel;
this.noIC = noIC;
}
public String toFile(){
return name+";"+ noTel + ";" + noIC ;
}//toFile
}//class

First, your pList is a raw-type. That is causing it to ignore your second issue, where you add the wrong variable to the List. Change
ArrayList pList = new ArrayList();
to
List<Reading> pList = new ArrayList<>();
and change
Reading reading = new Reading(name,phone,ic);
pList.add(read);
to
Reading reading = new Reading(name,phone,ic);
pList.add(reading);

Related

Java exiting entire program when parsing an input file

I am getting an error in my code which I cannot seem to wrap my head around. In my code I am parsing a data file and setting the values to my local variables that will later be turned into an object and added to the productList. But Somewhere in my while loop, the program stops running and
1 is printed to standard out and it says build successful (im using netbeans)
I tried catching the exception and printing it out using e.getmessage() but nothing will print and I know for a fact the error is in the try block because I used print statements to find out when the error occurs. This method is also inside a menu function that is not supposed to end the method input finishes.
public void input(ArrayList productList) {
String type = "";
String name = "";
String authors = "";
String publisher = "";
String maker = "";
String productID = "";
String priceS = "";
String yearS = "";
String filepath = "/home/alex/Desktop/CS/products.txt";
try{
File f = new File(filepath);
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String theData = sc.nextLine();
if(theData.contains("type")){
type = theData;
} else if(theData.contains("productID")){
productID = theData;
} else if(theData.contains("name")){
name = theData;
} else if(theData.contains("price")){
priceS = theData;
} else if(theData.contains("year")){
yearS = theData;
} else if(theData.contains("maker")){
maker = theData;
} else if(theData.contains("authors")){
authors = theData;
} else if(theData.contains("publisher")){
publisher = theData;
}
}
} catch(Exception e){
System.out.println("ERROR: " + e.getMessage());
}
}

Java Flat File database full of compiling errors

There are plenty of problems as I am new, I can find spelling and such, but I can't seem to call some of the methods, and referencing some objects also doesn't seem to work. I know it's a lot of code, but this is one puzzle I can't seem to solve, and my grade depends on this. My teacher has no free to help as he is working on a coding project of his own. Please Help me!
import java.io.*;
import java.util.Scanner;
public class FlatFileDatabase{
private final String PATH="table\\";
public boolean createTable(String file, String columns){
//create table
//allows users to specify what meta-information is in each column.
//check for hashtags.
if(!columns.startsWith("#")){
return false;
}
//check for the minimum amount of columns using String split.
if(columns.split("::").length < 2){
return false;
}
//write columns
PrintWriter pw = new PrintWriter(PATH + file);
pw.println(columns);
pw.close();
//try-catch-finally errors and exit
}
public void destroyTable(String table){
//deletes table
File f = new File(PATH + table);
f.delete();
}
public void create(String record, String file) throws IOException{
//makes method for printwriter
PrintWriter pw = new PrintWriter(new FileWriter(PATH+file,true));
pw.println(record);
pw.close();
}
public String findOne(String key, String table){
//open file
File f = new File(PATH + table);
Scanner sc = new Scanner("table.txt");
//the variables are just placeholders
String rawRecord = null;
String[] splitRecord;
String recordKey;
String record = null;
boolean recordNotFound = true;
//read each line until find record
while(recordNotFound && sc.hasNext()){
rawRecord = sc.nextLine();
splitRecord = rawRecord.split("::");
rawRecord = splitRecord[0];
if(key.equals(recordKey)){
record = recordKey;
recordNotFound = false;
}
}
//return
return record;
}
public boolean update(String key, String record, String table){
//helper variables
String contents = "";
String rawRecord;
String splitRecord[];
String recordKey;
//open
File f = new File(PATH + table);
Scanner sc = new Scanner(f);
//search for record
while(sc.hasNext()){
rawRecord = sc.nextLine();
splitRecord = rawRecord.split("::");
rawRecord = splitRecord[0];
if(key.equals(recordKey)){
contents += record;
} else {
contents += rawRecord;
}
}
f.close();
//if found, update record
//make private method of this and finding files
f.create();
//return
}
public boolean destroy(String key, String table){
//update
//return update(" ");
}
public static void main(String[]args){
createTable ct = new createTable();
destroyTable dt = new destroyTable();
findOne fo = new findOne();
update upd = new update();
Scanner sc = new Scanner(System.in);
System.out.print("What would you like to do?/n/n1]create a table/n2]delete table/n3]opentable/n4]update table");
int a = sc.nextInt();
if(a==1){
createTable();
}else if(a==2){
destroyTable();
}else if(a==3){
findOne();
}else{
update();
}
}
}

Open file from user input and then read the values stored on the file

Hi so I have a client and a host. I want the client to open a file whose file name is obtained from user input and then read the numbers stored on the file and send the numbers to the host.
Socket clntSock = new Socket("127.0.0.1", 6000);
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
String msgToSend = input;
byte[] bytesToSend = msgToSend.getBytes();
OutputStream out = clntSock.getOutputStream();
out.write(bytesToSend);
out.close();
clntSock.close();
At the moment thats what I have. I am stuck on how to scan the numbers on the file. Obviously it sends the file name to host as I set
String msgToSend = input;
The file looks like this (Anthony.txt).
1
2
3
4
5
Numbers are stored like that in the file. Any ideas on how could I instantiate a Player object and set the name and scores for the player from the file data and transfer the Player object to the server?
My host code:
ServerSocket servSock = new ServerSocket(6000);
PrintStream fileOut = new PrintStream("Datafromclient.txt");
while (true)
{
Socket clntSock = servSock.accept();
InputStream in = clntSock.getInputStream();
byte[] receiveBuf = new byte[BUFSIZE];
int recvMsgSize = in.read(receiveBuf);
System.out.println("received data >> "+ new String(receiveBuf));
fileOut.println(""+ new String(receiveBuf));
in.close();
clntSock.close();
First I was asked to make a game which creates a player and stores the scores into a file.
Player class:
//Class declaration of Player class
public class Player
{
/*--------------- Data Fields ---------------------------------------
Attributes of the class
*/
private String name;
private int playerId;
private int bestScore;
private static int numberOfPlayers = 0;
private ArrayList<Integer> scores = new ArrayList<Integer>();
/* -------------- CONSTRUCTOR --------------------------------------
*/
public Player(String name)
{
this.name = name;
numberOfPlayers++;
playerId = numberOfPlayers;
}
//Create set method for setName
public void setName(String name)
{
this.name = name;
}
//Create set method for setScores
public void setScore(int score)
{
scores.add(score);
}
//Create get method for getPlayerId
public int getPlayerId()
{
return this.playerId;
}
//Create get method for getName
public String getName()
{
return this.name;
}
//Create get method for getScores
public ArrayList<Integer> getScores()
{
return scores;
}
//Create get method for getBestScore
public int getBestScore()
{
return bestScore;
}
//Method to expose the value of numberOfPlayers
public static int getNumberOfPlayers()
{
return numberOfPlayers;
}
//Create get method for calcualteAverage
public double calculateAverage()
{
Integer sum = 0;
if(!scores.isEmpty())
{
for(Integer score : scores)
{
sum += score;
}
return sum.doubleValue() / scores.size();
}
return sum;
}
The application:
String name;
int scores;
PrintStream fout = new PrintStream(new File("PlayerData2.txt"));
//Create Scanner object
Scanner input = new Scanner (System.in);
while(true)
{
//Ask user for name
System.out.printf("\n Enter Player Name:");
name = input.nextLine();
//Create a Player Object
Player player1 = new Player(name);
for (int i=0; i<5; i++)
{
//Ask user for number input
System.out.println("Please pic a number between 1 - 20");
player1.setScore(Integer.parseInt(input.nextLine()));
Random rand = new Random();
int answer = rand.nextInt(20) + 1;
System.out.println(answer);
System.out.println(""+player1.getScores());
if ((answer >= player1.getScores().get(i)))
{
System.out.println("Your guess is too low");
}
else if(answer <= player1.getScores().get(i))
{
System.out.println("Your guess is too high");
}
}
fout.println( "" + player1.getName() );
fout.println( "" + player1.getScores().get(0) );
fout.println( "" + player1.getScores().get(1) );
fout.println( "" + player1.getScores().get(2) );
fout.println( "" + player1.getScores().get(3) );
fout.println( "" + player1.getScores().get(4) );
This is one way you could do it,
// Use a Scanner to read the File
Scanner readFile = new Scanner(file);
// Loop Through Each Line
while(readFile.hasNext()) {
// Get Number as a Byte
byte[] number = readFile.nextLine().getBytes();
// Write number to OuputStream
out.write(number);
// Flush OuputStream, Never forget to Flush your OutputStreams
out.flush();
}
If you want to send the Numbers all at once you could just store them in an Array or StringBuilder first then do with it what you want.
EDIT
I see you want to send the Player object, not sure how to do that, atleast now you can see how to read the text file.

Scanner from file doesn't seem to be reading file

I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

BinarySearch on Object Array List in Java

I am trying to perform binary search on an object array list. The user must type in admin number to perform search. Here is my code :
File Controller class to read file from .text file
public class FileController extends StudentApp{
private String fileName;
public FileController() {
String fileName = "student.txt";
}
public FileController(String fileName) {
this.fileName = fileName;
}
public ArrayList<String> readLine() {
ArrayList<String> studentList = new ArrayList<String>();
try {
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while (sc.hasNextLine()) {
studentList.add(sc.nextLine());
}
fr.close();
} catch (FileNotFoundException exception) {
System.out.println("File " + fileName + " was not found");
} catch (IOException exception) {
System.out.println(exception);
}
return studentList;
}
Student Class with all the setter & getter and compareTo method
public Student(String adminNo, String name, GregorianCalendar birthDate) {
this.adminNo = adminNo;
this.name = name;
this.birthDate = birthDate;
}
public Student(String record) {
Scanner sc = new Scanner(record);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(sc.next());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
public String toString(){
return (adminNo + " " + name + " " + MyCalendar.formatDate(this.birthDate));
}
public static ArrayList<Student> readStudent(String file) {
FileController fc = new FileController(file);
ArrayList<Student> recs = new ArrayList<Student>();
ArrayList<String> recsReturn = new ArrayList<String>();
recsReturn = fc.readLine();
for (int index = 0; index < recsReturn.size(); index++) {
String input = recsReturn.get(index);
recs.add(new Student(input));
}
return recs;
}
public int compareTo(Student s) {
return Compare(this, s);
}
public int Compare(Student s1, Student s2){
if(s1.getAdminNo().equals(s2.getAdminNo())) {
return 0;
}else{
return 1;
}
}
Executable main method lies here, in StudentSearch Class
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
ArrayList <Student> studentList = new ArrayList <Student> ();
studentList = Student.readStudent("student.txt");
Collections.sort(studentList);
System.out.println("Enter student admin number: ");
String searchAdminNo = sc.next();
int pos = Collections.binarySearch(studentList, new Student(searchAdminNo));
System.out.println(pos);
}
I want to perform search by using the user input admin number. However, here's the error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at StudentGradeApps.Student.<init>(Student.java:22)
at StudentGradeApps.StudentSearch.main(StudentSearch.java:14)
I think the problem lies at the compareTo method and my binary search. Because when I removed them, my program can get the array list fine. The error only occurs when I try to perform search on my object list. Any help would be appreciated.
Thanks in advance.
As the error message say, the exception is occurring within the Student constructor -
public Student(String record) {
Scanner sc = new Scanner(record);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(sc.next());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
You are invoking the constructor here -
int pos = Collections.binarySearch(studentList, new Student(searchAdminNo));
searchAdminNo probably doesn't have that many tokens (delimited by ;) as you are reading in the constructor.

Categories