The goal is to fill an ArrayList with custom Country objects made up of information from a separate text file. The while loop gives me the "identifier expected" error, and I'm at my wit's end trying to fix it.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
public class Driver {
public static void main(String[] args) {
//Instance variables
Scanner sc;
Country next = new Country();
String reader;
int size;
ArrayList<Country> ledger = new ArrayList<Country>();
//Suppressing this exception because I know it's there.
#SuppressWarnings("unreported exception FileNotFoundException; must be caught or declared to be thrown")
sc = new Scanner(new File("testLedger.txt"));
//"<identifier> expected" error
while (sc.hasNext()) {
next.setName(sc.nextLine());
next.setFaith(sc.nextLine());
next.setInfo(sc.nextLine());
next.setOrder(sc.nextInt());
ledger.add(next);
}
//Test accessor methods and filling of the ArrayList
for (int i = 0; i < ledger.size(); i++) {
System.out.println(ledger.get(i));
}
}
}
First, your code will not compile. You need to handle the exceptions. As in this case you are just running a test, you can use a Throw in the main method.
try {
sc = new Scanner(new File("testes.txt"));
while (sc.hasNext()) {
next.setName(sc.nextLine());
next.setFaith(sc.nextLine());
next.setInfo(sc.nextLine());
next.setOrder(sc.nextInt());
ledger.add(next);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
Second, look at the setters of your Country class and see if the method types are compatible with what you are using in the while.
For example:
sc.nextLine () // will return a String
sc.nextInt () // will return an int
your setters should be compatible with this
public void setOrder(int order){
this.order = order;
}
and Finally, as mentioned by #Dawood in comments, you need do see stackoverflow.com/q/13102045
Related
Basically, I am running a few tests for a simple CLI game I am making, and initially all of my variables/objects were declared at the beginning of the main() method. I now have to create a new method that uses some of the same objects/variables, so I decided to move all of my variables out of main() and make them static/global. In doing so, I've run into a problem: despite main() throwing FileNotFoundException, I was getting the following error message:
Tests.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
static Scanner boardReader = new Scanner(board);
Here was my code, up to the problematic line:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
class Tests {
// GAME OBJECTS AND VARIABLES
// The following is used for reading, displaying, and writing to the game board.
static File board = new File("Board.txt");
static Scanner boardReader = new Scanner(board);
static FileWriter boardWriter = null;
static StringBuilder boardBuilder = new StringBuilder((int)board.length());
static String boardDisplay = null; // This String allows boardContents to print in a more readable way.
static String boardContents = null; // This is Board.txt represented as a String.
// There are more variables here than shown, but these are the ones relevant to my problem.
// GAMEPLAY
public static void main(String[] args) throws FileNotFoundException, IOException {
boolean gameIsOngoing = true;
while(gameIsOngoing) {
// boardContents String from boardBuilder StringBuilder
while (boardReader.hasNextLine()) {
boardContents = (boardBuilder.append(boardReader.nextLine() + System.lineSeparator()).toString());
}
// More irrelevant code here.
}
}
}
In trying to fix the problem, I tried to put the code utilizing boardReader inside a proper try-catch as shown here:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
class Tests {
// GAME OBJECTS AND VARIABLES
// The following is used for reading, displaying, and writing to the game board.
static File board = new File("Board.txt");
static FileWriter boardWriter = null;
static StringBuilder boardBuilder = new StringBuilder((int)board.length());
static String boardDisplay = null; // This String allows boardContents to print in a more readable way.
static String boardContents = null; // This is Board.txt represented as a String.
// There are more variables here than shown, but these are the ones relevant to my problem.
// GAMEPLAY
public static void main(String[] args) throws IOException {
boolean gameIsOngoing = true;
while(gameIsOngoing) {
// boardContents String from boardBuilder StringBuilder
try (Scanner boardReader = new Scanner(board)) {
while (boardReader.hasNextLine()) {
boardContents = (boardBuilder.append(boardReader.nextLine() + System.lineSeparator()).toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// More irrelevant code here.
}
}
}
Which works, but it makes my code feel less readable, as the Scanner object is no longer listed with all of the other objects. I guess my question is, why didn't the first code work? Is it possible for something resembling it more to work?
I also want to mention quick that in researching for this question, I saw some things saying it is generally bad practice to have Scanner objects be global/static. I figured that because this particular Scanner isn't gathering user input (and me having no plans on maintaining this relatively simple project post-completion), it wouldn't be too problematic.
Edit: I don't know why but the editor isn't letting me put a "Hello" at the beginning of this post, so here it is... hello everyone :)
There is error because the exception is not caught. The Scanner instance is created in context of the Tests class, main method is something different, therefore catching it there won't solve the issue.
If you want a work-around, you can try something like this:
static {
try {
boardReader = new Scanner(board);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I created a Util class that returns an array that is based on a file. When I try to instantiate this array object in the Statistics class, I get this error:
error: unreported exception IOException; must be caught or declared to be thrown
I have both a throws IOException and try and catch. A similar stack overflow question was solved by placing the try and catch inside of the action method, but mine seems to have that already.
Any help would be much appreciated.
Util:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Util {
public static Student[] readFile(String fileName) throws IOException {
Student studentArray[]=new Student[15];
try{
FileReader file = new FileReader("studentData.txt");
BufferedReader buff = new BufferedReader(file);
String line;
line = buff.readLine();
int index=0;
while(line != null){
System.out.println(line);
if(index>14){
break;
}
line = buff.readLine();
String[] result = line.split("\\s");
int sid = Integer.parseInt(result[0]);
int scores[] = new int[5];
for(int x=1;x<result.length;x++){
scores[x-1] = Integer.parseInt(result[x]);
}
Student myCSC20Student = new Student(sid, scores);
studentArray[index++] = myCSC20Student;
}
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
return studentArray;
}
}
Statistics:
import java.io.*;
import java.util.*;
public class Statistics {
final int LABS = 5;
public int[] lowscores = new int[LABS];
private int[] highscores = new int[LABS];
private float[] avgscores = new float[LABS];
public static void main(String args[]) {
Student[] studArr = Util.readFile("studentData.txt") ;
System.out.println(studArr[1]);
}
void calculateLow(Student[] a){
}
void calculateHigh(Student[] a){
}
void calculateAvg(Student[] a){
}
}
You've marked readFile as throwing IOException, so anywhere you use that method, you need to wrap it in a try-catch block.
With your current code, I would suggest removing the throws portion of the method, because you're catching it anyway. What I suggest you do is remove the try-catch in the method and leave that to the callers. I recommend this because it makes it simpler to catch errors as opposed to the returned array just being empty.
readFile() declares IOException. This means that anywhere it's called, must also declare IOException, or catch it. In this case, readFile() does not need to declare IOException because it's caught within the method.
However, a larger issue is that you're calling an IO oriented method in class initialization. This makes it very difficult to deal with actual exceptions sanely. At the very least, your readFile() should return null or an empty array in the event of an exception.
In short, don't declare IOException on readFile().
You have already added try catch block in Util class so no need to throws the IOException. Remove throws clause from readFile method in Util class.
I'd like to populate an array list with lines from an input file, the input file looks like this:
7f00000000000000000000000000000000000000000000000000000000000000027f00000000000000000000000000000000000000000000000000000000000000027f00000000000000000000000000000000000000000000000000000000000000020101
7f00000000000000000000000000000000000000000000000000000000000000037f00000000000000000000000000000000000000000000000000000000000000037f00000000000000000000000000000000000000000000000000000000000000030101
7f00000000000000000000000000000000000000000000000000000000000000047f00000000000000000000000000000000000000000000000000000000000000047f00000000000000000000000000000000000000000000000000000000000000040101
7f00000000000000000000000000000000000000000000000000000000000000057f00000000000000000000000000000000000000000000000000000000000000057f00000000000000000000000000000000000000000000000000000000000000050101
7f00000000000000000000000000000000000000000000000000000000000000067f00000000000000000000000000000000000000000000000000000000000000067f00000000000000000000000000000000000000000000000000000000000000060101
The data object in Java that I'd like to create based on this would have each one of those lines as a new string, and they would live together in a list, so to speak*.
So, in my attempt to read in the lines of the file into different components of this array list, I can't figure out where I need to declare the array list in my main program. My plan is to populate it in a separate method:
import java.io.*;
import java.util.Scanner;
import java.util.List;
import java.util.Array;
import java.util.ArrayList;
class evmTest {
public static void main(String[] args) {
Array<String> inputLinesObject = new ArrayList<String>();
// populate from file
inputLinesObject = readFile("/Users/s.matthew.english/codes.txt", inputLinesObject);
System.out.println(Array.toString(inputLinesObject));
}
private static void readFile(String fileName, Array<String> inputLines) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
// System.out.println(scanner.nextLine());
inputLines.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return inputLines;
}
}
Maybe I can initially instantiate it as null, and then pass that null array list to the method to be populated?
* The terms in that last sentence are not totally precise- please forgive me- I'm re-adjusting to the vocabulary of Java, nevertheless I think it should be clear enough what I'm trying to do. If not please let me know and I'll be happy to clarify.
For your test, you simply have to instantiate the ArrayList just above the try
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EvmTest {
public static void main(final String[] args) {
// populate from file
final List<String> inputLinesObject = EvmTest.readFile("/Users/s.matthew.english/codes.txt");
for (final String line : inputLinesObject) {
System.out.println(line);
}
}
private static List<String> readFile(final String fileName) {
final List<String> inputLinesObject = new ArrayList<>();
try {
final File file = new File(fileName);
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
// System.out.println(scanner.nextLine());
inputLinesObject.add(scanner.nextLine());
}
scanner.close();
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
return inputLinesObject;
}
}
That has 2 advantages:
- You don't modify an input parameter of your readFile method
- You don't have to handle the case where the List is empty or null
You actually have three options:
Pass in a presumably empty list as a parameter into the method, and then add elements to the list:
static void readFile(String filename, List<String> inputLines) {
// For each line
inputLines.add(line);
}
You can then call is this way:
List<String> inputLines = new ArrayList<>();
readFile("someFilename", inputLines);
Let the readFile() method return a list:
static List<String> inputLines(String filename) {
List<String> lines = new ArrayList<>();
// For each line
lines.add(line);
// And then return the list with lines:
return lines;
}
And then call it this way:
List<String> lines = readFile("someFilename");
Don't reinvent the wheel and use functional programming to get the lines of the file:
List<String> lines = Files.lines(Paths.get("somefile"))
.collect(Collectors.toList());
The second one is way better than the first one, since it leaves the responsibility to create the list to the method itself. However, the latter is the best option.
A few more things:
Stick to the Java Naming Conventions: class names should start with uppercase.
You are using an Array<String>, but java.util.Arrray doesn't exist. I assume you mean List<String>.
Use this code for readFile() method:
private static List<String> readFile(String fileName, List<String> inputLines) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
// System.out.println(scanner.nextLine());
inputLines.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return inputLines;
}
and then call this readFile() method as below:
List<String> inputLinesObject = new ArrayList<String>();
inputLinesObject = readFile("/Users/s.matthew.english/codes.txt", inputLinesObject);
for(String str : inputLinesObject){
System.out.println(str);
}
Create a singleton class with a composition of ArrayList.
You can create a sinleton like this
import java.util.ArrayList;
import java.util.List;
public class FileLines {
private List<String> lines;
private FileLines() {
lines = new ArrayList();
}
private static class FileListHolder {
private final static FileLines instance = new FileLines();
}
public static FileLines getInstance() {
return FileListHolder.instance;
}
public void addLine(String line) {
lines.add(line);
}
public String getLine(int lineNumber) {
return lines.get(lineNumber);
}
}
and in your main program use it
FileLines fileLines = FileLines.getInstance();
fileLines.addLine(scanner.nextLine());
And in other part of your programm you can retrieve a line with
FileLines fileLines = FileLines.getInstance();
fileLines.getLine(12);
Here is a program similar to the sinking battleship game from the book head first java. After compiling I am getting the error: "String cannot be converted to ArrayList Error" and ^ pointer point to the line I have two different files one with the main method and other a separate class. Whats wrong here.
Main method class
import java.util.Scanner;
public class SimpleDotComTestDrive{
public static void main(String[] args){
SimpleDotCom dot=new SimpleDotCom();
boolean repeat=false;
String[] locations={"2","3","4"};
dot.setLocationCells(locations); //^ where compiler points the error
Scanner input=new Scanner(System.in);
System.out.println("Lets Start");
while(repeat==false) {
System.out.println("Type your guess");
String userGuess=input.nextLine();
String result=dot.checkYourSelf(userGuess);
System.out.println(result);
if(result=="kill") {
repeat=true;
break;
}
}
} //close main
} //close test class
Separately saved class which is part of this program:
import java.util.ArrayList;
public class SimpleDotCom {
private ArrayList<String>locationCells;
public void setLocationCells(ArrayList<String> locs) {
locationCells=locs;
}
public String checkYourSelf(String userGuess) {
String result="miss";
int index = locationCells.indexOf(userGuess);
if(index>=0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result="kill";
}
else {
result="hit";
}
}
return result;
} //close check yourself method
} //close simple class
You are getting the error because setLocationCells() method accepts an ArrayList<String> and you are passing it a String Array by doing:
dot.setLocationCells(locations);
You should either replace your method to accept String[] instead of ArrayList<String> or change your code as follows:
dot.setLocationCells(new ArrayList<String>(Arrays.asList(locations));
You cannot have String[] locations={"2","3","4"}; and then parse it to the method setLocationCells(ArrayList<String> locs){ that requires the ArrayList.
So, there are more ways:
Convert the array to list with: new ArrayList<String>(Arrays.asList(locations);
Define the ArrayList instead:
ArrayList<String> list = new ArrayList<String>() {{
add("2");
add("3");
add("4");
}};
Change your method at all:
public void setLocationCells(String[] locs){
Collections.addAll(locationcells, locs);
}
I am trying to return an arraylist from this method
import java.io.*;
import java.util.*;
/** The class reader read the file 2RainfallDataLanc.txt and stores is as an ArrayList.
* It also parses the variables within the file by white spaces, making variables accessible.
*
*/
public class reader {
public ArrayList<String[]> getRows(){
try {
BufferedReader reader = new BufferedReader(new FileReader("2RainfallDataLanc.txt"));
String line = null;
ArrayList<String[]> rows = new ArrayList<String[]>();
while((line=reader.readLine())!=null)
{String[] row = line.split("\\s+");
rows.add(row);
}
for (String[] row : rows) {
System.out.println(Arrays.toString(row));
return rows;
}
} catch (IOException e) {
}
return null;
}
}
As I wish to use it in another class. The second class currently looks like this :
public class mean extends reader{
public static void main(String[] args) {
reader newarray = new reader();
}
}
Could someone tell me what am I doing wrong? Whenever I try to return rows I get an error message saying that void methods cannot return a value.
You didn't create a method in your reader object with which to return something from. Create a method signature like the following:
public ArrayList<String[]> getRows() {
// Rest of your code here.
}