I am supposed to read strings from a text file and sort them (alphabetically).
The text files include string names like Tory Warren, Guy Cowan. I am able to read all the strings (names) from the file. However, they are all unsorted.I have tried to use collections.sort. Unfortunately, it wouldn't work. Can you please help me with that one?
Here is my error trace:
java.lang.Error: Unresolved compilation problems:
The method sortNames(String) in the type ProcessNames is not applicable for the arguments (ArrayList<String>)
And my code:
public ArrayList<String> sortNames(String filename) throws Exception{
File file = new File(filename);
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(file);
while (scan.hasNext()) {
names.add(scan.nextLine());
Collections.sort(names);
}
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
scan.close();
Collections.sort(names);
return names;
}
My Test Unit:
void testSortNames() {
Collections.sort(namesMatchFile1);
assertArrayEquals(namesMatchFile1.toArray(), processNames.sortNames(namesReadFile1).toArray());
Collections.sort(namesMatchFile2);
assertArrayEquals(namesMatchFile2.toArray(), processNames.sortNames(namesReadFile2).toArray());
Collections.sort(namesMatchFile3);
assertArrayEquals(namesMatchFile3.toArray(), processNames.sortNames(namesReadFile3).toArray());
Collections.sort(namesMatchFile4);
assertArrayEquals(namesMatchFile4.toArray(), processNames.sortNames(namesReadFile4).toArray());
I am new to Java and literally just started a few weeks ago! So please be kind.
Thank you loads for your help.
Your code is fine. You aren't calling the method correctly.
I made a local file at /tmp/test.txt containing this:
300
200
400
500
100
Then I copied your sortNames() method exactly as you posted it and ran it with the following (where Scratch is the name of the class I used):
try {
new Scratch().sortNames("/tmp/test.txt");
} catch (Exception e) {
e.printStackTrace();
}
Your code correctly sorted and printed the contents of the file:
100
200
300
400
500
Related
Now this may sound like a question that has been repeated many times before but I've done a day of research with people that has other reasons for this Issue.
I have a function that reads a part of the save file and its been shown that it does receive the correct data. So the error is that the integer variable completely ignores the new variable and shows no change in the live debugger so like many other post it is not just a duplicate object error. I cant seem to pinpoint what is the main issue is here and it's the last major thing holding me back. Any help would be great and I'm very extremely sorry if I did manage to miss a topic about this on the internet.
Code that fails:
#Override
public void read(List<String> data) {
//world positions are not being changed at all
System.out.println(data.get(1));
int test = Integer.valueOf(data.get(1).replaceAll("[^\\d.]", ""));
worldXPos = Integer.valueOf(data.get(0).replaceAll("[^\\d.]", ""));
worldZPos = test;
}
Another class that gives the data:
public void readSaveFunctions(){
if(!gameSaves.exists()){
gameSaves.mkdir();
}
String currentLine;
try {
List<String> data = new ArrayList<String>();
FileReader read = new FileReader(currentFile);
BufferedReader reader = new BufferedReader(read);
String key = "";
while((currentLine = reader.readLine()) != null){
if(currentLine.contains("#")){
key = currentLine;
data = new ArrayList<String>();
}else if(currentLine.contains("*end")){
for(int i = 0; i < saves.length; i++){
String tryKey = "#" + saves[i].IDName();
if(tryKey.equals(key)){
key = "";
saves[i].read(data);
}
}
}else data.add(currentLine);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Another way of explaining it is this:
Debugger is set to step - to - step mode so I see each line getting executed at human speed then I get to a line like this but all of the ones setting the variables have the same effect:
worldXPos = Integer.valueOf(data.get(0).replaceAll("[^\\d.]", ""));
and the debugger shows the two integers having different numbers but the instant class variable stays exactly the same with no effect in the debugger after the line goes through.
Update:
I forgot to mention the method has a #override method and it seems that this #override may be causing this issue, now finally I may have a path to follow again
So I found my answer: The AWT thread manage to activate calling a method from another class that changed the integer before it could be read. It really though me off at first because the debugger only showed one of the threads and with no way to know the other one was actively changing it to early. Thanks for all the help :P.
(For this I need to use Arrays - not Array lists. Snipping code to make it easier to follow. Renaming variables and constants to label so others who read this later understand what I am doing better.)
At the class level I have my arrays defined like so:
private static final int CONSTANT = 20;
public static String[] arrayName = new String[CONSTANT - 1];
and in the main method I am pointing to the method like so:
readArrays("filenName.txt", arrayName);
and a line like that points to the following complete method which is where the error occurs:
public static void readArrays(String codeFile,
String[] Arrays)
{
try ( Scanner fin = new Scanner ( new File(codeFile) ); )
{
for (int i = 0; i < CONSTANT - 1; i++)
{
Arrays[i] = fin.next();
}
}
catch (FileNotFoundException e)
{
System.err.println( "Read Error: " + e.getMessage() );
}
It shows no errors in NetBeans, but in the console window the exact error message is:
run:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at mp06.Main.readArrays(Main.java:47)
at mp06.Main.main(Main.java:33)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
What is causing this error? Ultimately, my goal is to write the entire contents of multiple text files to multiple arrays using the same method and without using any other approach.
try ( Scanner fin = new Scanner ( new File(codeFile) ); )
{
for (int i = 0; i < CONSTANT - 1 && fin.hasNext(); i++)
{
Arrays[i] = fin.next();
}
}
catch (FileNotFoundException e)
{
System.err.println( "Read Error: " + e.getMessage() );
}
You also need to check Scanner has next.
In Java8, you can use stream to read file:
List<String> contents = Files.lines(Paths.get("filenName.txt")).collect(Collectors.toList());
The below code might help you.
There are couple of things, you have to check whether next element is exists in scanner before you call next() and the other one is the constant "20", it will end up with Array Index Bounds exception if the size exceeds 20.
Adding them in the list and converting them to an array will resolve this. Try the below code.
List<String> list = new ArrayList<String>();
while (fin.hasNext()) {
list.add(fin.next());
}
String[] array = new String[list.size()];
list.toArray(array);
for (String str: array) {
System.out.println(str);
}
Java noob working on a project where I'm supposed to display data obtained from a text file onto grids. Project is essentially written, but output displays this exception:
run:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50)
at boggle.Boggle.main(Boggle.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Boggle.java:27 links to a line of code in the main method of my superclass Boggle.java. The line is supposed to call one of the methods in my class ReadDataFile.java. The line reads dataRead.populateData(); (//2. on the comments below), and in context the main method looks like:
public static void main(String[] args) { //main() method begins
// TODO code application logic here
ReadDataFile dataRead = new ReadDataFile("BoggleData.txt"); //1. instance of class ReadDataFile created
dataRead.populateData(); //2. populateData() method called
boggleData = dataRead.getData(); //3. member variable set equal to getData() method
Board boggleBoard = new Board(boggleData); //4. instance of class Board created, passing data as argument
boggleBoard.shakeDice(); //5. shakeDice() method called
} //main() method ends
ReadDataFile.java:50 links to a line in a method called populateData() inside of my subclass ReadDataFile.java. The line is input.next(); and it's in the finally component of a try-catch-finally I created for the class. In context, the populateData() method looks like:
public void populateData(){ //populateData() method begins
try{ //try begins
URL url = getClass().getResource(dataFile); //1. instance of class URL created from file name
File file = new File(url.toURI()); //2. instance of class File based on url
input = new Scanner(file); //3. member variable initialized based on file
while(input.hasNext()){ //4. while loop goes through data file
data.add(input.next()); //a. data from file added to ArrayList
}
} //try ends
catch(Exception ex){ //catch begins
System.out.println(ex.toString());
ex.printStackTrace();
} //catch ends
finally{ //finally begins
input.next();
} //finally ends
} //populateDate() method ends
Basically, I'm having trouble figuring out how I can get around this exception. The actual goal of the project is to display data in grids, but I only get a notice that an exception has been found in the output. The code compiles fine, so I'm not worried about misplaced semicolons or incorrect data types. I'm new to the Java language, and while books and other stackoverflow questions have solved some of my problems, this exception has gotten me stuck.
Would anybody be able to provide some feedback on just what I need to do to get around the exception showing up in my output, what's causing it, or at least steer me in the right direction? I'd really appreciate any helpful comments. Thanks.
Your exception stack-trace shows where the problem is:
at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50)
At line 50 you have this:
finally{ //finally begins
input.next();
}
The problem is that you have already exhausted the file with a loop you previously executed:
while(input.hasNext()){ //4. while loop goes through data file
data.add(input.next()); //a. data from file added to ArrayList
}
I think you meant to close in your finally.
finally{ //finally begins
input.next();
}
should (almost certainly) be
finally{
input.close();
}
Or you could use try-with-resources to close your Scanner like
public void populateData(String dataFile) {
try {
URL url = getClass().getResource(dataFile);
File file = new File(url.toURI());
try (Scanner input = new Scanner(file)) {
while (input.hasNext()) {
data.add(input.next());
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
}
Ok so I'm about to start pulling my hair out. I thought file input was a little tricky, but oh man then there is file output. I am trying to write an array of coordinates stored in an object to a file. In C++ this was easy peasy, but for the love of God I cannot figure this out.
public static void outFile(int intersectionsIndex, Coordinate arg[], Coordinate avgPoint) {
File file = new File("resource/result.txt");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file);
int i = 0;
while (i < intersectionsIndex) {
writer.print(arg[i].getX());
writer.print(" ");
writer.println(arg[i].getY());
i++;
}
writer.print("Predicted Coordinate: ");
writer.print(avgPoint.getX());
writer.print(" ");
writer.println(avgPoint.getY());
writer.close();
return;
}
I am constantly getting the same error no matter what method of IO I use. I followed some posts on here with similar problems but to no avail. Any suggestions or other methods? I am probably missing something basic.
Edit: sorry error is
Error:(83, 30) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Which is the "PrintWriter writer = newPrintWriter(file); line.
UPDATE: Problem solved. Working code below:
public static void outFile(int intersectionsIndex, Coordinate arg[], Coordinate avgPoint) throws Exception{
File file = new File("resource/result.txt");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file);
int i = 0;
while (i < intersectionsIndex) {
writer.print(arg[i].getX());
writer.print(" ");
writer.println(arg[i].getY());
i++;
}
writer.print("Predicted Coordinate: ");
writer.print(avgPoint.getX());
writer.print(" ");
writer.println(avgPoint.getY());
writer.close();
return;
}
It looks like the error that you get is actually a compile-time error, not a runtime error.
The contructor PrintWriter(File) declares a checked FileNotFoundException in its signature, therefore you either need to surround its invocation with try ... catch block, or to declare that exception in throws declaration of your method to catch it later.
See also:
Lesson: Exceptions
Always try to avoid absolute path because the same code might not work on another system.
I suggest you to place it inside the project under resources folder.
You can try any one based on file location.
// Read from resources folder parallel to src in your project
File file1 = new File("resources/results.txt");
// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/results.txt").toURI());
You might forget to increment i in while loop. Add i++ to avoid infinite loop.
Try
while (i++ < intersectionsIndex) {...}
OR
while (i < intersectionsIndex) {
...
i++;
}
I'm writing a little program to analyze some data I have and this code, which worked yesterday, is no longer working.
For the life of me, I can't tell why. To my eye, everything is as it should be. I've tried re-syncing the folder on my computer with my GitHub Repo and still was receiving the same error. Maybe a second pair of eyes could help me out?
The text file being read from can be found here.
Here are the methods referred to by the stack trace:
public static void main(String[] args) throws IOException{
FileManagementMethods fmm = new FileManagementMethods();
fmm.runProgram();
}
void runProgram() throws IOException{
boolean doesFileExist = doesFileExist();
if(doesFileExist){
int numLines = getNumberOfLines();
String[] linesFromFile = getLines(numLines);
WeatherAnalysisMethods wam = new WeatherAnalysisMethods();
wam.parseFileAverageTemp(linesFromFile);
wam.parseFileAverageHumidity(linesFromFile);
wam.predictNextTemperature(linesFromFile);
} else{
try {
throw new IOException("Could not find log.txt in default directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
void parseFileAverageHumidity(String[] linesFromFile) throws IOException{
int[] humiditiesFromFile = new int[linesFromFile.length];
humiditiesFromFile = getHumiditiesFromFile(linesFromFile.length);
int averageFromFile = 0;
for(int i = 0; i < humiditiesFromFile.length; i++){
averageFromFile += humiditiesFromFile[i];
}
averageFromFile = averageFromFile / humiditiesFromFile.length;
String outString = "Average humidity for whole file = " + averageFromFile;
FileManagementMethods fmm = new FileManagementMethods();
fmm.saveAnalyzedData(outString);
}
int[] getHumiditiesFromFile(int numLines){
int[] humiditiesFromFile = new int[numLines];
FileManagementMethods fmm = new FileManagementMethods();
String[] lines = fmm.getLines(numLines);
int i = 0;
while(1 < numLines){
String[] lineDivides = lines[i].split(",");
String tempString = lineDivides[4];
humiditiesFromFile[i] = Integer.parseInt(tempString);
i++;
}
return humiditiesFromFile;
}
Line 51:
String tempString = lineDivides[4];
And here is the stack trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at org.weatheralert.analysis.WeatherAnalysisMethods.getHumiditiesFromFile(WeatherAnalysisMethods.java:51)
at org.weatheralert.analysis.WeatherAnalysisMethods.parseFileAverageHumidity(WeatherAnalysisMethods.java:22)
at org.weatheralert.analysis.FileManagementMethods.runProgram(FileManagementMethods.java:22)
at org.weatheralert.analysis.Main.main(Main.java:9)
If you guys need more information, don't hesitate to ask.
The problem is here, inside your getHumiditiesFromFile method:
while(1 < numLines){
It should be
while (i < numLines){
Since inside this loop you're calling humiditiesFromFile[i].
As Foo Bar User noted in comment, the error may be here:
String tempString = lineDivides[4];
It would be better to make sure there are at least 4 items in that array.
Besides that, the error noted in the section above (assuming it's not a typo) could also throw this Exception for being in an infinite loop.
You've hardcoded a 4 here without checking to see if it exists:
String tempString = lineDivides[4];
You will need to do some data validation beforehand. You're assuming that the line you read has at least three commas. Either change the code to check, or validate the file.
So, it was a silly issue.... JSoup had a couple bad connections and didn't save some of the data I needed it to save. So it didn't recognize some of the lines of data.
Once I fixed the actual data, it runs without issue again.
I apologize for wasting your time.