Search Results

Search found 37 results on 2 pages for 'printstream'.

Page 1/2 | 1 2  | Next Page >

  • What is the best way, if possible, to send information from a Java PrintStream to a JTextPane?

    - by Daniel Reeves
    In Java, I have a package that translates XML metadata from one standard to another. This package is ultimately accessed through a single function and sends all of its output through a PrintStream object. The output sent is just a status of each file and whether or not it was translated. This is pretty fine and dandy if I'm just printing to System.out, but I'm actually wanting to print this to a JTextPane while it translates (kind of like a progress text box). It wouldn't be a big deal to just print the status after it was done translating the XML, but since there may be thousands of XML files, that's just not feasible. One thing that I've tried is to use a thread that takes all of the information from the PrintStream (which is attached to a ByteArrayOutputStream) and let it send any new information to the text pane. Unfortunately, this still sends the information all at once at the end of the translation. This does work correctly for System.out. Here's the code that does the translation and tries to show the output: public class ConverterGUI extends javax.swing.JFrame { boolean printToResultsBox = false; PrintStream printStream = null; ByteArrayOutputStream baos = null; private class ResultsPrinter implements Runnable { public ResultsPrinter() { baos = new ByteArrayOutputStream(); printStream = new PrintStream(baos); } public void run() { String tempString = ""; while (printToResultsBox) { try { if (!baos.toString().equals(tempString)) { tempString = baos.toString(); resultsBox.setText(tempString); } } catch (Exception ex) { } } } } ... ResultsPrinter rp = new ResultsPrinter(); Thread thread = new Thread(rp); thread.start(); // Do the translation. try { printToResultsBox = true; boolean success = false; TranslationEngine te = new TranslationEngine(); // fileOrFolderToConvert is a text box in the GUI. // linkNeeded and destinationFile are just parameters for the translation process. success = te.translate(fileOrFolderToConvert.getText(), linkNeeded, destinationFile, printStream); if (success) { printStream.println("File/folder translation was a success."); } resultsBox.setText(baos.toString()); } catch (Exception ex) { printStream.println("File translation failed."); } finally { printToResultsBox = false; } ... } Ultimately, this code prints out to the JTextPane just fine after all the translation is done but not during. Any suggestions? Do I need to change the PrintStream to something else?

    Read the article

  • Java: Difference between PrintStream and PrintWriter

    - by Martijn Courteaux
    Hi, What is the difference between PrintStream and PrintWriter? They have much methods in common. I always mix up this classes because of that reason. And I think we can use them for exactly the same. But there has to be a difference. Otherwise there was only one class. I first searched on StackOverflow, but not yet this question. Thanks

    Read the article

  • plain old system.out question

    - by mac
    I was looking at someone's code and saw that he repeatedly declared PrintStream out = System.out; and later called out.println("blah"); I actually thought this was kind of neat. Is this a common practice? Was he just being fancy?

    Read the article

  • Why is javac 1.5 running so slowly compared with the Eclipse compiler?

    - by Simon Nickerson
    I have a Java Maven project with about 800 source files (some generated by javacc/JTB) which is taking a good 25 minutes to compile with javac. When I changed my pom.xml over to use the Eclipse compiler, it takes about 30 seconds to compile. Any suggestions as to why javac (1.5) is running so slowly? (I don't want to switch over to the Eclipse compiler permanently, as the plugin for Maven seems more than a little buggy.) I have a test case which easily reproduces the problem. The following code generates a number of source files in the default package. If you try to compile ImplementingClass.java with javac, it will seem to pause for an inordinately long time. import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; public class CodeGenerator { private final static String PATH = System.getProperty("java.io.tmpdir"); private final static int NUM_TYPES = 1000; public static void main(String[] args) throws FileNotFoundException { PrintStream interfacePs = new PrintStream(PATH + File.separator + "Interface.java"); PrintStream abstractClassPs = new PrintStream(PATH + File.separator + "AbstractClass.java"); PrintStream implementingClassPs = new PrintStream(PATH + File.separator + "ImplementingClass.java"); interfacePs.println("public interface Interface<T> {"); abstractClassPs.println("public abstract class AbstractClass<T> implements Interface<T> {"); implementingClassPs.println("public class ImplementingClass extends AbstractClass<Object> {"); for (int i=0; i<NUM_TYPES; i++) { String nodeName = "Node" + i; PrintStream nodePs = new PrintStream(PATH + File.separator + nodeName + ".java"); nodePs.printf("public class %s { }\n", nodeName); nodePs.close(); interfacePs.printf("void visit(%s node, T obj);%n", nodeName); abstractClassPs.printf("public void visit(%s node, T obj) { System.out.println(obj.toString()); }%n", nodeName); } interfacePs.println("}"); abstractClassPs.println("}"); implementingClassPs.println("}"); interfacePs.close(); abstractClassPs.close(); implementingClassPs.close(); } }

    Read the article

  • Does this variable need to be declared volatile?

    - by titaniumdecoy
    Does the out variable in the MyThread class need to be declared volatile in this code or will the "volatility" of the stdout variable in the ThreadTest class carry over? import java.io.PrintStream; class MyThread implements Runnable { int id; PrintStream out; // should this be declared volatile? MyThread(int id, PrintStream out) { this.id = id; this.out = out; } public void run() { try { Thread.currentThread().sleep((int)(1000 * Math.random())); out.println("Thread " + id); } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadTest { static volatile PrintStream stdout = System.out; public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(new MyThread(i, stdout)).start(); } } }

    Read the article

  • Wildcards vs. generic methods

    - by FredOverflow
    Is there any practical difference between the following approaches to print all elements in a range? public static void printA(Iterable<?> range) { for (Object o : range) { System.out.println(o); } } public static <T> void printB(Iterable<T> range) { for (T x : range) { System.out.println(x); } } Apparently, printB involves an additional checked cast to Object (see line 16), which seems rather stupid to me -- isn't everything an Object anyway? public static void printA(java.lang.Iterable); Code: 0: aload_0 1: invokeinterface #18, 1; //InterfaceMethod java/lang/Iterable.iterator:()Ljava/util/Iterator; 6: astore_2 7: goto 24 10: aload_2 11: invokeinterface #24, 1; //InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object; 16: astore_1 17: getstatic #30; //Field java/lang/System.out:Ljava/io/PrintStream; 20: aload_1 21: invokevirtual #36; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V 24: aload_2 25: invokeinterface #42, 1; //InterfaceMethod java/util/Iterator.hasNext:()Z 30: ifne 10 33: return public static void printB(java.lang.Iterable); Code: 0: aload_0 1: invokeinterface #18, 1; //InterfaceMethod java/lang/Iterable.iterator:()Ljava/util/Iterator; 6: astore_2 7: goto 27 10: aload_2 11: invokeinterface #24, 1; //InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object; 16: checkcast #3; //class java/lang/Object 19: astore_1 20: getstatic #30; //Field java/lang/System.out:Ljava/io/PrintStream; 23: aload_1 24: invokevirtual #36; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V 27: aload_2 28: invokeinterface #42, 1; //InterfaceMethod java/util/Iterator.hasNext:()Z 33: ifne 10 36: return

    Read the article

  • [Netbeans 6.9] Java MethodOverloading error with double values

    - by Nimitips
    Here is a part of my code I'm having trouble with: ===Class Overload=== public class Overload { public void testOverLoadeds() { System.out.printf("Square of integer 7 is %d\n",square(7)); System.out.printf("Square of double 7.5 is %d\n",square(7.5)); }//..end testOverloadeds public int square(int intValue) { System.out. printf("\nCalled square with int argument: %d\n",intValue); return intValue * intValue; }//..end square int public double square(double doubleValue) { System.out.printf("\nCalled square with double argument: %d\n", doubleValue); return doubleValue * doubleValue; }//..end square double }//..end class overload ===Main=== public static void main(String[] args) { Overload methodOverload = new Overload(); methodOverload.testOverLoadeds(); } It compiles with no error, however when I try to run it the output is: Called square with int argument: 7 Square of integer 7 is 49 Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999) at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709) at java.util.Formatter$FormatSpecifier.print(Formatter.java:2661) at java.util.Formatter.format(Formatter.java:2433) at java.io.PrintStream.format(PrintStream.java:920) at java.io.PrintStream.printf(PrintStream.java:821) at methodoverload.Overload.square(Overload.java:19) at methodoverload.Overload.testOverLoadeds(Overload.java:8) at methodoverload.Main.main(Main.java:9) Called square with double argument:Java Result: 1 What am I doing wrong? I'm on Ubuntu 10.10, Netbeans 6.9. Thanks.

    Read the article

  • Create and Share a File (Also a mysterious error)

    - by Kirk
    My goal is to create a XML file and then send it through the share Intent. I'm able to create a XML file using this code FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE); PrintStream printStream = new PrintStream(outputStream); String xml = this.writeXml(); // get XML here printStream.println(xml); printStream.close(); I'm stuck trying to retrieve a Uri to the output file in order to share it. I first tried to access the file by converting the file to a Uri File outFile = context.getFileStreamPath(fileName); return Uri.fromFile(outFile); This returns file:///data/data/com.my.package/files/myfile.xml but I cannot appear to attach this to an email, upload, etc. If I manually check the file length, it's proper and shows there is a reasonable file size. Next I created a content provider and tried to reference the file and it isn't a valid handle to the file. The ContentProvider doesn't ever seem to be called a any point. Uri uri = Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + fileName); return uri; This returns content://com.my.package.provider/myfile.xml but I check the file and it's zero length. How do I access files properly? Do I need to create the file with the content provider? If so, how? Update Here is the code I'm using to share. If I select Gmail, it does show as an attachment but when I send it gives an error Couldn't show attachment and the email that arrives has no attachment. public void onClick(View view) { Log.d(TAG, "onClick " + view.getId()); switch (view.getId()) { case R.id.share_cancel: setResult(RESULT_CANCELED, getIntent()); finish(); break; case R.id.share_share: MyXml xml = new MyXml(); Uri uri; try { uri = xml.writeXmlToFile(getApplicationContext(), "myfile.xml"); //uri is "file:///data/data/com.my.package/files/myfile.xml" Log.d(TAG, "Share URI: " + uri.toString() + " path: " + uri.getPath()); File f = new File(uri.getPath()); Log.d(TAG, "File length: " + f.length()); // shows a valid file size Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Share")); } catch (FileNotFoundException e) { e.printStackTrace(); } break; } } I noticed that there is an Exception thrown here from inside createChooser(...), but I can't figure out why it's thrown. E/ActivityThread(572): Activity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@4148d658 that was originally registered here. Are you missing a call to unregisterReceiver()? I've researched this error and can't find anything obvious. Both of these links suggest that I need to unregister a receiver. Chooser Activity Leak - Android Why does Intent.createChooser() need a BroadcastReceiver and how to implement? I have a receiver setup, but it's for an AlarmManager that is set elsewhere and doesn't require the app to register / unregister. Code for openFile(...) In case it's needed, here is the content provider I've created. public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { String fileLocation = getContext().getCacheDir() + "/" + uri.getLastPathSegment(); ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY); return pfd; }

    Read the article

  • Java assert nasty side-effect - compiler bug?

    - by Alex
    This public class test { public static void main(String[] args) { Object o = null; assert o != null; if(o != null) System.out.println("o != null"); } } prints out "o != null"; both 1.5_22 and 1.6_18. Compiler bug? Commenting out the assert fixes it. The byte code appears to jump directly to the print statement when assertions are disabled: public static main(String[]) : void L0 LINENUMBER 5 L0 ACONST_NULL ASTORE 1 L1 LINENUMBER 6 L1 GETSTATIC test.$assertionsDisabled : boolean IFNE L2 ALOAD 1: o IFNONNULL L2 NEW AssertionError DUP INVOKESPECIAL AssertionError.<init>() : void ATHROW L2 LINENUMBER 8 L2 GETSTATIC System.out : PrintStream LDC "o != null" INVOKEVIRTUAL PrintStream.println(String) : void L3 LINENUMBER 9 L3 RETURN L4

    Read the article

  • What structure of data use to communicate via tcp/ip in java?

    - by rmaster
    Let's assume I want to send many messages between 2 programs made in java that use TCP sockets. I think the most convienient way is to send objects like: PrintStream ps = new PrintStream(s.getOutputStream()); ObjectOutputStream oos = new ObjectOutputStream(ps); some_kind_of_object_here; oos.writeObject(some_kind_of_object_here); ps.print(oos); I want to send, strings, numbers, HashMaps, boolean values How can I do this using fx 1 object that can store all that properties? I though about ArrayList that is serializable and we can put there everything but is not elegant way. I want to send different types of data because user can choose from a variety of options that server can do for it. Any advices?

    Read the article

  • GlassFish cluster-targeted jdbc is not enabled

    - by Jin Kwon
    I have a GlassFish cluster. When I tried to add node and a instance, DAS saids a bunch of error messages telling Resource [ jdbc/xxxx ] of type [ jdbc ] is not enabled [#|2012-11-14T12:07:04.318+0900|SEVERE|glassfish3.1.2|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=2803;_ThreadName=Thread-2;|java.lang.StackOverflowError at java.io.FileOutputStream.writeBytes(Native Method) at java.io.FileOutputStream.write(FileOutputStream.java:318) at java.io.BufferedOutputStream.write(BufferedOutputStream.java:122) at java.io.PrintStream.write(PrintStream.java:480) at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221) at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291) at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295) at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141) at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229) at java.util.logging.StreamHandler.flush(StreamHandler.java:242) at java.util.logging.ConsoleHandler.publish(ConsoleHandler.java:106) at java.util.logging.Logger.log(Logger.java:522) at com.sun.logging.LogDomains$1.log(LogDomains.java:372) at java.util.logging.Logger.doLog(Logger.java:543) at java.util.logging.Logger.log(Logger.java:607) at com.sun.enterprise.resource.deployer.JdbcResourceDeployer.deployResource(JdbcResourceDeployer.java:117) at org.glassfish.javaee.services.ResourceProxy.create(ResourceProxy.java:90) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:507) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455) at javax.naming.InitialContext.lookup(InitialContext.java:411) at javax.naming.InitialContext.lookup(InitialContext.java:411) at com.sun.appserv.connectors.internal.api.ResourceNamingService.lookup(ResourceNamingService.java:221) the JDBC Resource is ok and targeted with the cluster. I've installed the JDBC driver on the new node. Can anybody help?

    Read the article

  • GroupLayout: JScrollPane in TextArea is not working

    - by Dozent
    i'm new in java and recently started to develop an simple application. For the moment i have a problem with JScrollPanne, it's not able to scroll down (or up) when the text in textarea more than size of area. I have looked to some solutions, but all of them were for FlowLayot (GridLayout and BoxLayout), but not for GroupLayout. Here is the code: JPanel conent_p = new JPanel(); conent_p.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JLabel lblItemName = new JLabel("Item name:"); itemField = new JTextField(); itemField.setColumns(10); JLabel lblMxPrice = new JLabel("Max price:"); mpriceField = new JTextField(); mpriceField.setColumns(10); JLabel lblQuantity = new JLabel("Quantity:"); quanField = new JTextField(); quanField.setColumns(10); JLabel lblDelivery = new JLabel("Delivery:"); delivField = new JTextField(); delivField.setColumns(10); JLabel lblLogcat = new JLabel("LogCat:"); final JTextArea txtConsole = new JTextArea(); txtConsole.setEditable(false); txtConsole.setLineWrap(true); txtConsole.setWrapStyleWord(true); sbrText = new JScrollPane(txtConsole); sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a // PrintStream around it to support the println/printf methods. PrintStream out = new PrintStream(new TextAreaOutputStream(txtConsole)); // redirect standard output stream to the TextAreaOutputStream System.setOut(out); // redirect standard error stream to the TextAreaOutputStream System.setErr(out); GroupLayout gl_conent_p = new GroupLayout(conent_p); gl_conent_p.setHorizontalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addComponent(lblMxPrice, Alignment.TRAILING) .addComponent(lblItemName, Alignment.TRAILING) .addComponent(lblLogcat, Alignment.TRAILING)) .addGap(18) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING, false) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 365, GroupLayout.PREFERRED_SIZE) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblQuantity) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(quanField, 0, 0, Short.MAX_VALUE) .addGap(18) .addComponent(lblDelivery) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED))) .addGap(100)) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 345, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText) .addContainerGap()))) ); gl_conent_p.setVerticalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblItemName) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)) .addGap(20) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblDelivery) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblMxPrice) .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblQuantity) .addComponent(quanField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(55) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblLogcat) .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText)) .addContainerGap()) ); conent_p.setLayout(gl_conent_p); getContentPane().add(conent_p, BorderLayout.NORTH); JButton btnBuy = new JButton("Buy"); btnBuy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { try { String title = itemField.getText().trim(); String mprice = mpriceField.getText().trim(); String quantity = quanField.getText().trim(); String deliver = delivField.getText().trim(); Item_CONCEPT item = new Item_CONCEPT(); item.setName(title); item.setDelivery(Integer.parseInt(deliver)); item.setStartPrice(0); item.setMaxPrice(Integer.parseInt(mprice)); myAgent.existsSeller(item); Date date = new Date(); DateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); System.out.println(df.format(date)+": Buyer orders an item: "+item.getName()); //Clearing all fields itemField.setText(""); quanField.setText(""); delivField.setText(""); //txtConsole.setText(""); mpriceField.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(BuyerGUI.this, "A field is filled incorrectly. "+e.getMessage()+" is invalid.", "Error", JOptionPane.ERROR_MESSAGE); } } } );![enter image description here][1]

    Read the article

  • TCP client in C and server in Java

    - by faldren
    I would like to communicate with 2 applications : a client in C which send a message to the server in TCP and the server in Java which receive it and send an acknowledgement. Here is the client (the code is a thread) : static void *tcp_client(void *p_data) { if (p_data != NULL) { char const *message = p_data; int sockfd, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { error("ERROR opening socket"); } server = gethostbyname(ALARM_PC_IP); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(TCP_PORT); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) { error("ERROR connecting"); } n = write(sockfd,message,strlen(message)); if (n < 0) { error("ERROR writing to socket"); } bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) { error("ERROR reading from socket"); } printf("Message from the server : %s\n",buffer); close(sockfd); } return 0; } And the java server : try { int port = 9015; ServerSocket server=new ServerSocket(port); System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":"+port); System.out.println("Run the Client"); while (true) { Socket socket=server.accept(); BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(in.readLine()); PrintStream out=new PrintStream(socket.getOutputStream()); out.print("Welcome by server\n"); out.flush(); out.close(); in.close(); System.out.println("finished"); } } catch(Exception err) { System.err.println("* err"+err); } With n = read(sockfd,buffer,255); the client is waiting a response and for the server, the message is never ended so it doesn't send a response with PrintStream. If I remove these lines : bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) { error("ERROR reading from socket"); } printf("Message from the server : %s\n",buffer); The server knows that the message is finished but the client can't receive the response. How solve that ? Thank you

    Read the article

  • Dealing with Try/Catch Exceptions in Java bytecode? ("stack height inconsistent")

    - by Cogwirrel
    I am trying to do some error handling in java bytecode. I first tried to implement some catch-like subroutines, where I would check for the error condition, and jump to the appropriate subroutine, a little like: iconst_1 iconst_0 dup ifeq calldiverr goto enddivtest calldiverr: jsr divError enddivtest: idiv ...More instructions... divError: getstatic java/lang/System/out Ljava/io/PrintStream; ldc "Oh dear you divided by 0!" invokevirtual java/io/PrintStream/print(Ljava/lang/String;)V The problem with the above is that when I have multiple instructions that jump to this subroutine, I get an error message when running the bytecode, saying that the stack height is inconsistent. Perhaps using exceptions is the best way to get around this? From some googling I have found that you can create instances of Exception classes and initialise them with something like: new java/lang/Exception dup ldc "exception message!" invokespecial java/lang/Exception/<init>(Ljava/lang/String;)V I have also found that you can throw them with athrow and this seems ok. What is confusing me however is exactly how exceptions are caught. There seems to be a magical "Exception table" which glues the throwing and catching of exceptions together, but I do not know how to define one of these when writing bytecode from scratch (and assembling using Jasmin). Can somebody tell me the secret of creating an exception table? And possibly give me an example of exception handling that will assemble with jasmin?

    Read the article

  • Why does Jcreator show iIlegal start of expression?

    - by Inusual Whisper Sinclair
    I am new at programming and currently in our classes we are learning java. I am trying to create a routine in which I need to use String variables only. Below it is the code in which I am working with: public static void main(String[] args) throws java.io.IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System. in )); PrintStream out = System.out; String hair.equals("damagedHair"); cutHair(marvin); cleanHair(michelle); for (int i = 0; i < 2; i++) { static void cutHair(String marvin) { String cabello; marvin.equals(hair); if (marvin.equals("damagedHair")) { cabello.equals("newHaircut"); result(hair); } static void cleanHair(String michelle) { String hair; michelle.equals(hair); if (michelle.equals(newHaircut)) { hair.equals("putShampooAndConditioner"); result(hair); } static void result(String pHair) {; PrintStream out = System.out; out.println("============="); out.println(pHair); out.println("============="); } } Jcreator is giving me an error that says Illegal start of expression and also java 50 error ';' expected. I am not sure why is this coming up and I am a little confused as to whether I am doing something I am not supposed to and how to correct it. Sorry about the double posting, this is the right message. Need some help from you guys to figure this out. Thanks in advanced!

    Read the article

  • FileNotFoundException Java

    - by Troels Hansen
    Hi, I'm trying to make a simple highscore system for a minesweeper game. However i keep getting a file not found exception, and i've tried to use the full path for the file aswell. package minesweeper; import java.io.*; import java.util.*; public class Highscore{ public static void submitHighscore(String difficulty) throws IOException{ int easy = 99999; int normal = 99999; int hard = 99999; //int newScore = (int) MinesweeperView.getTime(); int newScore = 10; File f = new File("Highscores.dat"); if (!f.exists()){ f.createNewFile(); } Scanner input = new Scanner(f); PrintStream output = new PrintStream(f); if (input.hasNextInt()){ easy = input.nextInt(); normal = input.nextInt(); hard = input.nextInt(); } output.flush(); if(difficulty.equals("easy")){ if (easy > newScore){ easy = newScore; } }else if (difficulty.equals("normal")){ if (normal > newScore){ normal = newScore; } }else if (difficulty.equals("hard")){ if (hard > newScore){ hard = newScore; } } output.println(easy); output.println(normal); output.println(hard); } //temporary main method used for debugging public static void main(String[] args) throws IOException { submitHighscore("easy"); } }

    Read the article

  • Java if/else behaving strangely

    - by Alex
    I'm a real newbie to java, so please excuse me if this is a hopelessly straightforward problem. I have the following from my java game server: // Get input from the client DataInputStream in = new DataInputStream (server.getInputStream()); PrintStream out = new PrintStream(server.getOutputStream()); disconnect=false; while((line = in.readLine().trim()) != null && !line.equals(".") && !line.equals("") && !disconnect) { System.out.println("Received "+line); if(line.equals("h")){ out.println("h"+EOF); // Client handshake System.out.println("Matched 1"); }else if (line.equals("<policy-file-request/>")) { out.println("..."+EOF); // Policy file System.out.println(server.getInetAddress()+": Policy Request"); disconnect=true; System.out.println("Matched 2"); }else if(line.substring(0,3).equals("GET")||line.substring(0,4).equals("POST")){ out.println("HTTP/1.0 200 OK\nServer: VirtuaRoom v0.9\nContent-Type: text/html\n\n..."); // HTML status page disconnect=true; System.out.println("Matched 3"); } else { System.out.println(server.getInetAddress()+": Unknown command, client disconnected."); disconnect=true; System.out.println("Matched else"); } } server.close(); First of all, the client sends an "h" packet, and expects the same back (handshake). However, I want it to disconnect the client when an unrecognised packet is received. For some reason, it responds fine to the handshake and HTML status request, but the else clause is never executed when there's an unknown packet. Thanks

    Read the article

  • Java redirected system output to jtext area, doesnt update until calculation is finished

    - by user1806716
    I have code that redirects system output to a jtext area, but that jtextarea doesnt update until the code is finished running. How do I modify the code to make the jtextarea update in real time during runtime? private void updateTextArea(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { consoleTextAreaInner.append(text); } }); } private void redirectSystemStreams() { OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { updateTextArea(String.valueOf((char) b)); } @Override public void write(byte[] b, int off, int len) throws IOException { updateTextArea(new String(b, off, len)); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } }; System.setOut(new PrintStream(out, true)); System.setErr(new PrintStream(out, true)); } The rest of the code is mainly just an actionlistener for a button: private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String shopRoot = this.shopRootDirTxtField.getText(); String updZipPath = this.updateZipTextField.getText(); this.mainUpdater = new ShopUpdater(new File(shopRoot), updZipPath); this.mainUpdater.update(); } That update() method begins the process of copying+pasting files on the file system and during that process uses system.out.println to provide an up-to-date status on where the program is currently at in reference to how many more files it has to copy.

    Read the article

  • how to configure jetty 7 to use syslog or log4j

    - by egemen ozden
    I am looking for a way to direct all the jetty 7 logging to syslog. My current configuration dumps everything to JETTY_HOME/logs/.. After some initial ivestigation, it seems I should change JETTY_HOME/etc/jetty-logging.xml, but this does not look straightforward. It looks like I should create a new PrintStream implementation which sends its output to syslog and redirecting stderr and stdout to that class in jetty-logging.xml. any easier way to do that or to make jetty log directly to log4j ? Thanks

    Read the article

  • Single console in eclipse for both Server and Client

    - by rits
    I am building a client server application using Java Sockets (in Windows XP). For that I need different consoles for both Client and Server(for Input and Output operations). But in eclipse both share a single console. Is there any plugin or some sort of cheat through which I can do this. After googling I got this, http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg17138.html But, this seems to be only for write operations, not read operations. Also, I tried the following to launch application manually, but even this is not working........ package mypack; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class MySystem { public static void changeStream(String mainFile) throws IOException{ File temp = new File(".") ; String parentPath = temp.getCanonicalPath() ; System.out.println(parentPath); //creation of batch file starts here try{ File f = new File(parentPath + "\\a.bat") ; System.out.println("Created : " + f.createNewFile()); //f.deleteOnExit() ; FileOutputStream fos = new FileOutputStream(f) ; String str = "java " + mainFile ; String batchCommand="@echo off\n"+str+"\npause\nexit"; char arr[] = batchCommand.toCharArray() ; System.out.println(str) ; for(int i = 0 ; i < arr.length ; i++){ fos.write(arr[i]) ; } fos.close() ; } catch(Exception e){ } //creation of batch file ends here //execution of batch file starts here try{ Runtime r = Runtime.getRuntime() ; System.out.println(parentPath + "\\a.bat") ; Process p = r.exec(new String[]{"cmd","/k","start a.bat"},null,new File(parentPath)) ; OutputStream os = (OutputStream)p.getOutputStream() ; System.setOut( new PrintStream(os) ) ; System.out.println("Hello"); } catch(Exception e){ e.printStackTrace(); } //execution of batch file ends here } public static void main(String[] args) throws IOException { MySystem.changeStream("MySystem") ; } }

    Read the article

  • how to configure jetty 7 to use syslog or log4j

    - by egemen ozden
    I am looking for a way to direct all the jetty 7 logging to syslog. My current configuration dumps everything to JETTY_HOME/logs/.. After some initial ivestigation, it seems I should change JETTY_HOME/etc/jetty-logging.xml, but this does not look straightforward. It looks like I should create a new PrintStream implementation which sends its output to syslog and redirecting stderr and stdout to that class in jetty-logging.xml. any easier way to do that or to make jetty log directly to log4j ? Thanks

    Read the article

  • easiest and best way to make a server queue java

    - by houlahan
    i have a server at the moment which makes a new thread for every user connected but after about 6 people are on the server for more than 15 mins it tends to flop and give me java heap out of memory error i have 1 thread that checks with a mysql database every 30 seconds to see if any of the users currently logged on have any new messages. what would be the easiest way to implement a server queue? this is the my main method for my server: public class Server { public static int MaxUsers = 1000; //public static PrintStream[] sessions = new PrintStream[MaxUsers]; public static ObjectOutputStream[] sessions = new ObjectOutputStream[MaxUsers]; public static ObjectInputStream[] ois = new ObjectInputStream[MaxUsers]; private static int port = 6283; public static Connection conn; static Toolkit toolkit; static Timer timer; public static void main(String[] args) { try { conn = (Connection) Mysql.getConnection(); } catch (Exception ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("****************************************************"); System.out.println("* *"); System.out.println("* Cloud Server *"); System.out.println("* ©2010 *"); System.out.println("* *"); System.out.println("* Luke Houlahan *"); System.out.println("* *"); System.out.println("* Server Online *"); System.out.println("* Listening On Port " + port + " *"); System.out.println("* *"); System.out.println("****************************************************"); System.out.println(""); mailChecker(); try { int i; ServerSocket s = new ServerSocket(port); for (i = 0; i < MaxUsers; ++i) { sessions[i] = null; } while (true) { try { Socket incoming = s.accept(); boolean found = false; int numusers = 0; int usernum = -1; synchronized (sessions) { for (i = 0; i < MaxUsers; ++i) { if (sessions[i] == null) { if (!found) { sessions[i] = new ObjectOutputStream(incoming.getOutputStream()); ois[i]= new ObjectInputStream(incoming.getInputStream()); new SocketHandler(incoming, i).start(); found = true; usernum = i; } } else { numusers++; } } if (!found) { ObjectOutputStream temp = new ObjectOutputStream(incoming.getOutputStream()); Person tempperson = new Person(); tempperson.setFlagField(100); temp.writeObject(tempperson); temp.flush(); temp = null; tempperson = null; incoming.close(); } else { } } } catch (IOException ex) { System.out.println(1); Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } } catch (IOException ex) { System.out.println(2); Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public static void mailChecker() { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new mailCheck(), 0, 10 * 1000); } }

    Read the article

  • Coupling/Cohesion

    - by user559142
    Hi All, Whilst there are many good examples on this forum that contain examples of coupling and cohesion, I am struggling to apply it to my code fully. I can identify parts in my code that may need changing. Would any Java experts be able to take a look at my code and explain to me what aspects are good and bad. I don't mind changing it myself at all. It's just that many people seem to disagree with each other and I'm finding it hard to actually understand what principles to follow... package familytree; /** * * @author David */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here KeyboardInput in = new KeyboardInput(); FamilyTree familyTree = new FamilyTree(in, System.out); familyTree.start(); } } package familytree; import java.io.PrintStream; /** * * @author David */ public class FamilyTree { /** * @param args the command line arguments */ private static final int DISPLAY_FAMILY_MEMBERS = 1; private static final int ADD_FAMILY_MEMBER = 2; private static final int REMOVE_FAMILY_MEMBER = 3; private static final int EDIT_FAMILY_MEMBER = 4; private static final int SAVE_FAMILY_TREE = 5; private static final int LOAD_FAMILY_TREE = 6; private static final int DISPLAY_ANCESTORS = 7; private static final int DISPLAY_DESCENDANTS = 8; private static final int QUIT = 9; private KeyboardInput in; private Family family; private PrintStream out; public FamilyTree(KeyboardInput in, PrintStream out) { this.in = in; this.out = out; family = new Family(); } public void start() { out.println("\nWelcome to the Family Tree Builder"); //enterUserDetails(); initialise(); while (true) { displayFamilyTreeMenu(); out.print("\nEnter Choice: "); int option = in.readInteger(); if (option > 0 && option <= 8) { if (quit(option)) { break; } executeOption(option); } else { out.println("Invalid Choice!"); } } } //good private void displayFamilyTreeMenu() { out.println("\nFamily Tree Menu"); out.println(DISPLAY_FAMILY_MEMBERS + ". Display Family Members"); out.println(ADD_FAMILY_MEMBER + ". Add Family Member"); out.println(REMOVE_FAMILY_MEMBER + ". Remove Family Member"); out.println(EDIT_FAMILY_MEMBER + ". Edit Family Member"); out.println(SAVE_FAMILY_TREE + ". Save Family Tree"); out.println(LOAD_FAMILY_TREE + ". Load Family Tree"); out.println(DISPLAY_ANCESTORS + ". Display Ancestors"); out.println(DISPLAY_DESCENDANTS + ". Display Descendants"); out.println(QUIT + ". Quit"); } //good private boolean quit(int opt) { return (opt == QUIT) ? true : false; } //good private void executeOption(int choice) { switch (choice) { case DISPLAY_FAMILY_MEMBERS: displayFamilyMembers(); break; case ADD_FAMILY_MEMBER: addFamilyMember(); break; case REMOVE_FAMILY_MEMBER: break; case EDIT_FAMILY_MEMBER: break; case SAVE_FAMILY_TREE: break; case LOAD_FAMILY_TREE: break; case DISPLAY_ANCESTORS: displayAncestors(); break; case DISPLAY_DESCENDANTS: displayDescendants(); break; default: out.println("Not a valid option! Try again."); break; } } //for selecting family member for editing adding nodes etc private void displayFamilyMembers() { out.println("\nDisplay Family Members"); int count = 0; for (FamilyMember member : family.getFamilyMembers()) { out.println(); if (count + 1 < 10) { out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName()); out.println(" " + member.getDob()); out.println(" Generation: " + member.getGeneration()); } else { out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName()); out.println(" " + member.getDob()); out.println(" Generation: " + member.getGeneration()); } count++; } } private int selectRelative() { out.println("\nSelect Relative"); out.println("1. Add Parents"); out.println("2. Add Child"); out.println("3. Add Partner"); out.println("4. Add Sibling"); out.print("\nEnter Choice: "); int choice = in.readInteger(); if (choice > 0 && choice < 5) { return choice; } return (-1); } private void addFamilyMember() { int memberIndex = selectMember(); if (memberIndex >= 0) { FamilyMember member = family.getFamilyMember(memberIndex); int relative = selectRelative(); if (relative > 0) { out.println("\nAdd Member"); //if choice is valid switch (relative) { case 1: //adding parents if (member.getFather() == null) { FamilyMember mum, dad; out.println("Enter Mothers Details"); mum = addMember(relative, "Female"); out.println("\nEnter Fathers Details"); dad = addMember(relative, "Male"); member.linkParent(mum); member.linkParent(dad); mum.linkPartner(dad); mum.setGeneration(member.getGeneration() - 1); dad.setGeneration(member.getGeneration() - 1); sortGenerations(); } else { out.println(member.getFirstName() + " " + member.getLastName() + " already has parents."); } break; case 2: //adding child if (member.getPartner() == null) { FamilyMember partner; if (member.getGender().equals("Male")) { out.println("Enter Mothers Details"); partner = addMember(1, "Female"); } else { out.println("Enter Fathers Details"); partner = addMember(1, "Male"); } //create partner member.linkPartner(partner); partner.setGeneration(member.getGeneration()); out.println(); } out.println("Enter Childs Details"); FamilyMember child = addMember(relative, ""); child.linkParent(member); child.linkParent(member.getPartner()); child.setGeneration(member.getGeneration() + 1); sortGenerations(); break; case 3: //adding partner if (member.getPartner() == null) { out.println("Enter Partners Details"); FamilyMember partner = addMember(relative, ""); member.linkPartner(partner); partner.setGeneration(member.getGeneration()); } else { out.println(member.getFirstName() + " " + member.getLastName() + " already has a partner."); } break; case 4: //adding sibling FamilyMember mum, dad; if (member.getFather() == null) { out.println("Enter Mothers Details"); mum = addMember(1, "Female"); out.println("\nEnter Fathers Details"); dad = addMember(1, "Male"); member.linkParent(mum); member.linkParent(dad); mum.linkPartner(dad); mum.setGeneration(member.getGeneration() - 1); dad.setGeneration(member.getGeneration() - 1); sortGenerations(); out.println("\nEnter Siblings Details"); } else { out.println("Enter Siblings Details"); } FamilyMember sibling = addMember(relative, ""); //create mum and dad mum = member.getMother(); dad = member.getFather(); sibling.linkParent(mum); sibling.linkParent(dad); sibling.setGeneration(member.getGeneration()); break; } } else { out.println("Invalid Option!"); } } else { out.println("Invalid Option!"); } } private int selectMember() { displayFamilyMembers(); out.print("\nSelect Member: "); int choice = in.readInteger(); if (choice > 0 && choice <= family.getFamilyMembers().size()) { return (choice - 1); } return -1; } private FamilyMember addMember(int option, String gender) { out.print("Enter First Name: "); String fName = formatString(in.readString().trim()); out.print("Enter Last Name: "); String lName = formatString(in.readString().trim()); if (option != 1) { //if not adding parents out.println("Select Gender"); out.println("1. Male"); out.println("2. Female"); out.print("Enter Choice: "); int gOpt = in.readInteger(); if (gOpt == 1) { gender = "Male"; } else if (gOpt == 2) { gender = "Female"; } else { out.println("Invalid Choice"); return null; } } String dob = enterDateOfBirth(); lName = formatString(lName); FamilyMember f = family.getFamilyMember(family.addMember(fName, lName, gender, dob)); f.setIndex(family.getFamilyMembers().size() - 1); return (f); } private String formatString(String s){ String firstLetter = s.substring(0, 1); String remainingLetters = s.substring(1, s.length()); s = firstLetter.toUpperCase() + remainingLetters.toLowerCase(); return s; } private String enterDateOfBirth(){ out.print("Enter Year Of Birth (0 - 2011): "); String y = in.readString(); out.print("Enter Month Of Birth (1-12): "); String m = in.readString(); if (Integer.parseInt(m) < 10) { m = "0" + m; } m += "-"; out.print("Enter Date of Birth (1-31): "); String d = in.readString(); if (Integer.parseInt(d) < 10) { d = "0" + d; } d += "-"; String dob = d + m + y; while(!DateValidator.isValid(dob)){ out.println("Invalid Date. Try Again:"); dob = enterDateOfBirth(); } return (dob); } private void displayAncestors() { out.print("\nDisplay Ancestors For Which Member: "); int choice = selectMember(); if (choice >= 0) { FamilyMember node = family.getFamilyMember(choice ); FamilyMember ms = findRootNode(node, 0, 2, -1); FamilyMember fs = findRootNode(node, 1, 2, -1); out.println("\nPrint Ancestors"); out.println("\nMothers Side"); printDescendants(ms, node, ms.getGeneration()); out.println("\nFathers Side"); printDescendants(fs, node, fs.getGeneration()); } else { out.println("Invalid Option!"); } } private void displayDescendants() { out.print("\nDisplay Descendants For Which Member: "); int choice = selectMember(); if (choice >= 0) { FamilyMember node = family.getFamilyMember(choice); out.println("\nPrint Descendants"); printDescendants(node, null, 0); } else { out.println("Invalid Option!"); } } private FamilyMember findRootNode(FamilyMember node, int parent, int numGenerations, int count) { FamilyMember root; count++; if (node.hasParents() && count < numGenerations) { if (parent == 0) { node = node.getMother(); root = findRootNode(node, 1, numGenerations, count); } else { node = node.getFather(); root = findRootNode(node, 1, numGenerations, count); } return root; } return node; } private int findHighestLeafGeneration(FamilyMember node) { int gen = node.getGeneration(); for (int i = 0; i < node.getChildren().size(); i++) { int highestChild = findHighestLeafGeneration(node.getChild(i)); if (highestChild > gen) { gen = highestChild; } } return gen; } private void printDescendants(FamilyMember root, FamilyMember node, int gen) { out.print((root.getGeneration() + 1) + " " + root.getFullName()); out.print(" [" + root.getDob() + "] "); if (root.getPartner() != null) { out.print("+Partner: " + root.getPartner().getFullName() + " [" + root.getPartner().getDob() + "] "); } if (root == node) { out.print("*"); } out.println(); if (!root.getChildren().isEmpty() && root != node) { for (int i = 0; i < root.getChildren().size(); i++) { for (int j = 0; j < root.getChild(i).getGeneration() - gen; j++) { out.print(" "); } printDescendants(root.getChild(i), node, gen); } } else { return; } } //retrieve highest generation public int getRootGeneration(){ int min = family.getFamilyMember(0).getGeneration(); for(int i = 0; i < family.getFamilyMembers().size(); i++){ min = Math.min(min, family.getFamilyMember(i).getGeneration()); } return Math.abs(min); } public void sortGenerations(){ int amount = getRootGeneration(); for (FamilyMember member : family.getFamilyMembers()) { member.setGeneration(member.getGeneration() + amount); } } //test method - temporary private void initialise() { family.addMember("Bilbo", "Baggins", "Male", "23-06-1920"); } } package familytree; import java.util.ArrayList; import java.util.Date; /** * * @author David */ public class Family { //family members private ArrayList<FamilyMember> family; //create Family public Family() { family = new ArrayList<FamilyMember>(); } //add member to the family public int addMember(String f, String l, String g, String d) { family.add(new FamilyMember(f, l, g, d)); return family.size()-1; } //remove member from family public void removeMember(int index) { family.remove(index); } public FamilyMember getFamilyMember(int index) { return family.get(index); } //return family public ArrayList <FamilyMember> getFamilyMembers() { return family; } public void changeFirstName(int index, String f) { family.get(index).setFirstName(f);//change to setfirstname and others } public void changeLastName(int index, String l) { family.get(index).setLastName(l); } public void changeAge(int index, int a) { family.get(index).setAge(a); } public void changeDOB() { //implement } } package familytree; import java.util.ArrayList; import java.util.Collections; /** * * @author David */ public class FamilyMember extends Person { private FamilyMember mother; private FamilyMember father; private FamilyMember partner; private ArrayList<FamilyMember> children; private int generation; private int index; //initialise family member public FamilyMember(String f, String l, String g, String d) { super(f, l, g, d); mother = null; father = null; partner = null; children = new ArrayList<FamilyMember>(); generation = 0; index = -1; } public void linkParent(FamilyMember parent) { if (parent.getGender().equals("Female")) { this.setMother(parent); } else { this.setFather(parent); } parent.addChild(this); } public void linkPartner(FamilyMember partner) { partner.setPartner(this); this.setPartner(partner); } public boolean hasParents() { if (this.getMother() == null && this.getFather() == null) { return false; } return true; } public FamilyMember getMother() { return mother; } public FamilyMember getFather() { return father; } public FamilyMember getPartner() { return partner; } public FamilyMember getChild(int index) { return children.get(index); } public int getGeneration() { return generation; } public int getIndex() { return index; } public ArrayList<FamilyMember> getChildren() { return children; } public void setMother(FamilyMember f) { mother = f; } public void setFather(FamilyMember f) { father = f; } public void setPartner(FamilyMember f) { partner = f; } public void addChild(FamilyMember f) { children.add(f); //add child if(children.size() > 1){ //sort in ascending order Collections.sort(children, new DateComparator()); } } public void addChildAt(FamilyMember f, int index) { children.set(index, f); } public void setGeneration(int g) { generation = g; } public void setIndex(int i){ index = i; } } package familytree; /** * * @author David */ public class Person{ private String fName; private String lName; private String gender; private int age; private String dob; public Person(String fName, String lName, String gender, String dob){ this.fName = fName; this.lName = lName; this.gender = gender; this.dob = dob; } public String getFullName(){ return (this.fName + " " + this.lName); } public String getFirstName(){ return (fName); } public String getLastName(){ return (lName); } public String getGender(){ return (gender); } public String getDob(){ return dob; } public int getAge(){ return age; } public void setFirstName(String fName){ this.fName = fName; } public void setLastName(String lName){ this.lName = lName; } public void setGender(String gender){ this.gender = gender; } public void setAge(int age){ this.age = age; } }

    Read the article

1 2  | Next Page >