I've got following .bat-file which is proposed to open a fully working java_cmd portable task.
#echo off
cd /d "%~dp0"
:: cd ..\CommonFiles
:: set Path=%cd%\bin;%path%
set Path=%~d0\PortableApps\CommonFiles\bin;%path%
:: set "JAVA_HOME=%~d0\PortableApps\CommonFiles\jre"
set "JAVA_HOME=%~d0\PortableApps\CommonFiles"
nircmd regsetval dword "HKCU\console" "QuickEdit" "1" >nul 2>&1
cd /d "\Documents\workspaces\java"
start "Java_cmd" cmd /k "cs -w 100x25 -b 100x3000"
I have translated to the following as far:
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using con = System.Console;
namespace javacmd
{
class Program
{
const int HWND_BROADCAST = 0xffff;
const uint WM_SETTINGCHANGE = 0x001a;
[DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam);
static string codeBase = Assembly.GetExecutingAssembly().CodeBase;
static string drive = Path.GetPathRoot(codeBase);
static string oldjavahome = "";
static int Main(string[] args)
{
PrintOutStart();
string args0 = null;
try
{
if (args == null || args0 == "?" || args0 == "/?" || args0 == "--?" || args0 == "help" || args0 == "/help" || args0 == "--help")
{
return PrintOutHelp();
}
else
{
args0 = args[0];
}
}
catch
{
return PrintOutHelp();
}
if (args0 != null)
{
if (!File.Exists(args0+ ".java"))
{
con.WriteLine($"Error: FileNotFound!\nDie Datei {args0} wurde nicht gefunden. Bitte überprüfen Sie, dass\nSie den Namen richtig geschrieben haben!");
con.WriteLine("");
con.Write("Drücken Sie eine beliebige Taste . . . ");
con.ReadLine();
return 1;
}
else
{
string javahome = Path.Combine(drive, #"PortableApps\CommonFiles");
string javabin = Path.Combine(drive, #"PortableApps\CommonFiles\bin");
using (var key = Registry.LocalMachine.OpenSubKey(#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{
var ojh = key.GetValue("JAVA_HOME");
if (ojh != null)
{
oldjavahome = ojh.ToString();
if (oldjavahome != javahome)
{
key.SetValue("JAVA_HOME", javahome);
}
}
var path = key.GetValue("path");
if (path != null)
{
if (!path.ToString().Contains(javabin))
{
key.SetValue("Path", javabin + ";" + path);
}
}
SendNotifyMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, (UIntPtr)0, "Environment");
}
Process p = new Process() { StartInfo = new ProcessStartInfo() { FileName = "javac", Arguments = $"{args0}.java", CreateNoWindow = true, RedirectStandardOutput = true } };
try
{
p.Start();
p.WaitForExit();
con.WriteLine($"output javac: \"{p.StandardOutput}\"");
}
catch
{
con.WriteLine("Error while compiling!\nFehler während des Kompilier-Vorgangs!");
con.WriteLine("");
con.Write("Drücken Sie eine beliebige Taste . . . ");
con.ReadLine();
return 1;
}
p.StartInfo.FileName = "java";
p.StartInfo.Arguments = args0;
try
{
p.Start();
p.WaitForExit();
con.WriteLine($"output java: \"{p.StandardOutput}\"");
}
catch
{
con.WriteLine("Fehler während des Start-Vorgangs!");
con.WriteLine("");
con.Write("Drücken Sie eine beliebige Taste . . . ");
con.ReadLine();
return 1;
}
}
}
else
{
con.WriteLine("Der benötigte Parameter \"args0\" hat den Wert \"null\". Bitte versuchen Sie es erneut!");
con.WriteLine("");
con.Write("Drücken Sie eine beliebige Taste . . . ");
con.ReadLine();
return 1;
}
return 0;
}
private static void PrintOutStart()
{
con.WriteLine("");
con.WriteLine("###################################################");
con.WriteLine("# #");
con.WriteLine("# javacmd #");
con.WriteLine("# #");
con.WriteLine("###################################################");
con.WriteLine("");
}
private static int PrintOutHelp()
{
string name = Path.GetFileNameWithoutExtension(codeBase);
con.WriteLine("Der javacmd compiliert und startet eine angegebene .java-Datei mit nur einem Befehl.");
con.WriteLine("");
con.WriteLine("Syntax: " + name + ".exe [name | [ | / | --]? | [ | / | --]help]");
con.WriteLine("");
con.WriteLine(" name\t\t\tDie zu startende Datei (ohne die Endung \".java\").");
con.WriteLine(" [ | / | --]?\t\tZeigt die Hilfe an. Dies entspricht einer Eingabe ohne Optionen.");
con.WriteLine(" [ | / | --]help\tZeigt die Hilfe an. Dies entspricht einer Eingabe ohne Optionen.");
con.WriteLine("");
con.WriteLine("Wird der javacmd ohne Argument aufgerufen, zeigt er diese Hilfe an.");
con.WriteLine("");
con.Write("Drücken Sie eine beliebige Taste . . . ");
con.ReadLine();
return 1;
}
}
}
The problem is that it throws a System.Security.SecurityException whilst opening the reigstry key. I think this is caused by missing admin rights - which I don't get on all computers I wanna use the program. How do I get this code running the same as the batch code?
My program is located in \Documents\workspaces\java where Documents is a child of (root) usb drive.
Thanks in advance!
Related
I have written a method that calculates a centroid using an inner buffer and adds it to my map. The generated point layer is displayed on the map, but when exporting, I noticed that no attributes are being exported. I need a way to save at least the coordinates in the attribute table.
/*
* Erstellung eines Inneren Puffers mit anschließenden Schwerpunkt für einen
* ausgewählten Layer. Diese Daten sind aus etlichen Internetforum
* zusammengebaut. die Methode hat leider, so vermute ich es, probleme mit
* bestimmten geometrien und somit entstehen Lücken in der Berechnung Variante 1
*/
public void InnerBufferCentroid() throws Exception {
JLabel label = new JLabel("Wählen Sie einen Layer aus:");
List<Layer> layerList = map.layers();
String[] layerNames = new String[layerList.size()];
for (int i = 0; i < layerList.size(); i++) {
layerNames[i] = layerList.get(i).getFeatureSource().getName().toString();
}
String selectedLayer = (String) JOptionPane.showInputDialog(null, label, "Layerauswahl",
JOptionPane.QUESTION_MESSAGE, null, layerNames, layerNames[0]);
FeatureLayer selectedFeatureLayer = null;
for (Layer layer : layerList) {
if (layer.getFeatureSource().getName().toString().equals(selectedLayer)) {
selectedFeatureLayer = (FeatureLayer) layer;
break;
}
}
System.out.println("Layerauswahl abgeschlossen");
SimpleFeatureSource featureSource = (SimpleFeatureSource) selectedFeatureLayer.getFeatureSource();
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
// Erzeuge eine Liste aus den berechneten Zentroiden
List<Point> centroidList = new ArrayList<Point>();
// Berechne für jedes Polygon im Layer den Zentroid
int featureCount = featureCollection.size();
int currentFeature = 0;
while (featureIterator.hasNext()) {
System.out.println("Verarbeite Feature " + currentFeature + " von " + featureCount);
currentFeature++;
SimpleFeature feature = featureIterator.next();
// Überprüfung des Arbeitsfortschrittes
System.out.println("Processing feature with ID: " + feature.getID());
Geometry geometry = (Geometry) feature.getDefaultGeometry();
double originalArea = geometry.getArea();
double bufferArea = originalArea;
Geometry buffer = geometry.buffer(0);
while (bufferArea >= originalArea * 0.05 && bufferArea > 0) {
buffer = buffer.buffer(-500);// aus Performancegründe habe ich mich für 500m Schritte entschieden. Bei
// der Größe werden noch für jeden Polygon Zentroide gerechnet, aber die
// Berechnung dauert nicht zu lange
bufferArea = buffer.getArea();
}
Point centr;
if (buffer instanceof Polygon) {
centr = ((Polygon) buffer).getInteriorPoint();
} else {
MultiPolygon multiPolygon = (MultiPolygon) buffer;
int numGeometries = multiPolygon.getNumGeometries();
Polygon largestPolygon = null;
double largestArea = 0;
for (int i = 0; i < numGeometries; i++) {
Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
double area = polygon.getArea();
if (area > largestArea) {
largestArea = area;
largestPolygon = polygon;
}
}
centr = largestPolygon.getCentroid();
}
centroidList.add(centr);
}
System.out.println("Zentroide berechnet");
// Erzeuge ein Feature Collection aus den berechneten Zentroiden
SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder();
featureTypeBuilder.setName("Centroids");
featureTypeBuilder.setCRS(CRS.decode("EPSG:25832"));
featureTypeBuilder.add("centroid", Point.class);
SimpleFeatureType featureType = featureTypeBuilder.buildFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
SimpleFeatureCollection centroidFeatureCollection = new DefaultFeatureCollection();
for (Point centroid : centroidList) {
featureBuilder.add(centroid);
SimpleFeature centroidFeature = featureBuilder.buildFeature(null);
((DefaultFeatureCollection) centroidFeatureCollection).add(centroidFeature);
}
System.out.println(centroidFeatureCollection.size());
// Erzeuge einen Layer aus den Zentroiden
DefaultFeatureCollection defaultFeatureCollection = new DefaultFeatureCollection(null, featureType);
defaultFeatureCollection.addAll(centroidFeatureCollection);
FeatureSource featureS = new CollectionFeatureSource(defaultFeatureCollection);
// Style style = SLD.createPointStyle("Centroid", Color.RED, Color.RED, 0.5f, 5);
Style style = SLD.createSimpleStyle(featureType);
Layer centroidLayer = new FeatureLayer(featureS, style);
System.out.println("zur karte hinzufügen");
// Füge den Layer dem Map Content hinzu
map.addLayer(centroidLayer);
System.out.println(map.layers());
}
That was my first attempt. At this point, no attributes are being passed, so I am exporting an empty geometry.
After that i tried this:
// Erzeuge eine Liste aus den Attributen für die Punkte
List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Centroids");
builder.setCRS(CRS.decode("EPSG:25832"));
GeometryType geometryType = DataUtilities.createType("centroid", Point.class, CRS.decode("EPSG:25832"));
builder.add(geometryType);
// Erstelle die Feature-Typ-Definition
SimpleFeatureType featureType = builder.buildFeatureType();
// Erstelle die Feature-Collection
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", featureType);
// Erstelle eine SimpleFeatureBuilder-Instanz zum Erstellen von Feature-Objekten
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
// Iteriere über den centroidList und erstelle für jeden Punkt ein Feature-Objekt
for (Point centroid : centroidList) {
// Setze den Wert für das Attribut "centroid" im Feature-Objekt
featureBuilder.set("centroid", centroid);
// Erstelle das SimpleFeature-Objekt
SimpleFeature feature = featureBuilder.buildFeature(null);
// Füge das Feature der Feature-Collection hinzu
featureCollection.addFeature(feature);
}
// Füge die Feature-Collection dem Layer hinzu
FeatureLayer centroidLayer = new FeatureLayer(featureCollection, style);
// Füge den Layer dem Map Content hinzu
map.addLayer(centroidLayer);
// Erzeuge eine Liste aus den Attributen für die Punkte
List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Centroids");
builder.setCRS(CRS.decode("EPSG:25832"));
GeometryType geometryType = DataUtilities.createType("centroid", Point.class, CRS.decode("EPSG:25832"));
builder.add(geometryType);
// Erstelle die Feature-Typ-Definition
SimpleFeatureType featureType = builder.buildFeatureType();
// Erstelle die Feature-Collection
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", featureType);
// Erstelle eine SimpleFeatureBuilder-Instanz zum Erstellen von Feature-Objekten
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
// Iteriere über den centroidList und erstelle für jeden Punkt ein Feature-Objekt
for (Point centroid : centroidList) {
// Setze den Wert für das Attribut "centroid" im Feature-Objekt
featureBuilder.set("centroid", centroid);
// Erstelle das SimpleFeature-Objekt
SimpleFeature feature = featureBuilder.buildFeature(null);
// Füge das Feature der Feature-Collection hinzu
featureCollection.addFeature(feature);
}
// Füge die Feature-Collection dem Layer hinzu
FeatureLayer centroidLayer = new FeatureLayer(featureCollection, style);
// Füge den Layer dem Map Content hinzu
map.addLayer(centroidLayer);
// Erzeuge eine Liste aus den Attributen für die Punkte
List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Centroids");
builder.setCRS(CRS.decode("EPSG:25832"));
GeometryType geometryType = DataUtilities.createType("centroid", Point.class, CRS.decode("EPSG:25832"));
builder.add(geometryType);
// Erstelle die Feature-Typ-Definition
SimpleFeatureType featureType = builder.buildFeatureType();
// Erstelle die Feature-Collection
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", featureType);
// Erstelle eine SimpleFeatureBuilder-Instanz zum Erstellen von Feature-Objekten
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
// Iteriere über den centroidList und erstelle für jeden Punkt ein Feature-Objekt
for (Point centroid : centroidList) {
// Setze den Wert für das Attribut "centroid" im Feature-Objekt
featureBuilder.set("centroid", centroid);
// Erstelle das SimpleFeature-Objekt
SimpleFeature feature = featureBuilder.buildFeature(null);
// Füge das Feature der Feature-Collection hinzu
featureCollection.addFeature(feature);
}
// Füge die Feature-Collection dem Layer hinzu
FeatureLayer centroidLayer = new FeatureLayer(featureCollection, style);
// Füge den Layer dem Map Content hinzu
map.addLayer(centroidLayer);
I put this together from many possible sources, but I keep getting the error
"The method addFeature(SimpleFeature) is undefined for the type DefaultFeatureCollection."
or
The method createType(String, String, String) in the type DataUtilities is not applicable for the arguments (String, Class<Point>, CoordinateReferenceSystem)
i dont know how to fixed that.
I'm trying to do a geolocation, but I keep having this error ~Method does not exist or incorrect signature: void newInstance(System.Location, System.Location) from the type System.Location~
Here's the code:
try{
for(Lead_2__c ld : records){
List<Double> distancias = new List<Double>();
Map<Double,Id> mapDistUd = new Map<Double,Id>();
for(Account ud : accs){
Location locleads = Location.newInstance(ld.Latitude__c,ld.Longitude__c);
Location locUD = Location.newInstance(ud.BillingLatitude,ud.BillingLongitude);
Double dist = Location.getDistance(locleads, locUD, 'km');
mapDistUd.put(dist, ud.Id);
distancias.add(dist);
}
distancias.sort();
System.debug('Unidade distribuidora mais próxima a ' + distancias.get(0) + ' Km');
Id IdConta = mapDistUd.get(distancias.get(0));
System.debug('Id da Unidade Distribuidora que será relacionada ao Lead: ' + IdConta);
if(IdConta != null){
ld.Conta__c = IdConta;
}
}
update records;
} catch (Exception e){
System.debug('ERROR: ' + e.getMessage()+'. In line: ' + e.getLineNumber());
}
}
I am new to this and I am trying to make a simple program that will send a command to the arduino and then send a response back to java via xbee. I am able to send command to arduino but I am unable to read a response from it. I am using XBee S2C with API-2 configuration. How can I read the response from the arduino in my java?
Here is my code for java:
public class Transmitdataxbee {
private static final String PORT = "COM8";
private static final int BAUD_RATE = 9600;
private static RemoteXBeeDevice myremote;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
XBeeDevice myDevice = new XBeeDevice(PORT, BAUD_RATE);
Scanner input_rpi = new Scanner(System.in);
String data;
try {
myDevice.open();
XBeeNetwork myXBeeNetwork = myDevice.getNetwork();
myXBeeNetwork.setDiscoveryTimeout(10000);
myXBeeNetwork.startDiscoveryProcess();
while (myXBeeNetwork.isDiscoveryRunning()) {
System.out.println("Discovering devices...");
}
myremote = myXBeeNetwork.getDevice(new XBee64BitAddress("0013A20041768E48"));
String nodeIdentifier = myremote.getNodeID();
System.out.print("Node ID: ");
System.out.println(nodeIdentifier);
System.out.println("Enter Command");
data = input_rpi.next();
myDevice.sendData(myremote, data.getBytes());
System.out.println("Current timeout: " + myDevice.getReceiveTimeout() + "milliseconds");
//read from arduino
XBeeMessage edMessage = myDevice.readDataFrom(myremote);
String data_ed = edMessage.getDataString();
System.out.println(data_ed);
} catch (XBeeException e) {
e.printStackTrace(System.out);
myDevice.close();
System.exit(1);
}
}
}
and this is my code for arudino
#include <XBee.h>
XBee xbee = XBee();
ZBRxResponse rx = ZBRxResponse();
XBeeAddress64 test = XBeeAddress64(0x0013A200, 0x41768E6E);
ModemStatusResponse msr = ModemStatusResponse();
uint8_t data;
char cmd1[9];
String cmd;
char d_ata;
int j = 0;
int icount = 0;
int count = 32;
void setup() {
Serial.begin(9600);
Serial2.begin(9600);
xbee.setSerial(Serial2);
xbee.setAPImode(2);
Serial.println("Connecting....");
}
void loop() {
xbee.readPacket(50);
if (xbee.getResponse().isAvailable()){
Serial.println("Connected");
Serial.println("Getting Message...");
if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
xbee.getResponse().getZBRxResponse(rx);
Serial.println("Packet received!");
if(rx.getOption() == ZB_PACKET_ACKNOWLEDGED){
Serial.println("Packet acknowledged");
}
cmd = "";
Serial.println("Received Data: ");
for (int i = 0; i < rx.getDataLength(); i++) {
//print8Bits(rx.getData()[i]);
cmd1[i] = (char) rx.getData()[i];
cmd += cmd1[i];
Serial.println(cmd);
Serial.println();
}
if (cmd == "a") {
data = "l";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "w"){
data = "u";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "s"){
data = "d";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "d"){
data = "r";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else{
data="e";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
}
} else if (xbee.getResponse().isError()) {
// some kind of error happened, I put the stars in so
// it could easily be found
Serial.print("************************************* error code:");
Serial.println(xbee.getResponse().getErrorCode(),DEC);
}
}
After a few reasearches I found a piece of documentation from Digi that might help you.
As I thought in my first comment, the problem appears to come from the part where you try to read datas from the device.
According to this documentation : https://www.digi.com/resources/documentation/digidocs/90001438/reference/r_xb_java_lib_data_reception_callback.htm
You have to create a datalistener an register it to your XBeeDevice.
They even give you a few hints about XBeeMessage information.
I don't know your Java level but all the code is provided in the link above.
If you want to read more about listeners, check this : What is the purpose of a listener in Java?
I am trying to draw a graph using java, to do this I got all the infos of my graph into an instance of a class in my main program. To draw the graph I need to transfer this infos into a xml file like this.
My graph is much simpler than the example of the link, my problem is: I have no idea how to transfer my instance of the class to this format.
Below the codes I have (the codes are correct, i just need a way to transfer the atributes of the instance of the class "atividade" to the xml format of the link:
Atividade Class:
/*
* 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 trabalho_m3;
import java.util.Arrays;
public class Atividade {
private int idAtividade;
private String nomeAtividade;
private float tempoDuracao, tInicioCedo, tTerminoCedo, tTerminoTarde, tInicioTarde, folga;
private int qtdPredecessores, qtdSucessores;
private Atividade predecessores[], sucessores[];
private int cnt_aux1 = 0, cnt_aux2 = 0;
public Atividade(int id, String nome, float duracao, int nPre, int nSuc){
this.idAtividade = id;
this.nomeAtividade = nome;
this.tempoDuracao = duracao;
this.qtdPredecessores = nPre;
this.qtdSucessores = nSuc;
this.predecessores = new Atividade[this.qtdPredecessores];
this.sucessores = new Atividade[this.qtdSucessores];
}
/*
* Método que calcula o TEMPO DE INÍCIO CEDO(Tes), assim como
* o TEMPO DE TÉRMINO CEDO(Tef) das atividades do projeto.
*/
public void calcular_Tes_Tef(){
// Cálculo do Tempo de Início Cedo da atividade (Tes).
if(this.qtdPredecessores == 0){
this.tInicioCedo = 0;
} else {
this.tInicioCedo = this.maxTefPredecessores(this.predecessores);
}
// Cálculo do Tempo de Término Cedo da atividade (Tef).
this.tTerminoCedo = (this.tInicioCedo + this.tempoDuracao);
}
/*
* Método que calcula o TEMPO DE TÉRMINO TARDE(Tlf), assim como
* o TEMPO DE INÍCIO TARDE(Tls) das atividades do projeto.
*/
public void calcular_Tlf_Tls(){
// Cálculo do Tempo de Término Tarde da atividade (Tlf).
if(this.qtdSucessores == 0){
this.tTerminoTarde = this.tTerminoCedo;
} else {
this.tTerminoTarde = this.minTlsSucessores(this.sucessores);
}
// Cálculo do Tempo de Início Tarde da atividade (Tls).
this.tInicioTarde = (this.tTerminoTarde - this.tempoDuracao);
}
/*
* Método calcula a FOLGA(R) das atividades do projeto.
*/
public void calcular_R(){
// Cálculo da Folga (R).
this.folga = (this.tTerminoTarde - this.tTerminoCedo);
}
/*
* Método encontra o valor MÁXIMO do Tef entre os predecessores
* de uma atividade.
*
* MAX{Tef(K)}; onde K representa as atividades precedentes.
*/
public float maxTefPredecessores(Atividade predecessores[]){
float maxTef = predecessores[0].tTerminoCedo;
for(int i = 1; i < predecessores.length; i++){
if(maxTef < predecessores[i].tTerminoCedo){
maxTef = predecessores[i].tTerminoCedo;
}
}
return maxTef;
}
/*
* Método encontra o valor MÍNIMO do Tls entre os sucessores
* de uma atividade.
*
* MIN{Tls(K)}; onde K representa as atividades sucessoras.
*/
public float minTlsSucessores(Atividade sucessores[]){
float minTls = sucessores[0].tInicioTarde;
for(int i = 1; i < sucessores.length; i++){
if(sucessores[i].tInicioTarde < minTls){
minTls = sucessores[i].tInicioTarde;
}
}
return minTls;
}
/*
* Vincula a uma dada atividade suas precedencias, incluindo
* seus precedentes no Array predecessores[].
*/
public void setarAtividadePredecessora(Atividade atividadePre){
if(cnt_aux1 == this.qtdPredecessores){
System.out.println("A atividade " + this.nomeAtividade + " nao suporta mais pre-requisitos!");
} else {
this.predecessores[this.cnt_aux1] = atividadePre;
this.cnt_aux1++;
}
}
/*
* Vincula a uma dada atividade seus sucessores.
*/
public void setarAtividadeSucessora(Atividade atividadeSuc){
if(cnt_aux2 == this.qtdSucessores){
System.out.println("A atividade " + this.nomeAtividade + " nao suporta mais atividades sucessoras!");
} else {
this.sucessores[this.cnt_aux2] = atividadeSuc;
this.cnt_aux2++;
}
}
// Retorna o NOME de uma atividade.
public String getNome(){
return this.nomeAtividade;
}
// Retorna a FOLGA(R) de uma atividade.
public float getFolga(){
return this.folga;
}
public float getPredecessores(){
return this.qtdPredecessores;
}
public float getId(){
return this.idAtividade;
}
public float getSucessores(){
return this.qtdSucessores;
}
/*
* Imprime todas as informações de uma atividade:
* Id, Nome, Precedencias, Sucessores, t, Tes, Tef, Tlf, Tls, R.
*/
public void informacoesAtividade(){
System.out.println();
System.out.println("Id: " + this.idAtividade);
System.out.println("Nome: " + this.nomeAtividade);
if(this.qtdPredecessores == 0){
System.out.println("Precedencia: --");
} else {
System.out.print("Precedencia: ");
for(int i = 0; i < this.predecessores.length; i++){
System.out.print(predecessores[i].nomeAtividade + " ");
}
System.out.println();
}
if(this.qtdSucessores == 0){
System.out.println("Sucessores: --");
} else {
System.out.print("Sucessores: ");
for(int j = 0; j < this.sucessores.length; j++){
System.out.print(sucessores[j].nomeAtividade + " ");
}
System.out.println();
}
System.out.println();
System.out.println("t: " + this.tempoDuracao);
System.out.println("Tes: " + this.tInicioCedo);
System.out.println("Tef: " + this.tTerminoCedo);
System.out.println("Tlf: " + this.tTerminoTarde);
System.out.println("Tls: " + this.tInicioTarde);
System.out.println("R: " + this.folga);
System.out.println();
}
}
Main:
package trabalho_m3;
import java.io.IOException;
import java.util.Scanner;
public class TRABALHO_M3 {
public static void Tes_Tef(Atividade[] Ativ){
for(int i = 0; i < Ativ.length; i++){
Ativ[i].calcular_Tes_Tef();
}
}
public static void Tlf_Tls(Atividade[] Ativ){
for(int i = (Ativ.length - 1); i >= 0; i--){
Ativ[i].calcular_Tlf_Tls();
}
}
public static void R(Atividade[] Ativ){
for(int i = 0; i < Ativ.length; i++){
Ativ[i].calcular_R();
}
}
public static void atividadeInfo(Atividade[] Ativ){
for(int i = 0; i < Ativ.length; i++){
Ativ[i].informacoesAtividade();
}
}
public static void caminhoCritico(Atividade[] Ativ){
System.out.print("Caminho Critico: ");
for(int i = 0; i < Ativ.length; i++){
if(Ativ[i].getFolga() == 0.0){
System.out.print(Ativ[i].getNome() + " ");
}
}
System.out.println();
}
public static void main(String[] args) throws IOException {
int qtd = 0;
int aux;
String rotulo;
float peso;
int predecessores, sucessores;
Scanner s = new Scanner(System.in);
System.out.println("Informe a quantidade de atividades: ");
qtd = s.nextInt();
Atividade atividades[] = new Atividade[qtd];
for (int i = 0; i < qtd; i++){
System.out.println("Informe o rótulo da atividade["+(i+1)+"]: ");
rotulo = s.next();
System.out.println("Informe a duracao da atividade["+(i+1)+"]: ");
peso = s.nextFloat();
System.out.println("Informe a quantidade de predecessores da atividade["+(i+1)+"]: ");
predecessores = s.nextInt();
System.out.println("Informe a quantidade de sucessores da atividade["+(i+1)+"]: ");
sucessores = s.nextInt();
atividades[i] = new Atividade(i,rotulo,peso,predecessores,sucessores);
System.out.println("Pressione Enter para continuar...");
System.in.read();
}
for (int i = 0; i < qtd; i++){
for (int b = 0; b < qtd; b++){
System.out.println("Atividade "+atividades[b].getNome()+" - ID = "+atividades[b].getId());
}
System.out.println("Pressione Enter para continuar...");
System.in.read();
if (atividades[i].getPredecessores() > 0 ) {
System.out.println("Atividades Predecessoras de "+atividades[i].getNome());
for (int k=0; k<atividades[i].getPredecessores(); k++){
System.out.println("Informe o ID da atividade predecessora de numero "+(k+1)+" ...");
aux = s.nextInt();
atividades[i].setarAtividadePredecessora(atividades[aux]);
System.out.println("Pressione Enter para continuar...");
System.in.read();
Runtime.getRuntime().exec("clear");
}
} else {
System.out.println("A atividade ["+atividades[i].getNome()+"] não possui predecessores");
System.out.println("Pressione Enter para continuar...");
System.in.read();
}
for (int b = 0; b < qtd; b++){
System.out.println("Atividade "+atividades[b].getNome()+" - ID = "+atividades[b].getId());
}
System.out.println("Pressione Enter para continuar...");
System.in.read();
if (atividades[i].getSucessores() > 0 ) {
System.out.println("Atividades Sucessoras de "+atividades[i].getNome());
for (int k=0; k<atividades[i].getSucessores(); k++){
System.out.println("Informe o id da atividade sucessora de numero "+(k+1)+" ...");
aux = s.nextInt();
atividades[i].setarAtividadeSucessora(atividades[aux]);
System.out.println("Pressione Enter para continuar...");
System.in.read();
}
} else {
System.out.println("A atividade ["+atividades[i].getNome()+"] não possui sucessores");
System.out.println("Pressione Enter para continuar...");
System.in.read();
}
}
Tes_Tef(atividades);
Tlf_Tls(atividades);
atividadeInfo(atividades);
R(atividades);
caminhoCritico(atividades);
}
}
OBS .: I need to transfer to a xml file because the lib i am going to use to draw the graph needs it. I am going to use the prefuse lib.
If all you need is to draw the graph with prefuse, you do not need to create a xml file for that. You can a prefuse graph object and add nodes, edges directly to it. Here is a simple example with 2 nodes, 1 edge, and a property value on 1 node:
Graph graph = new Graph();
graph.getNodeTable().addColumn("duration", double.class);
Node n1 = graph.addNode();
n1.setDouble("duration", 20.0);
Node n2 = graph.addNode();
Edge e = graph.addEdge(n1, n2);
You would need to iterate over all nodes and edge of your custom class.
I have a problem to get to right object. When I start my program it creates a object. And when I call opon a methode, the methode creates a new object, but when I am trying to print the object information, I am getting information from the first object. How do I refere to the new object ?
public Meny () {
tekstgr = new Tekstgrensesnitt();
fil = new Fil();
this.cde = new CDarkiv();
}
public CDArkivADT lesFraFil(CDArkivADT cde, String filnavn) throws java.io.IOException {
try {
// // 1 - FileReader
FileReader ansFil = new FileReader(filnavn);
// 2 - BufferedReader
BufferedReader innfil = new BufferedReader(ansFil);
// 3 - Leser den første posten som er antall info-poster
String linje = innfil.readLine();
int n = Integer.parseInt(linje);
// Oppretter CDarkiv
cde = new CDarkiv(n);
// 4 - Les postene, en hel post om gangen
for (int i = 0; i < n; i++) {
String post = innfil.readLine();
String[] felt = post.split(SKILLE);
int nr = Integer.parseInt(felt[0]);
String artist = felt[1];
String tittel = felt[2];
int år = Integer.parseInt(felt[3]);
Sjanger sjanger = Sjanger.valueOf(felt[4]); //Eventuelt lagret som heltall
//...Må så konvertere til enum
String plselskap = felt[5];
CD cd = new CD(nr, artist, tittel, år, sjanger, plselskap);
cde.leggTilCd(cd);
}
System.out.println(Arrays.toString(cde.getArkiv()));
// 4 - Lukk filen
innfil.close();
}
catch (FileNotFoundException unntak) {//arver fra IOException må stå først
// hvis ikke vil unntaket for IOException skygge
System.out.println("Finner ikke filen " + filnavn);
System.exit(-1);
}
catch (IOException e) {
System.out.println("Feil ved lesing av fil: " + e);
System.exit(1);
}
return cde;
}
public void start() {
Scanner tast = new Scanner(System.in);
String filnav = "test.txt";
System.out.println("Press '1' for å 'Lese fra fil'" + "\n" + "Press '2' for å 'Skrive til fil'");
int g = tast.nextInt();
if(g == 1) {
try {
fil.lesFraFil(cde, filnav);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Tast '1' for å søke etter tittel." + "\n" + "Tast '2' for å søke etter artist/gruppe");
int f = tast.nextInt();
if(f == 1) {
String twmp = tast.nextLine();
String temp = tast.nextLine();
CD d = cde.finnCD(temp);
tekstgr.visCD(d);
} else {
String temp = tast.nextLine();
cde.finnArtist(temp);
}
}
public static void main(String[] args) {
Meny meny = new Meny();
meny.start();
}
Where is your first declaration of cde?
When you pass it through your method, the reference you get in your parameters is a copy of the original reference, thus assigning a value to it does not change the original variable.
I see you are returning cde in your method, and this works, but you are not using the returned object in your main method. I'd suggest remove the cde parameter as it is pointless, and change your lesFraFil call like this:
CDArkivADT cde = file.lesFraFil(filnav);
public class CDarkiv implements CDArkivADT {
private CD[] cdTabell;
private int antall;
public CDarkiv (int antall) {
this.antall = antall;
cdTabell = new CD[antall];
}
public CDarkiv() {
antall = 0;
cdTabell = new CD[0];
}
{...}
public interface CDArkivADT {
public void utvidKapasitet(); //Utvider kapasiteten til et CD arkiv
public CD[] getArkiv(); //Henter arkiv
public void leggTilCd (CD c); //Legger til en CD i arkiv
public void slettCd (CD c); //Sletter en CD i arkiv
public CD finnCD (String s); //Finner CD-er ved gitt delstreng
public String finnArtist (String s); //Finner alle CD-er som tilhører en artist ved gitt delstring
public int hentAntall(Sjanger sjanger); //Henter antall CD-er i en sjanger
public int getAntall (); //Henter antall CD-er
}