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());
}
}
Related
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);
I currently have 2 loops, one which gets a timestamp, and another while loop to find the mapped information based off that time stamp and output in a certain way.
Issue I have is I am currently looping through a text, and want it to start reading the file from the beginning again when the isdone="N" for the second loop, however, this does not seem to be the case.
Code so far:
public static void organiseFile() throws FileNotFoundException {
String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1";
Scanner fileIn = new Scanner(new File(directory + "_temp.txt"));
Scanner readIn = new Scanner(new File(directory + ".txt"));
PrintWriter out = new PrintWriter(directory + "_ordered.txt");
ArrayList<String> lines = new ArrayList<String>();
String readTimeStamp = "";
String timeStampMapping = "";
String outputFirst = "";
String outputSecond = "";
String outputThird = "";
String previousTimeStamp = "";
String doneList = "";
String isdone = "";
int counter = 1;
// Loop to get time stamps
while(fileIn.hasNextLine()) {
readTimeStamp = fileIn.nextLine();
if(readTimeStamp != null && readTimeStamp.trim().length() > 0) {
readTimeStamp = readTimeStamp.substring(12, 25);
System.out.println(readTimeStamp);
// Previous time stamp found, no need to loop through it again
if(doneList.contains(readTimeStamp))
isdone = "Y";
// Counter in place to stop outputting the first record, otherwise output file and clear variables down
else if(!previousTimeStamp.equals(readTimeStamp) && counter > 1) {
out.println(outputFirst + outputSecond + outputThird);
System.out.println("Outputting....");
outputFirst = "";
outputSecond = "";
outputThird = "";
counter = 1;
}
// New time stamp found, start finding values in second loop
else
isdone = "N";
// Secondary loop to find match of record
while(readIn.hasNextLine() && isdone.equals("N")) {
System.out.println("Mapping...");
timeStampMapping = readIn.nextLine();
System.out.println(timeStampMapping);
// When a record has been found with matching time stamps, start ordering
if(timeStampMapping.contains(readTimeStamp)) {
previousTimeStamp = readTimeStamp;
System.out.println(previousTimeStamp);
if(timeStampMapping.contains("[EVENT=agentStateEvent]")) {
outputFirst += timeStampMapping + "\r\n";
} else if(timeStampMapping.contains("[EVENT=TerminalConnectionCreated]")) {
outputSecond += timeStampMapping + "\r\n";
} else {
outputThird += timeStampMapping + "\r\n";
doneList += readTimeStamp + ",";
}
counter++;
}
}
}
}
System.out.println("Outputting final record");
out.println(outputFirst + outputSecond + outputThird);
System.out.println("Complete!");
out.close();
}
You can use Scanner.reset() to reset it to the beginning of the file. For example, after your second while-loop include:
if (isdone.equals("Y")) {
fileIn.reset();
}
Btw: why are you using String for isdone instead of boolean??
I am facing a problem in the following code. I am trying to run the program and it terminates when it hits empty space in my input. How else I should approach this.
try {
BufferedReader sc = new BufferedReader(new FileReader(text.txt);
ArrayList<String> name = new ArrayList<>();
ArrayList<String> id = new ArrayList<>();
ArrayList<String> place = new ArrayList<>();
ArrayList<String> details = new ArrayList<>();
String line = null;
while ((line = sc.readLine()) !=null) {
if (!line.trim().equals("")) {
System.out.println(line);
if (line.toLowerCase().contains("name")) {
name.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("id")) {
id.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("location")) {
place.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("details")) {
details.add(line.split("=")[1].trim());
}
}
}
PrintWriter pr = new PrintWriter(new File(text.csv));
pr.println("Name;Id;;Location;Details");
for (int i = 0; i < name.size(); i++) {
pr.println(name.get(i) + ";" + id.get(i) + ";" + place.get(i) + ";" + details.get(i));
}
pr.close();
sc.close();
} catch (Exception e) {
e.printStackTrace();
} }
My Input looks like
name = abc
id = 123
place = xyz
details = hsdyhuslkjaldhaadj
name = ert
id = 7872
place =
details = shahkjdhksdhsala
name = sfd
id = 4343
place = ksjks
Details = kljhaljs
when im trying to execute then above text my program terminates at place = "null" because of no value there.I need the output as an empty space created in place ="null" and print the rest as follows in a .csv file
If you process the location, line.split("=")[1] could result in an ArrayIndexOutOfBoundException and line.split("=")[1].trim() could result in a NullPointerException.
You can avoid this by testing your parsed result.
Instead of place.add(line.split("=")[1].trim());, do place.add(parseContentDefaultEmpty(line));, with:
private String parseContentDefaultEmpty(final String line) {
final String[] result = line.split("=");
if(result.length <= 1) {
return "";
}
final String content = line.split("=")[1];
return content != null ? content.trim() : "";
}
First there is a issue,your input file contains key as "place" but your are trying for word "location"
if (line.toLowerCase().contains("location")) { //this must be changed to place
place.add(line.split("=")[1].trim());
}
Modified the code snippet as below.check it
while ((line = sc.readLine()) != null) {
if (!line.trim().equals("")) {
System.out.println(line);
if (line.toLowerCase().contains("name")) {
name.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("id")) {
id.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("place")) {
// change done here to add space if no value
place.add(line.split("=").length > 1 ? line.split("=")[1]
.trim() : " ");
}
if (line.toLowerCase().contains("details")) {
details.add(line.split("=")[1].trim());
}
}
}
Setting question to line doesn't appear to change what line is read later (if you're wanting the line to advance before it hits the while loop).
When I try to compile my code I get the message
Main.java:31: error: not a statement
String bed = f.split(" ")
and also
error: ';' expected
String bed = f.split(" ");
I don't understand what's going on. I need to assign part of a file to a string.
Here's the code :
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String[] args){
if ( args[0] == null){
System.out.println("File not Found");
return;
}
try {
File driver = new File (args[0]);
Scanner j = new Scanner( driver );
int i = 0;
while( j.hasNextLine()) {
String f = j.nextLine();
if (f.isEmpty() || f.startsWith("/")){ //If the String f is empty or has / it will continue reading the nextline after the / or space
continue;
if (f.startsWith("d")) {
String d = f.split(" ");
}
if (f.startsWith("b")) {
String b = f.split(" ");
}
if (f.startsWith("bed"))
String bed = f.split(" ");
}
System.out.println(f);
}
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage);
}
}
}
.split() method returns an array so you should store it in an array, not in a string. Your code should be string b[]=f.split(" ") rather than storing it in string b
The split method returns splits the string based on the regex and returns an String array.
What you have here is String d = f.split(" ");, here you are trying to assign a string array to a string, and that is wrong.
It should instead say String[] d = f.split(" ");
I had this error.
I found a solution like below.
Error code
String a = "I goto the school";
String [] b = a.split("\\\s"); // error not a statement
Run code
try
{
String a = "I goto the school";
String [] b = a.split("\\\s");
}
catch(exception e)
{
}
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