<identifier> expected, arrayList - java

I'm having trouble with some java code. The program consists of about 7 files, but I will try to keep it short.
I'm trying to load an ArrayList from a file into a variable, with ObjectStream. It gave me a warning, because all the compiler could see, was that I said an Object should be casted to ArrayList. of course the compiler won't know what kind of object there is in the file. As the coder I know that the file can only consist of one ArrayList and nothing else. So I searched the web, and found out to supress the warning, nut now it give me the error:
Schedule.java:34: error: <identifier> expected
To give you a picture of what's happening, here is the code the error happens in. This error shouldn't be affected by any of the other classes
import java.util.*;
import java.io.*;
public class Schedule
{
private static ArrayList<Appointment> schedule;
private static File file;
private static ObjectInputStream objIn;
private static boolean exit;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
initializeSchedule();
System.out.println("Welcome!");
while(!exit){
System.out.print("write command: ");
Menu.next(in.next());
}
}
public static void initializeSchedule()
{
try{
file = new File("Schedule.ca");
if(!file.exists()){
schedule = new ArrayList<Appointment>();
}
else{
objIn = new ObjectInputStream(new FileInputStream("Schedule.ca"));
#SuppressWarnings("unchecked")
schedule = (ArrayList<Appointment>)objIn.readObject();
objIn.close();
}
} catch (IOException e){
System.out.println("Exception thrown :" + e);
} catch (ClassNotFoundException e){
System.out.println("Exception thrown :" + e);
}
}
public static void exit()
{
exit = true;
}
public static ArrayList<Appointment> getSchedule()
{
return schedule;
}
}
the error is in initializeSchedule, right under the supression, where schedule is set to the ObjectStream input.

The correct locations for #SuppressWarnings("unchecked") are
TYPE, FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE
So the compiler cannot parse #SuppressWarnings at this point, but considers it a statement. If you move it above the method declaration or above the declaration of schedule, it should be fine.
A better way to fix that is to actually correct the issue that the compiler is complaining about like this:
final Object input = objIn.readObject();
if (input instanceof ArrayList) {
schedule = (ArrayList<Appointment>) input;
} else {
throw new IllegalStateException(); // or whatever suits you
}

You can't annotate an assignment. Move the
#SuppressWarnings("unchecked")
to the line before the method starts.

Related

Java ArrayList get() method doesn't return Point object?

so i created an ArrayList of Point objects but when i'm using the get() method of the ArrayList it seems that it does not return Point object.. why is this happening?
public class SkylineDC {
public static void openAndReadFile(String path,ArrayList pointsList){
//opening of the file
Scanner inputFile=null;
try{
inputFile=new Scanner(new File(path));
}
catch (Exception e1){
try{
inputFile=new Scanner(new File(path+".txt"));
}
catch (Exception e2){
System.out.println("File not found..");
System.exit(1);
}
}
//reading of the file
short listSize=inputFile.nextShort();
pointsList=new ArrayList<Point>(listSize);
//pointsList.add(new Point(10,10));
//System.out.println("Size of List:"+pointsList.size());
pointsList.get(0).
}
public static void main(String[] args) {
String path=args[0];
ArrayList totalPoints=null;
openAndReadFile(path,totalPoints);
//System.out.println("finish");
}
}
ArrayList pointsList
you're using a raw type in the declaration.
Change it to ArrayList<Point> pointsList
Also:
ArrayList totalPoints=null should not be the raw type either. Change to ArrayList<Point> totalPoints = new ArrayList<>()
I would furthermore suggest simply having your method return a List<Point> rather than trying to populate an existing list. I don't even know if the code you currently have will run as expected. My suspicion is that it will not.

Compiling error when reading a file in Java

I am trying to run this simple program that reads from a separate text file and prints out each line. However, when I try to compile it, it keeps giving me the same error:
story.java:11: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
x = new Scanner(new File("names.txt"));
Here is my code:
import java.io.*;
import java.util.*;
public class story {
private static Scanner x;
public static void main(String[] args) {
String story = "";
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
}
This message is telling you that your main() method is doing some stuff that may throw FileNotFoundException but you are neither catching this exception, nor declaring that such an exception may be thrown by the main() function.
To correct it, declare your main() method as follows:
public static void main(String[] args) throws FileNotFoundException {
Change it to
public static void main(String[] args) throws Exception {
String story = "";
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
OR
Put try catch in your code
public static void main(String[] args) {
String story = "";
try {
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
catch(Exception e) {
// handle
}
}
When programming there is the normal flow of logic that solves your problem, and a second flow of logic that handled "Exceptional" unexpected situations. Java uses the type Exception and the keyword throw to have bits of code present exceptional error states.
Your program, when being complied, is being checked for its ability to handle exceptional return values. Since you didn't handle the exceptional return value, it is not going to be compiled.
Below is your code, handling this Exception. Pay close attention to the try and catch block structure, as it is how one writes code that can handle an Exception being raised. However, don't be constrained by how I handled the exception for you, because the details of how to handle the exception are dependent on what you would prefer to do.
import java.io.*;
import java.util.*;
public class story {
private static Scanner x;
public static void main(String[] args) {
String story = "";
try {
x = new Scanner(new File("names.txt"));
} catch (FileNotFoundException error) {
System.out.println("the program failed because \"names.txt\" was not found.");
return -1;
}
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
}
There is another approach to handling exceptions that sometimes is appropriate, which is to "not handle" the exception. When doing so, change the method from whatever the method was to whatever the method was throws Exception. For example public static void main(String[] args) to public static void main (String[] args) throws Exception.
While this handles the compiler's complaint it should be used sparingly because exceptions that bubble up through the nested method calls past the main method will crash the program, typically without easily readable output that might make the error easier for a human to fix.
Whenever working with a file object, you must handle the chance of a FileNotFoundException, which occurs when the file you specify does not exist.
to fix this, simply say throws Exception in you main header, or use a try/catch block.
public static void main(String[] args) throws Exception {
or
public static void main(String[] args) {
String story = "";
try
{
x = new Scanner(new File("names.txt"));
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
catch(Exception e)
{
System.out.println("Error: File not found!");
}
}
1) You need to put them in the try catch block.
2) specify the path of "names.txt".
3) My code looks like:
String story = "";
try {
x = new Scanner(new File("/Users/Workspace/names.txt"));
while(x.hasNext()){
System.out.println(story = story+x.next());
}
System.out.println(story);
} catch (FileNotFoundException e){
e.printStackTrace();
}
}

Using variables from another method - problems understanding the object orientation

the following code is incomplete but the main focus of my question is on the method processConfig() anyway. It reads the properties out of a file and I want to handover these properties to the method replaceID(). It worked already when the content of processConfig was in the main()-method. But now I wanted to put this code into it´s own method. What is the best way of handing over the properties (which I saved in Strings like difFilePath). I´m not that familiar with OO-programming and want to understand the concept. Thanks for your help.
public class IDUpdater {
....
public static void main(String[] args) throws Exception {
//Here I want to call the variables from processConfig() to make them available for replaceID(...)
replaceID(difFilePath, outputDifPath, encoding);
}
public static void replaceID(String difFilePath, String outputDifPath, String encoding) throws Exception{
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
String difFilePath = prop.getProperty("dif_file_path");
String outputDifPath = prop.getProperty("output_dif_path");
String encoding = prop.getProperty("encoding");
}
}
You've to declare your variables globally. This way they can be accessed in each method. After you've declared them globally you first call your processConfig in your main method, which will set your variables to what they should be.
public class IDUpdater {
private String difFilePath;
private String outputDifPath;
private String encoding;
public void main(String[] args) throws Exception {
processConfig();
replaceID();
}
public void replaceID() throws Exception{
// You can use your variables here.
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
difFilePath = prop.getProperty("dif_file_path");
outputDifPath = prop.getProperty("output_dif_path");
encoding = prop.getProperty("encoding");
}
}
Note that I declared the variables privately. For more information about protecting your variables see https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx.
You may want to read an article (or even better yet - a book) on topic of encapsulation and objects. This or this may be a good starting point for you. There is no point in anyone fixing your code, if you don't understand the concepts behind it.

Java - Existence of method causing program to not work correctly

In my Java program, I have a class called Car, which is Serializable. I have another class called StaffCar which is a subclass of Car.
Then there a class called Fleet which essentially stores StaffCar objects in ArrayList<StaffCar> fleet.
I then have a class Main which consists of the main method which consists of a menu and a switch to handle menu options.
The problem I'm having is when I add a method in StaffCar, even if the method has nothing inside and the method isn't even called, one of the menu options which is 'Display all car information', stops working.
If I comment out this method, it starts working again.
The 'Display...' option calls printCars()from Fleet which has fleet loaded with StaffCar objects from the serialized file, it's like the existence of this method stops the file from even being read.
Snippet of Car
import java.util.ArrayList;
import java.io.*;
#SuppressWarnings("serial")
public class Car implements Serializable
{
//attributes for Car
String regNo;
String model;
int mileage;
//default constructor
public Car() throws CarException
{
try
{
setRegNo("??????");
setModel("Unknown");
setMileage(0);
}
catch (CarException c)
{
System.out.println(c.getMessage());
}
}
//setters
public void setRegNo(String regNo) throws CarException
{
if (regNo.isEmpty())
{
throw new CarException("\nInvalid registration number!\n");
}
this.regNo = regNo;
}
public void setModel(String model) throws CarException
{
if (model.isEmpty())
{
throw new CarException("\nModel can't be empty!\n");
}
this.model = model;
}
public void setMileage(int mileage) throws CarException
{
if (mileage < 0)
{
throw new CarException("\nInvalid mileage!");
}
this.mileage = mileage;
}
}
Snippet of StaffCar, where the problem is being caused
import java.util.ArrayList;
#SuppressWarnings("serial")
public class StaffCar extends Car
{
String staffName;
String availability;
public StaffCar() throws CarException
{
super();
try
{
setAvailability("Available");
setStaffName("");
}
catch (CarException c)
{
System.out.println(c.getMessage());
}
}
public void setStaffName(String staffName)
{
this.staffName = staffName;
}
public void setAvailability(String availability) throws CarException
{
if (availability != "Available" && availability != "Borrowed")
{
throw new CarException("\nInvalid borrow status!\n");
}
this.availability = availability;
}
//this method causing issues, even if empty
/*public void returnCar()
{
}*/
}
Snippet of Fleet class
import java.util.ArrayList;
import java.io.*;
public class Fleet
{
//declare container
ArrayList<StaffCar> fleet;
//container to hold regNos
ArrayList<String> regNumbers;
//create constructor
public Fleet()
{
fleet = new ArrayList<StaffCar>();
regNumbers = new ArrayList<String>();
}
//add method
public void addCar(StaffCar car)
{
fleet.add(car);
regNumbers.add(car.regNo);
}
//print all cars' details
public void printCars()
{
for (StaffCar car:fleet)
{
System.out.println(car);
}
}
public void saveAs(String fileName) throws CarException
{
FileOutputStream outputFile;
try
{
outputFile = new FileOutputStream(fileName);
}
catch (IOException io)
{
throw new CarException("\nCannot create " + fileName + "\n");
}
ObjectOutputStream fleetFile;
try
{
fleetFile = new ObjectOutputStream(outputFile);
fleetFile.writeObject(regNumbers);
fleetFile.writeObject(fleet);
fleetFile.close();
}
catch (FileNotFoundException e)
{
throw new CarException("\nCannot create " + fileName + "\n");
}
catch (IOException io)
{
throw new CarException("\nCannot write " + fileName + "\n");
}
}
#SuppressWarnings({ "unchecked", "resource" })
public void open(String fileName) throws CarException
{
FileInputStream inputFile;
try
{
inputFile = new FileInputStream(fileName);
}
catch (FileNotFoundException e)
{
throw new CarException("\nCannot open " + fileName + "\n");
}
ObjectInputStream fleetFile;
try
{
fleetFile = new ObjectInputStream(inputFile);
regNumbers = (ArrayList<String>)fleetFile.readObject();
fleet = (ArrayList<StaffCar>)fleetFile.readObject();
}
catch (IOException io)
{
throw new CarException("\nError reading from " + fileName + "\n");
}
catch (ClassNotFoundException e)
{
throw new CarException("\nError reading from " + fileName + "\n");
}
try
{
fleetFile.close();
}
catch (IOException io)
{
throw new CarException("\nCannot close " + fileName + "\n");
}
}
}
I apologise for what seems like me dumping a bunch of code to you, I know this is bad practice and I have tried to condense the code as much as I can, but I feel like this is all the relevant code to my problem.
Like I said, I don't understand why the simple addition of an empty method is causing this issue.
EDIT
Main class
public class Main
{
// new container
static Fleet fleet = new Fleet();
// initialise car object
static StaffCar car;
// programme loop variable
static boolean state = false;
String fileName;
public static void main(String[] args) throws CarException
{
start();
// programme loop
while (!state)
{
try
{
// menu option variable
String option;
//displays menu to user and takes in input
option = Console.askString("Menu:\n1 Add a car\n2 Display all car information\n3 Find a car\n4 Borrow a car\n5 Return a car\n6 Exit\n\n");
//removes white spaces
option = option.trim();
//switch to handle user request
switch (option)
{
//if option 1
case "1":
//call static add car method
addMethod();
break;
//if option 2
case "2":
//call static print car method
displayMethod();
break;
//..option 3
case "3":
//call static find car method
findMethod();
break;
//..option 4
case "4":
borrowMethod();
break;
case "5":
//returnMethod();
break;
case "6":
//call static quit method
quitMethod();
break;
default:
System.out.println();
System.out.println("Invalid option.");
System.out.println();
break;
}
}
catch (CarException c)
{
System.out.println(c.getMessage());
}
}
}
public static void start()
{
try
{
fleet.open("fleet.uwl");
}
catch (CarException e)
{
//System.out.println("\nFile not created yet!\n");
}
}
//static menu method to print cars
public static void displayMethod() throws CarException
{
System.out.println();
//call printCars method
fleet.printCars();
System.out.println();
}
}
You saved instances of StaffCar using serialization, then changed the StaffCar class, and are unable to read the saved StaffCar again.
That's because, if you don't specify a serialVersionUID in your class, the JVM computes one for you, based on the layout of the class (fields, methods, etc.). So, to temporarily fix your problem, examine the IOException thrown when reading the file, which should tell you what the serialVersionUID of the saved classes are, and add the following to your class:
private static final long serialVersionUID = XXXL;
where XXX is the serial version UID in the saved objects, which should be mentioned in the exception stack trace.
But really, you have these problems because you chose to use serialization for long term storage, which makes your code very hard to evolve. I wouldn't do that. Instead, I would choose a less fragile and easier to evolve format such as JSON or XML. Define what the file should contain, and generate a JSON/XML document containing this data. Then, whatever your future casses look like, as long as you still can parse JSON/XML, you'll be able to read the files and get the saved data.

creating, writing to and reading from files java

I have made a program that is supposed to create a file, write to it, and then read from it. The problem comes with readFile(), where suddenly hasNext() is undefined for Formatter? I thought that
while (file.hasNext()) {
String a = file.next();
System.out.println(a);
would go as long as there was something in the file, copy it to a and then print a? What am I doing wrong?
import java.util.*;
import java.io.*;
class Oppgave3
{
public static void main(String[] args)
{
Kryptosystem a = new Kryptosystem();
a.createFile();
a.writeFile();
a.openFile();
a.readFile();
a.closeFile();
}
}
class Kryptosystem
{
public Kryptosystem(){}
Scanner keyboard = new Scanner (System.in);
private Formatter file;
private Scanner x;
public void createFile(){
try {
file = new Formatter("kryptFil.txt");
}
catch (Exception e) {
System.out.println("could not create file");
}
}
public void writeFile(){
System.out.println("what do you want to write");
String tekst = keyboard.nextLine();
file.format(tekst);
}
public void openFile() {
try {
x = new Scanner (new File("kryptFil.txt"));
}
catch (Exception e) {
System.out.println("something is wrong with the file");
}
}
public void readFile() {
while (file.hasNext()) {
String a = x.next();
System.out.println(a);
}
}
public void closeFile() {
file.close();
}
}
You state:
where suddenly hasNext() is undefined for Formatter?
Please have a look at the Formatter API as it will show you that this class has no hasNext() method, and your Java compiler is correctly telling you the same thing. Similarly, the Scanner API will show you that it in fact has the method you need.
You're opening the same File in a Scanner, called x, and this is what you want to use to read from the file. So the solution is to call hasNext() on the Scanner variable:
while (x.hasNext()) { // x, not file
String a = x.next();
System.out.println(a);
}
Note I'm not sure why you opened the file a second time and placed it into a Formatter object. Please clarify your motivation for this. I believe that you wish to write to the file with this, but you certainly would not try to use it to read from the File, which is what you're use of hasNext() is trying to do. I think you were just a little confused on which tool to use is all.

Categories

Resources