Currently doing a typestate project and I am having problems with importing the List class. When I try to compile the class it throws an error in command line saying cannot find symbol and points to the List symbol. I was wondering how you fix this. It seems to work for String and Integer but not for List.
The java file is automatically create via another program that translates .scr files. In the scr file I use the following line :
type <java> "java.lang.List" from "rt.jar" as List;
Java file:
package demos.Redis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.UnknownHostException;
public class ClientRole {
private BufferedReader socketServerIn = null;
private PrintWriter socketServerOut = null;
public ClientRole(){
ServerSocket serverServer = null;
try {
serverServer = new ServerSocket(20000);
}
catch(IOException e) {
System.out.println("Unable to listen on ports");
System.exit(+1);
}
Socket socketServer = null;
try {
System.out.println("Accepting...");
socketServer = serverServer.accept();
System.out.println("Server accepted");
}
catch(IOException e) {
System.out.println("Accept failed");
System.exit(+1);
}
try {
socketServerIn = new BufferedReader(new InputStreamReader(socketServer.getInputStream()));
socketServerOut = new PrintWriter(socketServer.getOutputStream(), true);
}
catch(IOException e) {
System.out.println("Read failed");
System.exit(+1);
}
}
public void send_WATCHListToServer(List payload) { HERE IS WHERE IT BREAKS!!
this.socketServerOut.println(payload);
}
public Choice1 send_Choice1LabelToServer(String payload) {
this.socketServerOut.println(payload);
int intLabelChoice1 = Integer.parseInt(payload);
switch(intLabelChoice1){
case 1:
return new Choice1(Choice1.GET);
case 2:
return new Choice1(Choice1.WATCH);
case 3:
default:
return new Choice1(Choice1.MULTI);
}
}
public void send_GETStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public String receive_GET_respStringFromServer() {
String line = "";
try {
line = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public void send_MULTIStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public Choice2 send_Choice2LabelToServer(String payload) {
this.socketServerOut.println(payload);
int intLabelChoice2 = Integer.parseInt(payload);
switch(intLabelChoice2){
case 1:
return new Choice2(Choice2.SET);
case 2:
return new Choice2(Choice2.DISCARD);
case 3:
default:
return new Choice2(Choice2.EXEC);
}
}
public void send_SETStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public void send_DISCARDStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public void send_EXECStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public Choice3 receive_Choice3LabelFromServer() {
String stringLabelChoice3 = "";
try {
stringLabelChoice3 = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error, unable to get label");
System.exit(+1);
}
int intLabelChoice3 = Integer.parseInt(stringLabelChoice3);
switch(intLabelChoice3){
case 1:
return new Choice3(Choice3.EXEC_OK);
case 2:
default:
return new Choice3(Choice3.EXEC_FAIL);
}
}
public String receive_EXEC_okStringFromServer() {
String line = "";
try {
line = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public String receive_EXEC_failStringFromServer() {
String line = "";
try {
line = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
}
Command Line
Your Java file is missing an import statement for java.util.List, which is why it's failing to compile.
Unlike String and Integer, List is not in the java.lang package. You need to import java.util.List, not java.lang.List.
If I'm understanding your scenario correctly, your other program is generating the import statements and attempting to add an import for java.lang.List, which doesn't actually exist. Interestingly, there's no import statement in your code for java.lang.List. I don't know if that's a bug in your other program or a feature! But more than likely your problem will go away if you replace your line in the .scr file with type <java> "java.util.List" from "rt.jar" as List;
You are using the interface List but you didn't import it, it says that It can not find symbol java.lang.List because it is trying to search this class in the default java.lang package, add the import java.util.List and you are not going to have problems
Related
Why would this code be having memory issues? It runs fine once, and then when I try to run it again it hangs on "Enabling plugin". It'll then give me an OutOfMemoryException such as
"Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Worker-Main-10""
The code I am using is as follows from the Spigot API
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;
public class COVID19 extends JavaPlugin {
private static ArrayList<CovidInfection> infections;
#Override
public void onEnable() {
infections = new ArrayList<CovidInfection>();
System.out.println("1");
try {
readInfections();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
System.out.println("2");
this.getCommand("getInfected").setExecutor(new CommandGetInfected());
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
batCovid();
}
}, 0, 10);
System.out.println(4);
}
#Override
public void onDisable() {
try {
writeInfections();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void batCovid() {
System.out.println(3);
for(Player player : Bukkit.getOnlinePlayers()) {
for(Entity nearby : player.getNearbyEntities(6, 6, 6)) {
if (nearby instanceof Bat) {
String name = player.getName();
UUID uuid = player.getUniqueId();
infections.add(new CovidInfection(uuid, name, 14));
}
}
}
}
public void readInfections() throws FileNotFoundException {
File file = new File("infected.txt");
if(file.length() == 0) {
return;
}
Scanner input = new Scanner(file);
String line = input.nextLine();
while (!(line.equals(""))) {
infections.add(parseInfectionLine(line));
}
input.close();
}
public void writeInfections() throws IOException {
//File will be written as UUID,Name,DaysRemaining
FileWriter writer = new FileWriter("infected.txt", false);
for(CovidInfection infection : infections) {
writer.write(infection.toString());
}
writer.close();
}
private CovidInfection parseInfectionLine(String line) {
String[] words = line.replace("\n","").split(",");
return new CovidInfection(UUID.fromString(words[0]), words[1], Integer.parseInt(words[2]));
}
public static String getInfected() {
String compiled = "";
for (CovidInfection infection : infections) {
compiled += infection.toString() + "\n";
}
return compiled;
}
}
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGetInfected implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
String message = COVID19.getInfected();
if(!(message.equals(""))) {
sender.sendMessage(message);
} else {
sender.sendMessage("There are no infected!");
}
return(true);
}
}
import java.util.UUID;
public class CovidInfection {
private UUID uuid;
private String name;
private int days;
public CovidInfection(UUID uuid, String name, int days) {
this.uuid = uuid;
this.name = name;
this.days = days;
}
public int getDays() {
return days;
}
public String getName() {
return name;
}
public UUID getUuid() {
return uuid;
}
public void newDay() {
days--;
}
public String toString() {
return uuid.toString() + "," + name + "," + days + "\n";
}
}
Any help would be greatly appreciated, thank you!
Firstly, you are make I/O request on main thread.
To fix this issue, use multithreading such as explained here or here
Then, this :
Scanner input = new Scanner(file);
String line = input.nextLine();
Can't be used in a server.
An input like that already exist, it's the console sender.
To do that, I suggest you to use ServerCommandEvent and use spigot's console.
Suppose that file.txt only contains "Hello". When I compile the Java code, it shows
Error: This method must return a result of type java.lang.String in line5.
When I print in readTxt function, that works, it can show "Hello".
I already check the result is correctly String type, but it also shows compiler error. How can I make the return value to the main function?
import java.io.*;
import java.lang.String;
public class ReadTxtFile {
public static String readTxt(String filePath) {
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
lineTxt = br.readLine();
//System.out.println(lineTxt);
br.close();
return lineTxt;
} else {
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
String filePath = "C:/file.txt";
String fileword = readTxt(filePath);
System.out.println(fileword);
}
}
You promised to return a String from your method, so you now have to do that. The only way around that promise is to throw an exception.
public static String readTxt(String filePath) { // Here you promise to return a String
try {
...
if(file.isFile() && file.exists()) {
...
return lineTxt; // Here you return a String as promised
} else {
// Here you're missing either return or throw
}
} catch (Exception e) {
// Here you're missing either return or throw
}
}
This is fundamentally a design problem - what should your method do if it fails to read the file for some reason? Return a special string like "Error"? Return null? Fail and throw and exception? Something else?
Answer that to yourself and it will be clear to you how to fix the code.
There are several best practices you should follow that will prevent future error. I have tried to cover them. Not saying mine is the perfect one, but you will get the idea.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StackOverFlow {
public static void main(String[] args) {
try {
String sText = getFileText("C:/file.txt");
System.out.println("Text is: " + sText);
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} catch (IOException e) {
System.out.println("#Error while reading text: " + e.getMessage());
}
}
private static String getFileText(String filePath) throws FileNotFoundException, IOException {
File file = new File(filePath);
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
}finally {
reader.close();
}
return new String(stringBuilder);
}
}
I have some problem with saving object to a file. I have class FileManager which contains method that saves object to file. This method is used in class Control which contains main loop (choosing different options). I would like to save object with choosing option EXIt but nothing happens. When I add new option (i.e. 6 - Save database) program works fine. I will be grateful for any clues what can be wrong.
class FileManager {
package utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import data.DataBase;
public class FileManager {
public static final String FILE_NAME = "file.txt";
public void writeDataBaseToFile(DataBase db) {
try (
FileOutputStream fos = new FileOutputStream(FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(fos);
) {
oos.writeObject(db);
} catch (FileNotFoundException e) {
System.err.println("Błąd");
} catch (IOException e) {
System.err.println("Błąd");
}
}
}
Control Class :
class Control {
package app;
import data.DataBase;
import data.Expense;
import data.Income;
import utils.AccountInfo;
import utils.AddData;
import utils.FileManager;
import utils.Info;
import utils.Options;
public class Control {
private AccountInfo account;
private AddData addData;
private DataBase dataBase;
private Info inf;
private Income income;
private FileManager fileManager;
public Control() {
addData = new AddData();
dataBase = new DataBase();
inf = new Info(dataBase);
account = new AccountInfo(dataBase);
fileManager = new FileManager();
}
public void ControlLoop() {
Options option;
printOptions();
while((option = Options.createOption(addData.getOption())) != Options.EXIT) {
try {
switch(option) {
case ADD_INCOME:
addIncome();
break;
case ADD_EXPENSE:
addExpense();
break;
case PRINT_INCOME:
printIncome();
break;
case PRINT_EXPENSE:
printExpense();
break;
case RESUME_ACCOUNT:
resumeAccount();
break;
case EXIT:
saveData();
}
} catch(NullPointerException ex) {
}
printOptions();
}
addData.close();
}
public void addIncome() {
income = addData.createIncome();
dataBase.addBudget(income);
}
public void addExpense() {
Expense expense = addData.createExpense();
dataBase.addBudget(expense);
}
public void printIncome() {
inf.printIncome();
}
public void printExpense() {
inf.printExpense();
}
public void resumeAccount() {
account.resumeIncome();
account.resumeExpense();
}
public void saveData() {
fileManager.writeDataBaseToFile(dataBase);
}
public void printOptions() {
System.out.println("Wybierz opcję:");
for(int i=0; i<6; i++) {
System.out.println(Options.values()[i]);
}
}
}
Your code can never reach the EXIT case.
Because when option is EXIT, it terminates the loop.
while ((option=...) != Options.EXIT) {
// execute loop body when option is not EXIT
switch (option) {
...
case Options.EXIT: // <-- it can simply not reach here. not ever.
saveData();
}
Try move saveData() outside the while loop.
while (...) { // process options
}
// We are exiting, save data.
saveData();
addData.close();
P.S. You need to close the output stream in your FileManager.
I have 2 class files in my simple project - sorry another newbee here!
But I get a compilation error on the last part where I am trying to print the hopefully stored configuration settings from a file for my project that will be referred to throughout the project.
The file is just rows of values like this 'ButtonConfig,8,V,NULL,bunny,mpg'
I basically want to be able to used the contents of this arraylist to dynamicly set up the configuration of a Raspberry pi GPO pins i.e. for the above values button attached to GPO pin 8 will play video (V) "<..other value...>_bunny.mpg"
Any help greatly appreciated - just telling me why I can't access the getExtension method would be nice!
Contents of first java file is -
package bpunit;
public class ButtonConfig {
private String keyword;
private String gponumber;
private String buttontype;
private String language;
private String filename;
private String extension;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
...............
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
The second contains this -
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List buttonList = new ArrayList();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
You have to add the parameterized type ButtonConfig to your ArrayList. It ends up being List<ButtonConfig> instead of just List.
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
The reason why the compilation is failing is because when you add an object to the ArrayList it is upcast as an object of the class Object. Now when you extract it you simply have to typecast it back to the original type. so all you have to do is this :
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
ButtonConfig buttonObject =(ButtonConfig)buttonListToPrint.get(i);
System.out.println(buttonObject.getExtension());
}
}
Or as mentioned in the comments and answers above you could use generics and create an List of type ButtonConfig
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
and pass it in the function printButtonList
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
I wanted to create a web page in Struts2.0 which contains a textarea, a property field and submit button. User will enter a java code in this text area and my code will compile it and execute it and will give the result of this code on my property field... the above code works fine in a standalone application. but it does not shows any thing in my web application. plz any one can address it... thanks in advance.
package org.controller;
import com.opensymphony.xwork2.ActionSupport;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
public class JCompilerAction extends ActionSupport
{
String program;
String MSg;
public JCompilerAction() {
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public String getMSg() {
return MSg;
}
public void setMSg(String MSg) {
this.MSg = MSg;
}
public String Compile() {
try {
byte[] bFile = program.getBytes();
File f = new File("D:/nullprog.java");
FileOutputStream fileOuputStream = new FileOutputStream(f);
fileOuputStream.write(bFile);
fileOuputStream.close();
Process p1 = Runtime.getRuntime().exec("javac D:/nullprog.java");
BufferedReader in = new BufferedReader(new InputStreamReader(p1.getErrorStream()));
String line = null;
boolean isError = false;
while ((line = in.readLine()) != null) {
MSg = line;
isError = true;
return SUCCESS;
}
p1.waitFor();
if (!isError)
{
Process p2 = Runtime.getRuntime().exec("cmd /c start nullprog");
BufferedReader in1 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line1 = null;
while ((line1 = in1.readLine()) != null) {
MSg += line1;
}
return SUCCESS;
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public String execute() {
return SUCCESS;
}
}
Below is a simple program that first compiles a code and then executes it:
Executer.java
import java.lang.reflect.Method;
public class Executer {
public static void main(String args[]) {
try{
java.lang.Process p1 = Runtime.getRuntime().exec("javac MyClass.java");
p1.waitFor();
Class<?> c = Class.forName("MyClass");
Object obj = c.newInstance();
Method[] mArr = obj.getClass().getMethods();
for(Method m : mArr){
if(m.getName().equalsIgnoreCase("main")){
m.invoke(obj, new Object[]{new String[]{}});
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
MyClass.java
import javax.swing.JOptionPane;
public class MyClass {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hii");
}
}
For simplicity both the classes are in same package. When I execute Executer class, it first compiles MyClass.java and then runs the main method.
If your requirement is to have the Java files in some folder outside of the project, the to load the compiler class file, you need to follow as mentioned in this answer.