Class issue java - java

I wrote a flesch reading program that uses another class. I was under the impression that simply having the two classes saved in the same folder would enable one to access the other but I am getting errors. Any ideas.
The error I am getting is:
Flesch.java:36: cannot find symbol
symbol : method getSyllableCt()
location: class Flesch
sllyablesCt = getSyllableCt();
flesh is here:
public class Flesch{
public static void main(String args[])throws Exception{
int syllablesCt,
wordCt,
sentenceCt;
double flesch;
String listStr;
StringBuffer sb = new StringBuffer();
String inputFile = JOptionPane.showInputDialog("What file do you want to sort?");
BufferedReader inFile = new BufferedReader(new FileReader(inputFile));
sb.append(inFile.readLine());
//listStr = inFile.readLine();
while (inFile.readLine() != null){
sb.append(inFile.readLine());
//listStr = inFile.readLine();
}
Sentence sentence = new Sentence(sb);
wordCt = getWordCt();
sentenceCt = getSentenceCt();
System.out.println("The sentence count is" + sentenceCt);
System.out.println("The word count is" + wordCt());
Word word = new Word(getWords());
sllyablesCt = getSyllableCt();
System.out.println("The syllable count is" + syllablesCt);
flesch = (.39 * wordCt / sentenceCt) + (11.8 * syllablesCt / wordCt) - 15.59;
System.out.println("The Flesch Readability of this document is" + flesch);
inFile.close();
}
}

If the methods live in another class they need to either be (a) referenced as static methods, or (b) called on an instance of the class.
// Static method
int syllableCount = TheOtherClassName.getSyllableCt();
// Instance method
TheOtherClassName otherClass = new TheOtherClassName();
int syllableCount = otherClass.getSyllableCt();
However it's not clear where the methods in question live, or how they're getting their data.

if the method is in another class, you need to be make the class static.
ClassName.getSyllableCt();

sllyablesCt = getSyllableCt();
Your code has a typo. That variable doesn't exist. Change it to
syllablesCt = getSyllableCt();

Related

java read from file. the last row overwrites the values of the previous lines in list

I have a file name 1.txt
Coupe 1 2
Coupe 3 4
and I have a code
br = new BufferedReader(new FileReader("1.txt"));
String tmp = "";
while ((tmp = br.readLine()) != null) {
String[] s = tmp.split("\\s");
comfortName = s[0];
tickets = Integer.parseInt(br.readLine());
baggage = Integer.parseInt(br.readLine());
// next code send to constructor of class from value of comfort name a parametrs.
Class[] e = new Class[]{Integer.TYPE,Integer.TYPE};
comfortName = "second.objects.carriages.type." + comfortName;
Class carriageClass = Class.forName(comfortName); Constructor constructor = carriageClass.getDeclaredConstructor(e);
passenger = (Passenger) constructor.newInstance((tickets),(baggage));
// the next line add to list a value from constructor
carriage.addPassenger(passenger);
add passenger code:
public boolean addPassenger(Passenger passenger) {
totalPassenger +=Passenger.getTickets();
totalBaggage+=Passenger.getBaggage();
return Carriage.getPassengerList() .add(passenger);
}
So the result when I send it to list have something like that:
Coupe 3 4
Coupe 3 4
But from debugger I see that values reading good. but always the last row
overwrites the values ​​of the previous lines in list .
So when I send only one row it's working
You have a typo in your code
I believe you should get tickets and baggage from the splitted array
tickets = Integer.parseInt(s[1]);
baggage = Integer.parseInt(s[2]);
instead of reading next lines, below will throw exception
tickets = Integer.parseInt(br.readLine());
baggage = Integer.parseInt(br.readLine());
The java.lang.Class.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
This sample code is working fine for me.
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/src/1.txt"));
String tmp = "";
while ((tmp = br.readLine()) != null) {
String[] s = tmp.split("\\s+");
String comfortName = s[0];
int tickets = Integer.parseInt(s[1]);
int baggage = Integer.parseInt(s[2]);
System.out.println(comfortName + tickets + baggage);
}
br.close();
}
on console :
Coupe12
Coupe34
Check your Passenger constructor that you create instance.
passenger = (Passenger) constructor.newInstance((tickets),(baggage));
The problem is at you constructor. If you constructor create new instance of Passenger object it will be ok. You constructor should be like that:
private Passenger(int tickets, int baggage){
this.tickets = tickets;
this.baggage = baggage;
}

Unable to Read a Text File via BufferedReader

I am unable to read a text file via a BufferedReader Object. However I can successfully write to the same text file via a BufferedWriter Object.
The intent of my program is to read a text file called queryCountFile.txt which will then able to figure out how many Query Objects (my custom object) have been previously created. From there, I will then be able to create as many Query Objects as a want while being able to keep track of the number of said Queries.
The function that tries (and fails) to read from the text file is called findNumberOfQueries(). It is located in my file called Query.java
Can anyone understand why I am unable to read from the text file?
QuickControllerApplication.java
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class QuickControllerApplication {
public static void main(String[] args) {
SpringApplication.run(QuickControllerApplication.class, args);
//everthing below this line is for testing purposes
Query littleQuery = new Query(101L);
//littleQuery.testPrint();
littleQuery.generateQueryID();
System.out.println(littleQuery.findNumberOfQueries());
}
}
Query.java
/**************************************************************
* queryIDNumber - a long that holds the individual data of an
* individual query. Each query will have a unique number
* associated with it.
**************************************************************/
public class Query {
final Long MIN_ID_NUMBER = 1L; //minimum ID Number that can be ever generated by the program
final String QUERY_COUNT_FILE = "queryCountFile.txt"; //this file will simply hold a number that states how many queries have been created
final int SKIP_NUM_LINES_IN_FILE = 2; //the first X number of lines that will skipped in QUERY_COUNT_FILE
//final Long MAX_ID_NUMBER = 9223372036854775807L; //maximum ID Number that can be ever generated by the program
private Long queryID; //each query must have a unique ID Number which will go in the URL when the user is viewing the result of the query search.
private static Long totalQueryIDs = 0L; //holds the value of how many queries have been created over the life of the program
public Query(Long previouslyGeneratedIDNumber)
{
generateQueryID();
//totalQueryIDs++;
//OTHER FUNCTION CALLS
//WILL PROBABLY GO
//HERE LATER...
}
/**************************************************************
* generateQueryID - Generate a ID Number for a query. ID
* Number must be unique, and then is assigned to queryID
**************************************************************/
public void generateQueryID(){
Long generatedNumber;
//Finds the totalQueryIDs stored in QUERY_COUNT_FILE
generatedNumber = findNumberOfQueries();
if (generatedNumber <= MIN_ID_NUMBER){
totalQueryIDs = MIN_ID_NUMBER;
}
else {
totalQueryIDs = generatedNumber + 1L;
}
queryID = totalQueryIDs;
}
/**************************************************************
* findNumberOfQueries - This function finds out how many
* queries have been generated so far. This function will check
* a text file that will contain the past number of queries
* that have been generated.
**************************************************************/
public Long findNumberOfQueries(){
//Check a file. If queryCountFile.txt is not found then numberOfQueries is considered 0 and becomes 1?
try {
Date date = new Date();
//Assume default encoding.
FileWriter fileWriter = new FileWriter(QUERY_COUNT_FILE);
FileReader fileReader = new FileReader(QUERY_COUNT_FILE);
//Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
//Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
bufferedWriter.write("FILE LAST WRITTEN TO ON: " + date + "\n");
bufferedWriter.write("totalQueryIDs:\n");
bufferedWriter.write("5");
//reading from QUERY_COUNT_FILE
try{
System.out.println("got here\n"); //debug statement
String line; //temp var
//skip first SKIP_NUM_LINES_IN_FILE lines in QUERY_COUNT_FILE
for (int count = 0; count < SKIP_NUM_LINES_IN_FILE; count++) {
bufferedReader.readLine();
}
line = bufferedReader.readLine();
while (line != null) {
System.out.println("stuff bufferedReader got: " + line);
}
}
catch(IOException ex) {
System.out.println("Error reading to file '" + QUERY_COUNT_FILE + "'");
}
//Close the file.
bufferedWriter.close();
bufferedReader.close();
}
catch(IOException ex) {
System.out.println("Error writing to file '" + QUERY_COUNT_FILE + "'");
}
return totalQueryIDs;
}
}
Let me suggest you another way of reading your lines using most recent APIs method which make it easier to read and maintain (at least in my opinion) :
try(final Stream<String> fileStream = Files.lines(Paths.get("queryCountFile.txt")){
fileStream.skip(SKIP_NUM_LINES_IN_FILE)
.forEach(line -> processMyLine(line));
}
For completeness, the problem in your example is that you never re-assign line variable in your loop :
while(line != null)
should be :
while((line = bufferedReader.readLine()) != null)

Read a text file to an array Java

I know there are many questions about reading text files here but I have gone through all of them and I think I'm having some difficulty with syntax or SOMETHING because nothing that I've been trying has been working at all.
What I'm attempting to do is this:
1) read a text file inputed by user
2) copy each individual line into an array, so each line is its own element in the array
I feel like I am very close but for some reason I can't figure out exactly how to get it to work!
Here is the relevant code I have right now:
I keep getting out of bounds exceptions in three locations which I've marked off.
Been working on this for quite a while not sure what to do next! Any ideas?
import java.io.IOException;
import java.util.Scanner;
public class FindWords {
public static void main (String args[]) throws IOException{
FindWords d = new Dictionary();
((Dictionary) d).dictionary(); //********* out of bounds here
}
/**
* Validates and returns the dictionary inputed by the user.
*
* #param
* #return the location of the dictionary
*/
public static String getDict(){
///////////////////ASK FOR DICTIONARY////////////////////
System.out.println("Please input your dictionary file");
//initiate input scanner
Scanner in = new Scanner(System.in);
// input by user
String dictionary = in.nextLine();
System.out.println("Sys.print: " + dictionary);
//make sure there is a dictionary file
if (dictionary.length() == 0){
throw new IllegalArgumentException("You must enter a dictionary");
}
else return dictionary;
}
}
which calls on the class Dictionary:
import java.io.*;
public class Dictionary extends FindWords{
public void dictionary () throws IOException{
String dict = getDict();
String[] a = readFile(dict); //********** out of bounds here
int i = 0;
while(a[i] != null){
System.out.println(a[i]);
i++;
}
}
public static String[] readFile(String input) throws IOException{
//read file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
System.out.println ();
int count = 0;
String[] array = new String[count];
try{
while (br.readLine() != null){
array[count] = br.readLine(); //********out of bounds here
count++;
}
br.close();
}
catch (IOException e){
}
return array;
}
}
Thank you for looking!
Edit: Just fyi: I have my .txt file in the parent project folder.
Have you tried this?:
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
and then transform your list to an array if you want:
String[] myLines = lines.toArray(new String[lines.size()]);
You start with an array size of zero...
int count = 0;
String[] array = new String[count];
Several issues here :
In Java, you can't expand arrays, i.e you have to know their length in advance when you instantiate them. Hence the ArrayOutOfBoundException. To make this easy, I suggest that you use an ArrayList instead.
In your while loop, you're making 2 calls to br.readLine(), so basically you're skipping one line out of 2.
You are initializing a zero-length array, hence the exception on the first iteration:
int count = 0;
String[] array = new String[count];
Since you probably don't know the expected size, work with a List instead:
List<String> list = new ArrayList<>();
String thisLine = null;
try{
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
}
You can get the total size afterwards by:
list.size();
Or even better, go with morganos solution and use Files.readAllLines().

Identifying each word in a file

Importing a large list of words and I need to create code that will recognize each word in the file. I am using a delimiter to recognize the separation from each word but I am receiving a suppressed error stating that the value of linenumber and delimiter are not used. What do I need to do to get the program to read this file and to separate each word within that file?
public class ASCIIPrime {
public final static String LOC = "C:\\english1.txt";
#SuppressWarnings("null")
public static void main(String[] args) throws IOException {
//import list of words
#SuppressWarnings("resource")
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> temp = new ArrayList<String>();
//Find number of lines in txt file
String line;
while ((line = File.readLine()) != null)
{
temp.add(line);
}
//Identify each word in file
int lineNumber = 0;
lineNumber++;
String delimiter = "\t";
//assess each character in the word to determine the ascii value
int total = 0;
for (int i=0; i < ((String) line).length(); i++)
{
char c = ((String) line).charAt(i);
total += c;
}
System.out.println ("The total value of " + line + " is " + total);
}
}
This smells like homework, but alright.
Importing a large list of words and I need to create code that will recognize each word in the file. What do I need to do to get the program to read this file and to separate each word within that file?
You need to...
Read the file
Separate the words from what you've read in
... I don't know what you want to do with them after that. I'll just dump them into a big list.
The contents of my main method would be...
BufferedReader File = new BufferedReader(new FileReader(LOC));//LOC is defined as class variable
//Create an ArrayList to store the words
List<String> words = new ArrayList<String>();
String line;
String delimiter = "\t";
while ((line = File.readLine()) != null)//read the file
{
String[] wordsInLine = line.split(delimiter);//separate the words
//delimiter could be a regex here, gotta watch out for that
for(int i=0, isize = wordsInLine.length(); i < isize; i++){
words.add(wordsInLine[i]);//put them in a list
}
}
You can use the split method of the String class
String[] split(String regex)
This will return an array of strings that you can handle directly of transform in to any other collection you might need.
I suggest also to remove the suppresswarning unless you are sure what you are doing. In most cases is better to remove the cause of the warning than supress the warning.
I used this great tutorial from thenewboston when I started off reading files: https://www.youtube.com/watch?v=3RNYUKxAgmw
This video seems perfect for you. It covers how to save file words of data. And just add the string data to the ArrayList. Here's what your code should look like:
import java.io.*;
import java.util.*;
public class ReadFile {
static Scanner x;
static ArrayList<String> temp = new ArrayList<String>();
public static void main(String args[]){
openFile();
readFile();
closeFile();
}
public static void openFile(){
try(
x = new Scanner(new File("yourtextfile.txt");
}catch(Exception e){
System.out.println(e);
}
}
public static void readFile(){
while(x.hasNext()){
temp.add(x.next());
}
}
public void closeFile(){
x.close();
}
}
One thing that is nice with using the java util scanner is that is automatically skips the spaces between words making it easy to use and identify words.

Reading a customers name in a txt file with File Reader

My problem is that I can't figure out how to read the customers name with File Reader.
I am making a reservation system and I need to know of the customer already exist. That's why I have to read my Customers.txt file so I can check if someone is already a customer. If he is not I will make a new one with File writer(I Already have the code).
The meaning of this reservation system is to make reservations with a barber. I have to put the reservations in another txt file called Reservations.txt , and in that file you can see each reservation time and who made the reservation.
Thanks for the help!
This is the code I already have:
(some comments are in Dutch but I will translate them )
package nielbutaye;
import java.io.*;
import java.util.UUID;
/**
* #author Niel
*
*/
public class Klant {
//declaration that represents the text
public static String S;
public static String NEWLINE = System.getProperty("line.separator");
/**
* constructor
*/
public Klant(){}
/**
* #return
* By giving the name of the customer you will get all the data from the customer
*/
public double getCustomer() {
return 0 ;
}
/**
* Make a new customer
*/
public void setNew customer(){
// make a newSimpleInOutDialog
SimpleInOutDialog input = new SimpleInOutDialog("A new customer");
//input
S = "Name customer: " + input.readString("Give in your name:");
WriteToFile();
S = "Adress: " + input.readString("Give your adress");
WriteToFile();
S = "Telephonenummber: " + input.readString("Give your telephonenumber");
WriteToFile();
//making a customerID
UUID idCustomer = UUID.randomUUID();
S = "CustomerID: " + customerID.toString();
WriteToFile();
}
public void WriteToFile(){
try{
FileWriter writer = new FileWriter("L:\\Documents/Informatica/6de jaar/GIP/Customer.txt", true);
BufferedWriter out = new BufferedWriter(writer);
//Wrting away your data
out.write(S + NEWLINE);
//Closing the writer
out.close();
}catch (Exception e){//Catch when there are errors
System.err.println("Error: " + e.getMessage());
}
}
}
A BufferedReader() has a method named readLine(), which you can use to read a line from a file:
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
while ((line = br.readLine()) != null)
{
...
}
br.close();
From your WriteToFile() method it seems a customer's details occupies four lines, with the name of the customer appearing on the first line. When searching for a customer, arrange the while loop to only examine every fourth line read.
Other points:
There appears to be no reason for S to be a member variable, nevermind a static. Just declare a local String instance in setNewCustomer() and pass it as an argument to WriteToFile().
Instead of defining a NEWLINE variable you can use BufferedWriter's newLine() method.

Categories