Display loaded content into TextArea - java

I want to display information that I have loaded in from 2 methods onto my TextArea. The methods I am trying to call and display are named loadFleet and loadCrew which are in the Fleet class. I only have it working to where it prints out to the console like so System.out.println(Enterprise). I am pretty new to Java and JavaFX, so any help would be greatly appreciated.
Here's my MainController file:
package application.controller;
import java.io.IOException;
import application.model.Fleet;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class MainController implements EventHandler<ActionEvent>{
#FXML TextField starshipname;
#FXML TextArea shipInfo;
#FXML Button shipEnter;
#Override
public void handle( ActionEvent event) {
/*try {
Fleet.loadFleet(null);
} catch (IOException e) {
shipInfo.setText(" Starship name not found! ");
e.printStackTrace();
}*/
Fleet Enterprise = new Fleet( "Bozeman" );
try {
Enterprise.loadFleet("data/fleet");
Enterprise.loadCrew("data/personnel");
System.out.println(Enterprise);
}catch( IOException e ) {
System.out.println( "Error loading the file - please check its location." );
e.printStackTrace();
}
}
}
And here's my Fleet class:
package application.model;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Fleet {
private String fleetName;
public ArrayList<Starship> ship;
private String fileName;
public Fleet( String name ) {
this.fleetName = name;
this.ship = new ArrayList<Starship>();
}
public String getFleetName() {
return this.fleetName;
}
public void setFleetName( String name ) {
this.fleetName = name;
}
public ArrayList<Starship> getStarship() {
return this.ship;
}
public void setStarship( ArrayList<Starship> ship ) {
this.ship = ship;
}
public String getFileName() {
return this.fileName;
}
public void setFileName( String fName ) {
this.fileName = fName;
}
public void addShip(Starship starAdd) {
this.ship.add(starAdd);
}
public void getStarshipsByName( Starship starName ) {
Starship starname;
}
public void loadFleet(String fileName)throws IOException {
try {
Scanner scan = new Scanner(new File("data/fleet.csv") );
while( scan.hasNextLine() ) {
String line = scan.nextLine();
String[] items = line.split(",");
Starship tmp = null;
tmp = new Starship( items[0], items[1], items[2]);
this.addShip(tmp);
}
scan.close();
}catch(IOException e) {
e.printStackTrace();
}
}
public void loadCrew(String fileName)throws IOException {
try {
Scanner scan = new Scanner(new File("data/personnel.csv") );
while( scan.hasNextLine() ) {
String line = scan.nextLine();
String[] items = line.split(",");
Crewmember tmp = null;
tmp = new Crewmember( items[0], items[1], items[2], items[3], items[4]);
for(int i = 0; i < this.ship.size(); ++i) {
if(this.ship.get(i).getStarShipRegistry().equals(items[3]))
this.ship.get(i).addCrew( tmp );
}
}
scan.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public String toString() {
String ret = " ";
for( int i = 0; i < this.ship.size(); i++)
{
ret += this.ship.get(i).toString();
}
return ret;
}
}
Please let me know what other classes or methods you would like for me to provide.

add data to shipInfo (your TextArea) by appending from foreach
loop of your list.
Quick sample code:
//instance of your ship object
StarShip myShip = StarShip();
//method to add data to your TextArea
private void showShipInfo(){
//getStarShip returns the list of ships
//same as the method on your Fleet class
myShip.getStarShip().forEach(starShip ->{
//add data to TextArea for each field of
//StarShip object you want to display
shipInfo.append(starShip.getName());
//shipInfo.append(starShip.get....());
//shipInfo.append(starShip.get....());
}
}
Note: only String values are allowed to be appended to TextArea!
Hope it helps!

Related

Minecraft plugin hanging on "Enabling plugin" and producing out of memory errors

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.

I am trying to write a method that will DETECT recursion in a file but am having trouble iterating through the methods of that file

This is what my recursion detector looks like (with an error of "The method contains(String) is undefined for Method Declaration" in if (md.contains(methodName))). I am not sure how I should change this to make it work. I hope to have some advice on what I could do to iterate through each individual method and check for its methodName in it. Thank you!
RecursionDetector.java
package detectors;
import java.awt.*;
import java.util.*;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class RecursionDetector extends VoidVisitorAdapter <Breakpoints> {
#Override
public void visit(MethodDeclaration md, Breakpoints collector) {
String className = getClass().getName();
String methodName = md.getName().asString();
int startline = md.getRange().get().begin.line;
int endline = md.getRange().get().end.line;
final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (md.contains(methodName)) {
}
for (int i=0; i < trace.length-1; i++) {
if( trace[i].equals(trace[trace.length-1]) ) {
super.visit(md, collector);
collector.addEmpty(className, methodName, startline, endline);
}
}
}
}
I also have a Breakpoints.java that looks like this:
package detectors;
import java.util.ArrayList;
public class Breakpoints {
private ArrayList<String> collector = new ArrayList<String>();
public Breakpoints() { }
public void addClass(String currentClass) { }
public void addMethod(String currentMethod) { }
public ArrayList<String> returnCollector() {
return new ArrayList<String>(this.collector);
}
public void addEmpty(String currentClass, String currentMethod, int startLine, int endLine) {
String n = ("className: " + currentClass + ", methodName: " + currentMethod + ", startline : " + startLine
+ ", endline : " + endLine + "\n");
if (collector.contains(n)) {
return;
}
collector.add(n);
}
}
And a Driver.java that looks like this:
package detectors;
import java.io.*;
import java.util.Scanner;
import com.github.javaparser.*;
import com.github.javaparser.ast.CompilationUnit;
public class Driver {
public static String data;
public static String data2 = "";
public static void main(String[] args) {
try {
File myFile = new File("/Users/weihanng/Desktop/Calculator.java");
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
data2 = data2.concat(data);
}
myReader.close();
CompilationUnit cu = JavaParser.parse(myFile);
Breakpoints collector = new Breakpoints();
cu.accept(new RecursionDetector(), collector);
System.out.println("Recursions: ");
System.out.println(collector.returnCollector());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

I'm trying to read a text file and store it in an arraylist of objects

I'm trying to read a text file and store it in an arraylist of objects, but I keep getting an error saying I cannot convert a String to an Item, which is type of arraylist I am using. I have tried various solutions, but am not quite sure how its is suppossed to be done. I am new to coding and have this assignment due soon. Anything helps!
private void loadFile(String FileName)
{
Scanner in;
Item line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine();
MyStore.add(line);
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
my apologies for not adding the Item class
public class Item
{
private int myId;
private int myInv;
//default constructor
public Item()
{
myId = 0;
myInv = 0;
}
//"normal" constructor
public Item(int id, int inv)
{
myId = id;
myInv = inv;
}
//copy constructor
public Item(Item OtherItem)
{
myId = OtherItem.getId();
myInv = OtherItem.getInv();
}
public int getId()
{
return myId;
}
public int getInv()
{
return myInv;
}
public int compareTo(Item Other)
{
int compare = 0;
if (myId > Other.getId())
{
compare = 1;
}
else if (myId < Other.getId())
{
compare = -1;
}
return compare;
}
public boolean equals(Item Other)
{
boolean equal = false;
if (myId == Other.getId())
{
equal = true;;
}
return equal;
}
public String toString()
{
String Result;
Result = String.format("%8d%8d", myId, myInv);
return Result;
}
}
This is the creation of my arraylist.
private ArrayList MyStore = new ArrayList ();
Here is a sample of my text file.
3679 87
196 60
12490 12
18618 14
2370 65
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.rosmery;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author Sem-6-INGENIERIAINDU
*/
public class aaa {
public static void main(String arg[]) throws FileNotFoundException, IOException{
BufferedReader files=new BufferedReader(new FileReader(new File("")));
List<String> dto=new ArrayList<>();
String line;
while((line= files.readLine())!= null){
line= files.readLine();
dto.add(line);
//Hacer la logica para esos datos
}
}
}
in.nextLine() returns a String.
So, you cannot assign in.nextLine() to an instance of Item.
Your code may need to correct it as:
List<String> myStore = new ArrayList<String>();
private void loadFile(String FileName)
{
Scanner in;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
myStore.add(in.nextLine());
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
If you want to have a list of Item after reading a file, then you need provide the logic that convert given line of information into an instance of Item.
let's say your file content is in the following format.
id1,inv1
id2,inv2
.
.
Then, you can use the type Item as the following.
List<Item> myStore = new ArrayList<Item>();
private void loadFile(String FileName)
{
Scanner in;
String[] line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine().split(",");
myStore.add(new Item(line[0], line[1]));
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
One of the possible solutions (assuming that the data in file lines is separated by a comma), with using streams:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = loadFile("myfile.txt");
System.out.println(items);
}
private static List<Item> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream
.map(s -> Stream.of(s.split(",")).mapToInt(Integer::parseInt).toArray())
.map(i -> new Item(i[0], i[1]))
.collect(Collectors.toList());
}
}
}
or with foreach:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = new ArrayList<>();
for (String line : loadFile("myfile.txt")) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
int inv = Integer.parseInt(data[1]);
items.add(new Item(id, inv));
}
System.out.println(items);
}
private static List<String> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.collect(Collectors.toList());
}
}
}

why my constructor isn't working

I get enclosing instance of type error in my java code and i don't know what is that error my java code is below
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class phase45 {
public class Vertex {
public Vertex(Integer na){ name = na;}
private Integer name ;
public Integer getname(){
return name;
}
ArrayList adjs = new ArrayList<Integer>();
}
public class graph {
// public Integer name ;
ArrayList Vertexes = new ArrayList<Vertex>();
public Vertex GetVertex(Integer name){
for(int i = 0; i < Vertexes.size(); i++){
if (((Vertex) Vertexes.get(i)).name == name)
return (Vertex) Vertexes.get(i);
}
return null;
}
public void AddVertex(Vertex V){
Vertexes.add(V);
}
}
public static void CreateGraph(File a , graph g) throws IOException{
String st1 , st2 , line;
Integer vs , es;
try {
BufferedReader br = new BufferedReader(new FileReader(a));
st1 = br.readLine();
st2 = br.readLine();
vs = Integer.parseInt(st1);
es = Integer.parseInt(st2);
while ((line = br.readLine()) != null) {
String[] splited = line.split("\\s+");
//Vertex vTemp = null;
Integer NameV = Integer.valueOf(splited[0]);
System.out.println("line + " + line);
//vTemp.name = NameV;
Vertex vTemp = new Vertex(NameV);
Integer AdjV = Integer.valueOf(splited[1]);
vTemp.adjs.add(AdjV);
if(g.GetVertex(NameV) == null)
g.AddVertex(vTemp);
else
g.GetVertex(NameV).adjs.add(AdjV);
}
System.out.println("vs : " + vs + " es "+ es);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
//try{
File file = new File("/Users/mehran/Desktop/filee.txt");
graph g = null;
System.out.println("hi boy");
CreateGraph(file , g);
//}catch(NullPointerException ee){;}
}
}
I get error in CreateGraph this line : Vertex vTemp = new Vertex(NameV);
and I can't understand why , please fix it?
You try to use a C++-Constructor.
In Java you have to write:
Vertex vTemp = new Vertex(NameV); // Class-names should start with a capital letter
The code you attached here compile fine for me. I tried to compile the class Vertex and found it OK.
I think the problem occurred when you try to create object of this class. Try to create Vetex object like this -
Vetex v = new Vertex(name);
Here's a little edit to your code (of course you can instantiate adjs anywhere in your methods)
package test;
import java.util.ArrayList;
public class vertex {
private Integer name ;
public vertex(Integer na){ name = na;}
public Integer getname(){
return name;
}
public static void main(String[] args) {
ArrayList adjs = new ArrayList<Integer>();
}
}
the code compiled, but didn't want to run because you didn't add the main method

I'm getting warning from PostConstruct annotated init method

I'm getting this warning from #PostConstruct annotated init method
Nis 18, 2014 2:46:10 PM com.sun.faces.vendor.WebContainerInjectionProvider getAnnotatedMethodForMethodArr
WARNING: JSF1047: Method 'public void com.revir.managed.bean.PickListBean.init() throws java.lang.Exception' marked with the 'javax.annotation.PostConstruct' annotation cannot declare any checked exceptions. This method will be ignored.
So my method is ignored, what do I have to do to fix this problem ?
package com.revir.managed.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import org.springframework.beans.factory.annotation.Autowired;
#ManagedBean(name = "pickListBean")
#ViewScoped
public class PickListBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<TrvrTani> tanis;
private DualListModel<TrvrIlac> ilacs;
int tanisize = 0;
String taniadi = null;
Long taniidp = null;
public Long getTaniidp() {
return taniidp;
}
public void setTaniidp(Long taniidp) {
this.taniidp = taniidp;
}
String tanikodu = null;
#Autowired(required=false)
private TrvrTaniDAO tanidao;
public TrvrTaniDAO getTanidao() {
return tanidao;
}
public void setTanidao(TrvrTaniDAO tanidao) {
this.tanidao = tanidao;
}
List<TrvrTani> sourcetani;
List<TrvrTani> targettani;
List<TrvrIlac> sourceilac;
List<TrvrIlac> targetilac;
#PostConstruct
public void init(){
try {
sourcetani = new ArrayList<TrvrTani>();
targettani = new ArrayList<TrvrTani>();
tanidao = new TrvrTaniDAO();
List<TrvrTani> taniList = tanidao.findAll();
for (TrvrTani tani : taniList) {
Long taniid = tani.getTaniid();
sourcetani.add(new TrvrTani(taniid, tani.getTaniadi(), tani
.getTanikodu()));
}
tanis = new DualListModel<TrvrTani>(sourcetani, targettani);
sourceilac = new ArrayList<TrvrIlac>();
targetilac = new ArrayList<TrvrIlac>();
ilacdao = new TrvrIlacDAO();
List<TrvrIlac> ilacList = ilacdao.findAll();
for (TrvrIlac ilac : ilacList) {
sourceilac.add(new TrvrIlac(ilac.getIlacid(), ilac.getIlacad(),
ilac.getBarkod(), null));
}
ilacs = new DualListModel<TrvrIlac>(sourceilac, targetilac);
} catch (Exception e) {
System.out.println("Hata mesajı : " +e);
throw e;
}
}
public DualListModel<TrvrIlac> getIlacs() {
return ilacs;
}
public void setIlacs(DualListModel<TrvrIlac> ilacs) {
this.ilacs = ilacs;
}
public DualListModel<TrvrTani> getTanis() {
return tanis;
}
public void setTanis(DualListModel<TrvrTani> tanis) {
this.tanis = tanis;
}
public void onTransferTani(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrTani) item).getTaniadi()).append("<br />");
targetlist(tanisize, taniadi, taniidp, tanikodu);
}
FacesMessage msgtani = new FacesMessage();
msgtani.setSeverity(FacesMessage.SEVERITY_INFO);
msgtani.setSummary("Tanı Eklendi");
msgtani.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgtani);
}
public void targetlist(int tanisize, String taniadi, Long taniidp,
String tanikodu) {
tanisize = tanis.getTarget().size();
System.out.println(" ************target************* : "
+ tanis.getTarget().size());
for (int h = 0; h < tanisize; h++) {
/* elemanin adi, id si ve kodu */
taniadi = tanis.getTarget().get(h).getTaniadi();
System.out.println(" ************taniadi1************* : "
+ taniadi);
taniidp = tanis.getTarget().get(h).getTaniid();
System.out.println(" ************taniid2************* : "
+ taniidp);
tanikodu = tanis.getTarget().get(h).getTanikodu();
System.out.println(" ************tanikodu3************* : "
+ tanikodu);
}
}
public void onTransferIlac(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrIlac) item).getIlacad()).append("<br />");
}
FacesMessage msgilac = new FacesMessage();
msgilac.setSeverity(FacesMessage.SEVERITY_INFO);
msgilac.setSummary("İlaç Eklendi");
msgilac.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgilac);
}
}
Remove the throws Exception from the init method. Use try catch to prevent any exception from being thrown. Once you remove the exception declaration, the compiler will show you of any exceptions that may be thrown, so add try catch there.

Categories

Resources