PLEASE HELP!!!! simple java program...

Hi there,
im seeking HEP!!!! from any one who could solve my problem. i have a program to be written that consists of gym members details and prints tem out to the screen.
A program is to be written to store Gym registration details. A Gym member record consists of membership number, name, postcode and fee.
Write a class definition to represent such Gym membership details.
Write a main method that declares and initialises two new Gym membership objects.
Write a method to request data items from the user to fill both the new Gym member objects.
Write a method to display to the screen the names and membership numbers of both members.
Example data entry ( ?Z123456?, ?Paul Jones?, ?HN78HG?, 250);
thanks ...

public class Gym
    //set the membership number of a member as String
    private void setMembershipNumber(String number)
        membershipNumber = number;
    //sets the name of the member as String
    private void setMemberName(String name)
        memberName = name;
    //sets the post code as String
    private void setPostCode(String postCode)
        memberPostCode = postCode;
    //sets the fee as String
    private void setFee(String fee)
        gymFee = fee;
    //return methods here
    private String getMemberNumber( )
        return membershipNumber;
    private String getMemberName( )
        return memberName;
    private String getPostCode( )
        return memberPostCode;
    private String getFee( )
        return gymFee;
    /* A method displayOutput,just in case the user wants to use all the
     *return methods in just one call
    public void displayOutput( )
        System.out.println("Number: " + getMemberNumber( ) + "\n" +
                          ("Name: " + getMemberName( ) + "\n" +
                          ("Post Code: " + getPostCode( ) + "\n" +
                          ("Fee: " + getFee( )))));
/*Main  program
public class GymMembers
    public static void main(String[] args)
      Gym gymMembership1 = new Gym("129983", "Parvez", "1490", "50.00");
      Gym gymMembership2 = new Gym("324512", "Middlesex", "00013", "40.00");
      gymMembership1.displayOutput( );
      System.out.println("\n");
      gymMembership2.displayOutput( );
      System.exit(0);
}and ther error im getting from the compiler is..........
C:\Documents and Settings\user\My Documents\Gym.java:91: inner classes cannot have static declarations
public static void main(String[] args)
^
1 error
Tool completed with exit code 1

Similar Messages

  • *****Please Help Simple Java Corba Problem*****

    This is probably a really simple one but I am very cheased off about it.
    I run my applications on a Win XP pro OS, and when I go to type in nameserv it gives me the following error I hava downloaded and installed JDK 1.4.1. I also have the JRE, And jbuilder personal edition ver 8.....And J2RE 1.4.1
    C:\Documents and Settings\Ash>nameserv
    Exception in thread "main" java.lang.NoClassDefFoundError: java/util/HashSet
    at com.inprise.vbroker.orb.ORB.<init>(ORB.java:81)
    at org.omg.CORBA.ORB.create_impl(ORB.java)
    at org.omg.CORBA.ORB.init(ORB.java)
    at com.inprise.vbroker.naming.ExtFactory.main(ExtFactory.java:126)
    my classpath looks like this
    .;C:\VisualCafePDETrial\BIN\COMPONENTS\SYMBEANS.JAR;C:\VisualCafePDETrial\JAVA\LIB\CLASSES.ZIP;C:\VisualCafePDETrial\JAVA\LIB;C:\BES\bin;C:\j2sdk1.4.1\lib\tools.jar;.;
    and my path is
    C:\VisualCafePDETrial\BIN;C:\VisualCafePDETrial\JAVA\BIN;C:\BES\binC:\j2sdk1.4.1\lib\tools.jar;.;
    what on earth am I doing wrong ??
    Also when I goto compile any java program it comes up with the following
    C:\DOCprac\Prac5\bank_naming>vbmake
    Building the bank_agent example ...
    Exception in thread "main" java.lang.ClassCastException
    at com.visigenic.vbroker.tools.idl2java.main(idl2java.java:30)
    Symantec Java! JustInTime Compiler Version 3.00.021(i) for JDK 1.1.x (TRIAL VER)
    Copyright (C) 1996-98 Symantec Corporation
    compiling: Client.java
    Client.java:2: Package org.omg.CORBA not found in import.
    import org.omg.CORBA.*;
    ^
    Client.java:3: Package org.omg.CosNaming not found in import.
    import org.omg.CosNaming.*;
    ^
    2 errors
    Symantec Java! JustInTime Compiler Version 3.00.021(i) for JDK 1.1.x (TRIAL VER)
    Please help I am really desperate to sort this one out. Can you give me some detailed info on how I would do this.>>>Thanx in advance

    You have 2 sets of errors, at least.
    The first is : Exception in thread "main" java.lang.NoClassDefFoundError: java/util/HashSet which is that you have not imported the class for hashset.
    The second is that the import of the jars is probably wrong, hard to say without seeing code.

  • Please help with Java program

    Errors driving me crazy! although compiles fine
    I am working on a project for an online class - I am teaching myself really! My last assignment I cannot get to work. I had a friend who "knows" what he is doing help me. Well that didn't work out too well, my class is a beginner and he put stuff in that I never used yet. I am using Jgrasp and Eclipse. I really am trying but, there really is no teacher with this online class. I can't get questions answered in time and stuff goes past due. I am getting this error:
    Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader .java:55)
    at java.util.Scanner.<init>(Scanner.java:590)
    at ttest.main(ttest.java:54)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    This is my code:
    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    The assignment is:
    Create a Java program to read in an unknown number of lines from a data file. You will need to create the data file. The contents of the file can be found at the bottom of this document. This file contains a football team's name, the number of games they have won, and the number of games they have lost.
    Your program should accomplish the following tasks:
    1. Process all data until it reaches the end-of-file. Calculate the win percentage for each team.
    2. Output to a file ("top.txt") a listing of all teams with a win percentage greater than .500. This file should contain the team name and the win percentage.
    3. Output to a file ("bottom.txt") a listing of all teams with a win percentage of .500 or lower. This file should contain the team name and the win percentage.
    4. Count and print to the screen the number of teams with a record greater then .500 and the number of teams with a record of .500 and below, each appropriately labeled.
    5. Output in a message box: the team with the highest win percentage and the team with the lowest win percentage, each appropriately labeled. If there is a tie for the highest win percentage or a tie for the lowest win percentage, you must output all of the teams.
    Dallas 5 2
    Philadelphia 4 3
    Washington 3 4
    NY_Giants 3 4
    Minnesota 6 1
    Green_Bay 3 4

    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    }

  • Problem while executing simple java program

    Hi
    while trying to execute a simple java program,i am getting the following exception...
    please help me in this
    java program :import java.util.*;
    import java.util.logging.*;
    public class Jump implements Runnable{
        Hashtable activeQueues = new Hashtable();
        String dbURL, dbuser, dbpasswd, loggerDir;   
        int idleSleep;
        static Logger logger = Logger.getAnonymousLogger();      
        Thread myThread = null;
        JumpQueueManager manager = null;
        private final static String VERSION = "2.92";
          public Jump(String jdbcURL, String user, String pwd, int idleSleep, String logDir) {
            dbURL = jdbcURL;
            dbuser = user;
            dbpasswd = pwd;
            this.idleSleep = idleSleep;
            manager = new JumpQueueManager(dbURL, dbuser, dbpasswd);
            loggerDir = logDir;
            //preparing logger
            prepareLogger();
          private void prepareLogger(){      
            Handler hndl = new pl.com.sony.utils.SimpleLoggerHandler();
            try{
                String logFilePattern = loggerDir + java.io.File.separator + "jumplog%g.log";
                Handler filehndl = new java.util.logging.FileHandler(logFilePattern, JumpConstants.MAX_LOG_SIZE, JumpConstants.MAX_LOG_FILE_NUM);
                filehndl.setEncoding("UTF-8");
                filehndl.setLevel(Level.INFO);
                logger.addHandler(filehndl);
            catch(Exception e){
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
            logger.addHandler(hndl);
            logger.setLevel(Level.FINE);
            logger.info("LOGGING FACILITY IS READY !");
          private void processTask(QueueTask task){
            JumpProcessor proc = JumpProcessorGenerator.getProcessor(task);       
            if(proc==null){
                logger.severe("Unknown task type: " + task.getType());           
                return;
            proc.setJumpThread(myThread);
            proc.setLogger(logger);       
            proc.setJumpRef(this);
            task.setProcStart(new java.util.Date());
            setExecution(task, true);       
            new Thread(proc).start();       
         private void processQueue(){       
            //Endles loop for processing tasks from queue       
            QueueTask task = null;
            while(true){
                    try{
                        //null argument means: take first free, no matters which queue
                        do{
                            task = manager.getTask(activeQueues);
                            if(task!=null)
                                processTask(task);               
                        while(task!=null);
                    catch(Exception e){
                        logger.severe(e.getMessage());
                logger.fine("-------->Sleeping for " + idleSleep + " minutes...hzzzzzz (Active queues:"+ activeQueues.size()+")");
                try{
                    if(!myThread.interrupted())
                        myThread.sleep(60*1000*idleSleep);
                catch(InterruptedException e){
                    logger.fine("-------->Wakeing up !!!");
            }//while       
        public void setMyThread(Thread t){
            myThread = t;
        /** This method is only used to start Jump as a separate thread this is
         *usefull to allow jump to access its own thread to sleep wait and synchronize
         *If you just start ProcessQueue from main method it is not possible to
         *use methods like Thread.sleep becouse object is not owner of current thread.
        public void run() {
            processQueue();
        /** This is just another facade to hide database access from another classes*/
        public void updateOraTaskStatus(QueueTask task, boolean success){
            try{         
                manager.updateOraTaskStatus(task, success);
            catch(Exception e){
                logger.severe("Cannot update status of task table for task:" + task.getID() +  "\nReason: " + e.getMessage());       
        /** This is facade to JumpQueueManager method with same name to hide
         *existance of database and SQLExceptions from processor classes
         *Processor class calls this method to execute stored proc and it doesn't
         *take care about any SQL related issues including exceptions
        public void executeStoredProc(String proc) throws Exception{
            try{
                manager.executeStoredProc(proc);
            catch(Exception e){
                //logger.severe("Cannot execute stored procedure:"+ proc + "\nReason: " + e.getMessage());       
                throw e;
         *This method is only to hide QueueManager object from access from JumpProcessors
         *It handles exceptions and datbase connecting/disconnecting and is called from
         *JumpProceesor thread.
        public  void updateTaskStatus(int taskID, int status){       
            try{
                manager.updateTaskStatus(taskID, status);
            catch(Exception e){
                logger.severe("Cannot update status of task: " + taskID + " to " + status + "\nReason: " + e.getMessage());
        public java.sql.Connection getDBConnection(){
            try{
                return manager.getNewConnection();
            catch(Exception e){
                logger.severe("Cannot acquire new database connection: " + e.getMessage());
                return null;
        protected synchronized void setExecution(QueueTask task, boolean active){
            if(active){
                activeQueues.put(new Integer(task.getQueueNum()), JumpConstants.TH_STAT_BUSY);
            else{
                activeQueues.remove(new Integer(task.getQueueNum()));
        public static void main(String[] args){
                 try{
             System.out.println("The length-->"+args.length);
            System.out.println("It's " + new java.util.Date() + " now, have a good time.");
            if(args.length<5){
                System.out.println("More parameters needed:");
                System.out.println("1 - JDBC strign, 2 - DB User, 3 - DB Password, 4 - sleeping time (minutes), 5 - log file dir");
                return;
            Jump jump = new Jump(args[0], args[1], args[2], Integer.parseInt(args[3]), args[4]);
            Thread t1= new Thread(jump);
            jump.setMyThread(t1);      
            t1.start();}
                 catch(Exception e){
                      e.printStackTrace();
    } The exception i am getting is
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe
    Exception in thread "main" ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820] Please help me.....
    Thanks in advance.....sathya

    I am not willing to wade through the code, but this portion makes me conjecture your using an Oracle connect string instead of a class name.
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe

  • Please help find the program

    Please help find the program to block unwanted number, call and SMS, that not all block number ,but  the number on which you want to.

    Which part of "The 5310 is just a java phone that cannot support applications like this." did you not understand?
    If you want to achieve any form of blocking at all, it won't be with that phone. Your operator may be able to help by putting a block in place on their end, though, but I doubt it.
    Was this post helpful? If so, please click on the white "Kudos!" star below. Thank you!

  • Need help connecting java-program to Clarion-software/database

    I have made a simple java-program which monitors control-lines in a computers com-port. Now I need to pass this information to Clarion-based software.
    I am currently writing the changes in to a file from which the clarion software will read the changes, but is there any better way to do this?

    Check out these websites:
    - http://www.softvelocity.com
    - http://en.wikipedia.org/wiki/Clarion_programming_language
    The problems is actually the fact that i don't have access to this clarion-based software or it's APIs etc.
    Message was edited by:
    RDuck

  • A simple Java program to be compiled with ojc and executed with java.exe

    Hi ,
    This thread is relevant to Oracle Java Compiler (file ojc) and jave.exe file.
    I have written a simple java program which consists of two simple simple classes and using the JDev's 10.1.3.2 ojc and java files , i'm trying to execute it after the successful compilation....
    The problem is that trying to run it... the error :
    Exception in thread "main" java.lang.NoClassDefFoundError: EmployeeTest
    appears.
    How can i solve this problem...????
    The program is as follows:
    import java.util.*;
    import corejava.*;
    public class EmployeeTest
    {  public static void main(String[] args)
       {  Employee[] staff = new Employee[3];
          staff[0] = new Employee("Harry Hacker", 35000,
             new Day(1989,10,1));
          staff[1] = new Employee("Carl Cracker", 75000,
             new Day(1987,12,15));
          staff[2] = new Employee("Tony Tester", 38000,
             new Day(1990,3,15));
          int i;
          for (i = 0; i < 3; i++) staff.raiseSalary(5);
    for (i = 0; i < 3; i++) staff[i].print();
    class Employee
    {  public Employee(String n, double s, Day d)
    {  name = n;
    salary = s;
    hireDay = d;
    public void print()
    {  System.out.println(name + "...." + salary + "...."
    + hireYear());
    public void raiseSalary(double byPercent)
    {  salary *= 1 + byPercent / 100;
    public int hireYear()
    {  return hireDay.getYear();
    private String name;
    private double salary;
    private Day hireDay;
    For compilation... i use :
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdev\bin\ojc -classpath D:\E-Book\Java\Sun_Java_Book_I\Corejava EmployeeTest.java
    For execution , i issue the command:
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    NOTE:I tried to use the jdk of Oracle database v.2 but the error :
    Unable to initialize JVM appeared....
    Thanks , a lot
    Simon

    Hi,
    Thanks god....
    I found a solution without using Jdev.....
    C:\oracle_files\Java\Examples>SET CLASSPATH=.;D:\E-Book\Java\Sun_Java_Book_I\Corejava
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\javac EmployeeTest.java
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    What does Ant has to do with this?Sorry, under the Ant tree a classpath label is found....I'm very new to Java and JDev...
    You need to include the jar file that has the Day method in it inside project properties->libraries.I have not .jar file.. just some .java files under the corejava directory.... By the way , I have inserted the corejava directory to the project pressing the button Add Jar/Directory.... , but the problem insists..
    Thanks , a lot
    Simon

  • I did write a simple java program but it is not working please help me.....

    This is the program I wrote LineRect just to draw a line a rectangle etc...... Y it is not working How can i used the same program to run without using applet that is by using awt and swing.........Pls Help me.............
    import java.awt.*;
    import java.io.*;
    public class LineRect
    {public void paint(Graphics g)
         {g.drawLine(10,10, 50,50);
         g.drawRect(10, 60, 40,30);
         g.fillRect(60,10,30,80);
         g.drawRoundRect(10,100,80,50,10,10);
         g.fillRoundRect(20,110,60,30,5,5);
         g.drawLine(100,10,230,140);
         g.drawLine(100,140,230,10);
    <APPLET
    CODE =LineRect.class
    WIDTH=250
    HEIGHT=200>
    </APPLET>

    There are many significant errors here for instance you are using a class file as if it were an applet yet you do not subclass applet. Your code has no init method (if it is to be an applet). Your best bet is to go through the tutorials one step at a time. One thing to consider is to subclass a JPanel and draw on the jpanel overriding the paintComponent method. This can then be added to a JFrame or a JApplet's contentPane and would allow the same graphics in both. But again, please study the tutorials on all of this, otherwise you will be doing hit-or-miss programming, and that is no way to learn.
    Much luck!
    Addendum: Also, if you are just beginning in Java programming, I suggest you start with the basics and not with Swing / AWT / graphics programming. Otherwise you will just end up bruised and disappointed. You have to learn to walk before you can run.
    Edited by: Encephalopathic on Dec 26, 2007 5:09 AM

  • Help with a simple Java program

    I'm making a sort of very simple quiz program with Java. I've got everything working on the input/output side of things, and I'm looking to just fancy everything up a little bit. This program is extremely simple, and is just being run through the Windows command prompt. I was wondering how exactly to go about making it to where the quiz taker was forced to hit the enter key after answering the question and getting feedback. Right now, once the question is answered the next question is immediately asked, and it looks kind of tacky. Thanks in advance for your help.

    Hmm.. thats not quite what I was looking for, I don't think. Here's an example of my program.
    class P1 {
    public static void main(String args[]) {
    boolean Correct;
    char Selection;
    int number;
    Correct = false;
    System.out.println("Welcome to Trivia!\n");
    System.out.println("Who was the first UF to win the Heisman Trophy?\n");
    System.out.print("A) Danny Wuerffel\nB) Steve Spurrier\nC) Emmit Smith\n");
    Selection = UserInput.readChar();
    if(Selection == 'B' | Selection == 'b')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    System.out.println("(\nHit enter for the next question...");
    System.in.readLine();
    Correct = false;
    System.out.println("\nWhat year did UF win the NCAA Football National Championship?\n");
    number = UserInput.readInt();
    if(number == 1996)
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    Correct = false;
    System.out.println("\nWho is the President of the University of Florida?\n");
    System.out.println("A) Bernie Machen\nB) John Lombardi\nC) Stephen C. O'Connell\n");
    Selection = UserInput.readChar();
    if(Selection == 'A' | Selection == 'a')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    }

  • Help With Java Program Please!

    Greetings,
    I am trying to figure out to write a Java program that will read n lines of text from the keyboard until a blank line is read. And as it read each line, It's suppose to keep track of
    The longest string so far
    The Longest word seen so far
    The line that contains the most words
    The total number of words seen in all lines
    I don't know where to begin. Help me please! Thank you very much.

    Man I have to say that this smells like home work.
    Since you have not asked for a cut paste code I tell you what to do
    1. Write a function which take single string as a parameter and break it down to words and return words as a array or string
    (You can use this)
    you will need several variables to keep track of
    The longest string so far
    The Longest word seen so far
    The line that contains the most words and number of words in that line
    The total number of words seen in all lines
    now read lines in a loop if the length is 0 exit (that is your exis condition right)
    otherwise check the length of input string and update "The longest string so far"
    then break down the words and update "The Longest word seen so far", "The line that contains the most words and number of words in that line" and "The total number of words seen in all lines"
    and when you are exiting display the above values

  • Help with Simple JAVA program

    I'm a complete novice with Java. I want to write a Java program to run on Windows 2000 servers to write a list of certain files in a directory into a *.txt file. I hope to add complexity once I have this basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.

    I'm a complete novice with Java. I want to write a
    Java program to run on Windows 2000 servers to write
    a list of certain files in a directory into a *.txt
    file. I hope to add complexity once I have this
    basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.
    You need to create a method and insert your if statement in there

  • Please help (Simple chat programme)

    I made a simple chat programme.
    It has a server object and it can handle several client.
    It is working properly and can use to chat.
    I have some problems. can you please help me.
    1.What is the best method to read input and outputStreams
    I have used inputStream.readUTF()/outputStream.writeUTF() methods and
    also I have used bufferedReader.readLine()/Printwriter.println() methods.
    I don't know about other methods.So please tell me what is the best and new out of these two.
    And are there any method which is better than these two.
    2.Is there any way to get more details from input and output streams
    Here more details means Fontcolor,Size etc;
    by now I'm adding them in to my output streams and filtering them when rea input stream.
    I'm getting other details(Fontcolor,Size) and add them all to a string.
    that means if client type "hi" my string will be something like this
    "12ff0000hi".
    When read the input stream i make a char[] and take first 2 chars to integer next six to a string and rest
    to another string.
    I think now you can understand my concept. So I'll not tell every thing.(if you want i can fully describe it)
    I' feeling this is very bad way to do that kind of work.
    Am i correct?
    so can you give me some hints or examples to do such kind of things.

    Here's a simple DataInputStream program that talks to itself. It runs the server as a seperate thread.
    import java.io.*;
    import java.net.*;
    public class DataXfer
            private int port = 5050;
            private String address="127.0.0.1";
            public static void main(String args[])
                    new DataXfer().startup();
            // run the server code as a thread and then run the client code
            private void startup()
                    new Thread(new Runnable(){public void run(){listen();}}).start(); // start server thread
                    synchronized(this){
                            try{wait();}catch(InterruptedException ie){}    // wait until its ready
                    connect();                                      // do client stuff     
            private void listen()
                    ServerSocket ss = null;
                    Socket us = null;
                    boolean running = true;
                    try{
                            System.out.println("Listening on port "+port);
                            synchronized(this){notify();}               // tell client we're ready
                            ss = new ServerSocket(port);    // listen for incoming connection
                            us = ss.accept();
                            ss.close();
                            ss = null;
                            DataInputStream dis = new DataInputStream(us.getInputStream());
                            try{
                                    while(running){
                                            int len = dis.readShort();      // read the count
                                            byte [] ba = new byte[len];
                                            int rlen = dis.read(ba,0,len);  // read the data
                                            System.out.println("len="+len+" read length="+rlen);
                                            if(rlen < len){
                                                    us.close();
                                                    running = false;
                                            else{
                                                    for(int j = 0; j<rlen; j++)System.out.print(ba[j]+" ");
                                                    System.out.println("");
                            catch(EOFException ee){System.out.println("EOF");}
                    catch(IOException ie){
                            ie.printStackTrace();
                            System.exit(0);
                    finally{
                            if(ss != null)try{ss.close();}catch(IOException se){}
                            if(us != null)try{us.close();}catch(IOException ue){}
            private void connect()
                    Socket us=null;
                    byte [] ba = new byte[31];
                    for(byte i = 0; i<ba.length; i++)ba=i;
    try{
    System.out.println("Connecting to "+address+":"+port);
    us = new Socket(address, port); // make connection
    System.out.println("Connected");
    DataOutputStream dos = new DataOutputStream(us.getOutputStream());
    for(int j = 0; j<ba.length;j+=10){
    dos.writeShort(j); // write the count
    dos.write(ba,0,j); // write the data
    System.out.println("sent "+j+" bytes");
    try{Thread.sleep(1000);}catch(InterruptedException ie){}
    catch(IOException ie){ie.printStackTrace();}
    finally{
    if(us != null)try{us.close();}catch(IOException ue){}
    For an example of a chat program using NIO see my NIO Server Example. That example is neither short nor simple.

  • Please help with my program

    I'm a newbie, i wrote a simple dictanary program, but i can't make it run properly. there are no errors but there is a problem...
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.regex.*;
    public class Dictionary{
    public static void main(String args[]){
    DicWin dic = new DicWin("Dictionary");
    class DicWin extends Frame implements ActionListener{
    Panel[] panels = new Panel[2];
    private static String REGEX = "^";
    Button ok;
    TextField text;
    String[] words;
    TextArea textF;
    public DicWin(String title){
         super(title);
         ReadDic("Mueller24.txt");
         setLayout(new GridLayout(2,1));
         panels[0] = new Panel();
         panels[1] = new Panel();
         First(panels[0]);
         Second(panels[1]);
         add(panels[0]);
         add(panels[1]);
         pack();
         setVisible(true);
    public void First(Container con){
         ok = new Button("OK");
         text = new TextField(20);
         con.add(ok);
         ok.addActionListener(this);
         con.add(text);
    public void Second(Container con){
         textF = new TextArea(5,20);
         con.add(textF);
    public void actionPerformed(ActionEvent e)
    String text2 = text.getText();
    Pattern p = Pattern.compile(REGEX + text2);
    for(int j=0;j<words.length;j++){
    Matcher m = p.matcher(words[j]);
    if(m.find())
         textF.setText(textF.getText() + "\n" + words[j]);
    private void ReadDic (String FileName){
    String line;
    int i=0;
    BufferedReader in = null;
    try{
    in = new BufferedReader(new FileReader("Mueller24.txt"));
         while((line = in.readLine())!=null)
         i++;
         words = new String;
         i=0;
         while((line = in.readLine())!=null)
         words[i]=line;
         i++;
    catch(IOException e){
    System.out.println("Error Loading the file.");

    Please make the ReadDic() method as following.
    private void ReadDic(String FileName) {
    String line;
    int i = 0;
    BufferedReader in = null;
    try {
    in = new BufferedReader(new FileReader("Mueller24.txt"));
    while ((line = in.readLine()) != null) {
    i++;
    words = new String[10];
    i = 0;
    while ((line = in.readLine()) != null) {
    words[i] = line;
    i++;
    } catch (IOException e) {
    System.out.println("Error Loading the file.");
    Please notice the line
    words = new String;
    in your original program should be something like following,
    words = new String[10]
    and the line,
    words = line;
    should be
    words[i] = line;
    I hope this would help.
    Pramoda

  • Please help me this program

    Please help me with this program,the progarm should operates as follows
    1)Calculate the number of words
    2)Calculate the number of sentences
    3)Calculate the repeated words
    * Title: <p>
    * Description: <p>
    * Copyright: Copyright (c) cds<p>
    * Company: s<p>
    * @author cds
    * @version 1.0
    package count;
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.border.*;
    import java.util.StringTokenizer;
    public class Frame1 extends JFrame {
    JPanel jPanel1 = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    XYLayout xYLayout2 = new XYLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JTextArea jta1 = new JTextArea();
    JScrollPane jScrollPane2 = new JScrollPane();
    JTextArea jta2 = new JTextArea();
    JLabel jLabel1 = new JLabel();
    JLabel jLabel2 = new JLabel();
    JButton jbtCountSentances = new JButton();
    JButton jbtCountWords = new JButton();
    JButton jbtRWords = new JButton();
    JButton jbtClearList = new JButton();
    JTextField jtfNumOfSentances = new JTextField();
    JLabel jLabel3 = new JLabel();
    JLabel jLabel4 = new JLabel();
    JTextField jtfNumOfWords = new JTextField();
    private JFileChooser jFileChooser = new JFileChooser();
    public static String sentence,RepeatedWords,repwords,chr=" ";
         public static int i,words,token,periods,characters,len,long_word,long_sent,stop;
    //Construct the frame
    public Frame1() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    }setSize(600,400);
    show();
    public static void main(String[] args) {
    Frame1 frame1 = new Frame1();
    private void jbInit() throws Exception {
    jPanel1.setLayout(xYLayout1);
    this.getContentPane().setLayout(xYLayout2);
    jLabel1.setForeground(Color.blue);
    jLabel1.setText(" Type your Doc");
    jLabel2.setForeground(Color.blue);
    jLabel2.setText(" Reapeated Words");
    jbtCountSentances.setBackground(Color.white);
    jbtCountSentances.setForeground(Color.blue);
    jbtCountSentances.setText("Count Sentances");
    jbtCountSentances.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtCountSentances_actionPerformed(e);
    jbtCountWords.setBackground(Color.white);
    jbtCountWords.setForeground(Color.blue);
    jbtCountWords.setText("Count Words");
    jbtCountWords.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtCountWords_actionPerformed(e);
    jbtRWords.setBackground(Color.white);
    jbtRWords.setForeground(Color.blue);
    jbtRWords.setText("Reapeted Words");
    jbtRWords.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtRWords_actionPerformed(e);
    jbtClearList.setBackground(Color.white);
    jbtClearList.setForeground(Color.blue);
    jbtClearList.setText("Clear");
    jbtClearList.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtClearList_actionPerformed(e);
    jLabel3.setForeground(Color.blue);
    jLabel3.setText("NumOfSentances");
    jLabel4.setForeground(Color.blue);
    jLabel4.setText("NumOfWords");
    jPanel1.setBackground(SystemColor.activeCaption);
    jPanel1.setForeground(SystemColor.activeCaption);
    this.getContentPane().add(jPanel1, new XYConstraints(4, 4, 986, 469));
    jPanel1.add(jScrollPane1, new XYConstraints(5, 105, 289, 192));
    jScrollPane1.getViewport().add(jta1, null);
    jPanel1.add(jScrollPane2, new XYConstraints(309, 102, 256, 193));
    jScrollPane2.getViewport().add(jta2, null);
    jPanel1.add(jLabel1, new XYConstraints(21, 81, 240, 22));
    jPanel1.add(jLabel2, new XYConstraints(340, 78, 191, 20));
    jPanel1.add(jbtCountSentances, new XYConstraints(69, 309, 190, 30));
    jPanel1.add(jbtCountWords, new XYConstraints(69, 339, 190, 24));
    jPanel1.add(jbtClearList, new XYConstraints(262, 337, 173, 26));
    jPanel1.add(jbtRWords, new XYConstraints(262, 310, 174, 24));
    jPanel1.add(jLabel3, new XYConstraints(14, 37, 105, 20));
    jPanel1.add(jtfNumOfSentances, new XYConstraints(114, 37, 64, 23));
    jPanel1.add(jLabel4, new XYConstraints(212, 38, 82, 23));
    jPanel1.add(jtfNumOfWords, new XYConstraints(304, 35, 83, 27));
    void jbtCountSentances_actionPerformed(ActionEvent e) {
    BufferedReader stdin = new BufferedReader
                   (new InputStreamReader (System.in));
    sentence = jta1.getText();
              System.out.flush ();
              len=sentence.length();
    jtfNumOfSentances.setText(String.valueOf(num_periods()));
    public static int num_periods () {
              i=0;
              periods=3;
              chr= ".";
    chr= "!";
    chr= "?";
              while (i<len){
                   if (sentence.charAt(i)==chr.charAt(0))
                        periods++;
                   i++;
         return periods;
         }//Method num_words
    void jbtCountWords_actionPerformed(ActionEvent e) {
    String s = jta1.getText();
    StringTokenizer st = new StringTokenizer(s);
    jtfNumOfWords.setText(String.valueOf(st.countTokens()));
    void jbtRWords_actionPerformed(ActionEvent e) {
    repwords = jta1.getText();
    StringTokenizer st = new StringTokenizer(repwords);
              while (st.hasMoreTokens())
    RepeatedWords = st.nextToken(st.toString()) ;
         jta2.append(RepeatedWords);
         //}//Method num_words
    /*void jbtClearList_actionPerformed(ActionEvent e) {
    jta2.setText(null);
    void jbtHelp_actionPerformed(ActionEvent e) {
    jta1.append("Please open a File Write a document");
    // JScrollPane jScrollPane1 = new JScrollPane();
    //JTextArea jta1 = new JTextArea();
    // JScrollPane jScrollPane2 = new JScrollPane();
    //JTextArea jta2 = new JTextArea();
    void jbtClearList_actionPerformed(ActionEvent e) {
    jta2.setText(null);
    jta1.setText(null);
    jtfNumOfWords.setText(null);
    jtfNumOfSentances.setText(null);

    Let me try specify the main problem in details
    The code that i had posted displays an interface consisting of a 2 textarea.
    The first textarea is for a user to enter a sentence and the second is for displaying duplicated words.
    The program should allow the user to enter a sentence on the first textarea and when JButton named showduplicatedwords pressed it must display the words that are being duplicated in the sentence on the second textarea.And again count the number of sentence available when
    JButton countsentence is pressed

  • PLEASE HELP making a program that uses sudo commands

    hey
    is there anyway to make a program run sudo commands
    i have a problem because in a terminal it would ask you to input a password.
    is there a way to use a fake keyboard program to input the password in the back ground
    of my java application or some how run sudo commands? my application relies on some outputs of these commands.
    please help thanks.

    ill tell you a bit about my program im making.
    i have a wireless usb that i have to switch back and forth to get my paticullar drivers to
    do certain things e.g. one is for web browsing and the other one has packet injection.
    by typing sudo modprobe ect.. i can switch through a terminal. which requires me to type in a password.
    iv made a application which uses the
    Runtime.getRuntime().exec("sudo ...."); it has 2 buttons to switch from diffrent drivers and always runs at start up.
    just a big problem i cant use sudo it just freezes when i start and click on the buttons. and doesnt ask me for a password.
    can anyone help thanks

  • Need help in java program execution...

    Hi all
    I have made a java program( JAR file) and I need to execute it from a double click...can you please tell how to do it..For normal execution i have to go to CMD prompt and write a couple of commands but i want to execute it through 1 click..
    The method which i thought was to make a batch(.bat) file and write the commands in it but its not working properly...do you have any other method or software which i can use...
    I am new to java and any help would be appreciated.

    You should avoid using a batch file since there's no explicit reason to do that.
    sachinmittal wrote:
    I have made a java program( JAR file) and I need to execute it from a double click...can you please tell how to do it.There a lot of tutorials out there. I prefer this one:
    [http://java.sun.com/docs/books/tutorial/deployment/jar/index.html]
    You should take look at the manifest section if you want to build an executable jar.

Maybe you are looking for

  • How to call a DLL with a char or a uint8_t

    Good afternoon, I need to pass an array (image) to my dll. I was able to successfully do this using  imageProcess(int **a, ... ){;} function declaration and using a signed or unsigned 32 bit integer as data type in labview DLL call However, when I ch

  • Tweening "y" and connecting movement to score

    Still trying to get a bar/column to move up and down based on a positive or negative total score value. Uisng "scaleY" doesn't scale proportionately for these values. The "absolute "0" point in this scaling is the mean value for the score. I thought

  • XML Project title help??

    Hi all, I'm currently taking a part-time course run by my university in database programming. I'm currently looking into areas for a project and am very interested into incorporating/using xml as my data source. Being quite a newbie to xml, I'm havin

  • After upgrading  my ipad 3 to ios 6 i am unable to access my i tune store from i pad3. please help me

    after upgrading  my ipad 3 to ios 6 i am unable to access my i tune store

  • Find File By Name

    Just upgraded to SL and was disappointed to find the the apple-F dialog box still defaults of find file by content. My gripe is that if you type the word "microsoft" for example, files beginning with this word appear well, and I mean WELL, down the l