HELP!! WHAT'S WRONG WITH MY PROGRAM?

It prints out "Please input next string" twice the first time and I can't figure out why. Here's the code:
import java.util.*;
public class VowelCounter {
     public static void main(String[] args) {
          Scanner read = new Scanner(System.in);
          int elements=0;
          // create string array
          System.out.print("How many strings do you want?");
          try{
               elements = read.nextInt();
          catch (InputMismatchException ime){
               System.err.println("Invalid data type!");
               System.exit(0);
          String[] testArray = new String[elements];
          // populate String array
          for (int i=0;i<testArray.length;i++){
               System.out.println("Please input next string:\n"+i);
               testArray=read.nextLine();
          } // end for
          // test array and print out result
          System.out.println(mostVowels(testArray)+ " has the most vowels.");
     } // end method main
     public static String mostVowels(String[] test){
          // create array to store count
          int[] numVowels = new int[test.length];
          // check all strings in array
          for (int i=0;i<test.length;i++){
               test[i].toLowerCase();
               // check each char in string
               for (int j=0; j<test[i].length();j++){
                    switch (test[i].charAt(j)){
                    case 'a': case 'e':case 'i':case 'o':case 'u':
                         numVowels[i]++;
                         break;
                    } // end switch
               } // end for
          } // end for
          // find string with most vowels
          int most=0;
          for(int i=0;i<numVowels.length-1;i++){
               if (numVowels[i]<numVowels[i+1]){
                    most = i+1;
          }// end for
          return test[most];
} // end class VowelCounter
Thanks a lot!

Hi,
U can do this with BufferedReader.
here is ur code
//It prints out "Please input next string" twice the first time and I can't figure out why. Here's the code:
import java.util.*;
import java.io.*;
public class VowelCounter {
     public static void main(String[] args) {
          BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
          Scanner read = new Scanner(System.in);
          int elements=0;
          // create string array
          System.out.print("How many strings do you want?");
          try{
               //elements = read.nextInt();
               elements = Integer.parseInt(bf.readLine());
          catch (Exception ime){
               System.err.println("Invalid data type!");
               System.exit(0);
          String[] testArray = new String[elements];
          int xyz =0;
          // populate String array
          for (int i=0;i<elements;i++){
               System.out.println(i+". Please input next string:\n");
               try {
                    testArray=bf.readLine();
               }catch(Exception ek){}
          } // end for
          // test array and print out result
          System.out.println(mostVowels(testArray)+ " has the most vowels.");
     } // end method main
     public static String mostVowels(String[] test){
          // create array to store count
          int[] numVowels = new int[test.length];
          // check all strings in array
          for (int i=0;i<test.length;i++){
               test[i].toLowerCase();
               // check each char in string
               for (int j=0; j<test[i].length();j++){
                    switch (test[i].charAt(j)){
                         case 'a': case 'e':case 'i':case 'o':case 'u':
                                                                                     numVowels[i]++;
                                                                                     break;
                    } // end switch
               } // end for
          } // end for
          // find string with most vowels
          int most=0;
          for(int i=0;i<numVowels.length-1;i++){
               if (numVowels[i]<numVowels[i+1]){
                    most = i+1;
          }// end for
          return test[most];
} // end class VowelCounter
Ganesh

Similar Messages

  • What Is Wrong With My Program Help

    This Is The Assignment I Have To Do:
    Write a Java program that prints a table with a list of at least 5 students together with their grades earned (lab points, bonus points, and the total) in the format below.
    == Student Points ==
    Name Lab Bonus Total
    Joe 43 7 50
    William 50 8 58
    Mary Sue 39 10 49
    The requirements for the program are as follows:
    1.     Name the project StudentGrades.
    2.     Print the border on the top as illustrated (using the slash and backslash characters).
    3.     Use tab characters to get your columns aligned and you must use the + operator both for addition and string concatenation.
    4.     Make up your own student names and points -- the ones shown are just for illustration purposes. You need 5 names.
    This Is What I Have So Far:
    * Darron Jones
    * 4th Period
    * ID 2497430
    *I recieved help from the internet and the book
    *StudentGrades
      public class StudentGrades
         public static void main (String[] args )
    System.out.println("///////////////////\\\\\\\\\\\\\\\\\\");
    System.out.println("==          Student Points          ==");
    System.out.println("\\\\\\\\\\\\\\\\\\\///////////////////");
    System.out.println("                                      ");
    System.out.println("Name            Lab     Bonus   Total");
    System.out.println("----            ---     -----   -----");
    System.out.println("Dill             43      7       50");
    System.out.println("Josh             50      8       58");
    System.out.println("Rebbeca          39      10      49");When I Compile It Keeps Having An Error Thats Saying: "Illegal Escape Character" Whats Wrong With The Program Help Please

    This will work exactly as you want it to be....hope u like it
         public static void main(String[] args)
              // TODO Auto-generated method stub
              System.out.print("///////////////////");
              System.out.print("\\\\\\\\\\\\\\\\\\\\\\\\");
              System.out.println("\\\\\\\\\\\\\\");
              System.out.println("== Student Points ==");
              System.out.print("\\\\\\\\\\\\\\");
              System.out.print("\\\\\\\\\\\\");
              System.out.print("\\\\\\\\\\\\");
              System.out.print("///////////////////");
              System.out.println(" ");
              System.out.println("Name Lab Bonus Total");
              System.out.println("---- --- ----- -----");
              System.out.println("Dill 43 7 50");
              System.out.println("Josh 50 8 58");
              System.out.println("Rebbeca 39 10 49");
         }

  • What's wrong with this program?

    /* Daphne invests $100 at 10% simple interest. Deirdre invests $100 at 5% interest compounded annually. Write a program that finds how many years it takes for the value of Deirdre's investment to exceed the value of Daphne's investment. Aso show the two values at that time.*/
    #include <stdio.h>
    #define START 100.00
    int main(void)
    int counter = 1;
    float daphne = START;
    float deirdre = START;
    printf("Daphne invests $100 at 10 percent simple interest. Deirdre invests $100 at 5 percent interest compounded annually.
    When will Deirdre's account value exceed Daphne's?
    Let\'s find out.
    while (daphne > deirdre)
    daphne += 10.00;
    deirdre *= 1.05;
    printf("%f %f
    ", daphne, deirdre);
    printf("At year %d, Daphne has %.2f dollars. Deirdre has %.2f dollars.
    ", counter, daphne, deirdre);
    counter++;
    printf("By the end of year %d, Deirdre's account has surpassed Daphne's in value.
    ", counter);
    return 0;
    This is my output:
    *Daphne invests $100 at 10 percent simple interest. Deirdre invests $100 at 5 percent interest compounded annually.*
    *When will Deirdre's account value exceed Daphne's?*
    *Let's find out.*
    *By the end of year 1, Deirdre's account has surpassed Daphne's in value.*
    What's wrong with it?
    Message was edited by: musicwind95
    Message was edited by: musicwind95

    John hadn't responded at the time I started typing this, but I'll keep it posted anyways in order to expand on John's answer a little bit. The answer to your last question is that the loop's condition has to return true for it to run the first time around. To examine this further, let's take a look at the way you had the while loop before:
    while (daphne > deirdre)
    Now, a while loop will run the code between its braces as long as the condition inside the parenthesis (daphne > deirdre, in this case) is true. So, if the condition is false the first time the code reaches the while statement, then the loop will never run at all (it won't even run through it once -- it will skip over it). And since, before the while loop, both variables (daphne and dierdre) are set equal to the same value (START (100.00), in this case), both variables are equal at the point when the code first reaches the while statement. Since they are equal, daphne is NOT greater than dierdre, and therefore the condition returns false. Since the condition is false the first time the code reaches it, the code inside the loop's braces is skipped over and never run. As John recommended in the previous post, changing it to this:
    while (daphne >= deirdre)
    fixes the problem because now the condition is true. The use of the "greater than or equal to" operator (>=) instead of the "great than" operator (>) means that the condition can now be returned true even if daphne is equal to deirdre, not just if it's greater than deirdre. And since daphne and deirdre are equal (they are both 100.00) when the code first reaches the while loop, the condition is now returned true and the code inside the loop's braces will be run. Once the program reaches the end of the code inside the loop's braces, it will check to see if the condition is still true and, if it is, it will run the loop's code again (and again and again and again, checking to see if the condition is still true each time), and if it's not true, it will skip over the loop's bottom brace and continue on with the rest of the program.
    Hope this helped clear this up for you. Please ask if you have any more questions.

  • What's wrong with my program?

    Mission: A program which returns a digit based on what character you enter, and it should follow this structure:
    Digit to output / Character entered
    2 / ABC
    3 / DEF
    4 / GHI
    5 / JKL
    6 / MNO
    7 / PRS
    8 / TUV
    9 / WXY
    If you enter the letters Q, Z or any nonalphabetic letter, the program should output that an error was encountered. Must have two buttons, one for "Ok" and one for "Quit".
    I made this code so far, which gives me tons of errors I don't get much out of:
    import java.awt.*;
    import java.awt.event.*;
    public class digit
    // Define action listener for alphabetic buttons
    private static class ButtonHandler implements ActionListener
    public void actionPerformed(ActionEvent event)
    char charEntered; // Holds the character entered
    String whichButton; // Button's name
    // Get the right button
    charEntered = inputField.getText();
    whichButton = event.getActionCommand;
    // If-Else procedures, to determine which button is pressed and what action to perform
    if (whichButton.equals("ok"))
    if (charEntered.equals("A"))
    outputLabel.setText("Your digit is 2");
    else if (charEntered == D || E || F)
    outputLabel.setText("Your digit is 3");
    else if (charEntered == G || H || I)
    outputLabel.setText("Your digit is 4");
    else if (charEntered == J || K || L)
    outputLabel.setText("Your digit is 5");
    else if (charEntered == M || N || O)
    outputLabel.setText("Your digit is 6");
    else if (charEntered == P || R || S)
    outputLabel.setText("Your digit is 7");
    else if (charEntered == T || U || V)
    outputLabel.setText("Your digit is 8");
    else if (charEntered == W || X || Y)
    outputLabel.setText("Your digit is 9");
    else outputLabel.setText("An error occured.");
    private static class ButtonHandler2 implements ActionListener
    public void actionPerformed(ActionEvent event)
    dFrame.dispose();
    System.exit(0);
    private static TextField inputField; // Input field
    private static Label outputLabel; // Output Label
    private static Frame dFrame; // Frame
    public static void main(String [] args)
    // Declare alphabetic listener
    ButtonHandler operation;
    ButtonHandler2 quitoperation;
    Label entryLabel; // Label for inputfield
    Label outputLabel_label; // Label for outputfield
    Button ok; // Ok Button
    Button quit; // quit button
    operation = new Buttonhandler();
    quitoperation = new ButtonHandler2();
    // New frame
    dFrame = new Frame();
    dFrame.setLayout(new GridLayout(4,2));
    entryLabel = new Label("Enter letter here");
    outputLabel_label = new Label("The result is");
    outputLabel = new Label("0");
    // Instantiate buttons
    ok = new Button("Ok");
    quit = new Button("Quit");
    // Name the button events
    ok.setActionCommand("ok");
    quit.setActionCommand("quit");
    // Register the button listeners
    ok.addActionListener(operation);
    quit.addActionListener(operation);
    // Add interface to the Frame
    dFrame.add(entryLabel);
    dFrame.add(inputField);
    dFrame.add(outputLabel_label);
    dFrame.add(outputLabel);
    dFrame.add(ok);
    dFrame.add(quit);
    dFrame.pack();
    dFrame.show();
    dFrame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent event)
    dFrame.dispose();
    System.exit(0);
    I get these errors:
    fnatte:~/inda/java/chapter6>javac digit.java
    digit.java:23: incompatible types
    found : java.lang.String
    required: char
    charEntered = inputField.getText();
    ^
    digit.java:24: cannot resolve symbol
    symbol : variable getActionCommand
    location: class java.awt.event.ActionEvent
    whichButton = event.getActionCommand;
    ^
    digit.java:31: char cannot be dereferenced
    if (charEntered.equals("A"))
    ^
    digit.java:33: cannot resolve symbol
    symbol : variable D
    location: class digit.ButtonHandler
    else if (charEntered == D || E || F)
    ^
    digit.java:33: cannot resolve symbol
    symbol : variable E
    location: class digit.ButtonHandler
    else if (charEntered == D || E || F)
    ^
    digit.java:33: cannot resolve symbol
    symbol : variable F
    location: class digit.ButtonHandler
    else if (charEntered == D || E || F)
    ^
    digit.java:35: cannot resolve symbol
    symbol : variable G
    location: class digit.ButtonHandler
    else if (charEntered == G || H || I)
    ^
    digit.java:35: cannot resolve symbol
    symbol : variable H
    location: class digit.ButtonHandler
    else if (charEntered == G || H || I)
    ^
    digit.java:35: cannot resolve symbol
    symbol : variable I
    location: class digit.ButtonHandler
    else if (charEntered == G || H || I)
    ^
    digit.java:37: cannot resolve symbol
    symbol : variable J
    location: class digit.ButtonHandler
    else if (charEntered == J || K || L)
    ^
    digit.java:37: cannot resolve symbol
    symbol : variable K
    location: class digit.ButtonHandler
    else if (charEntered == J || K || L)
    ^
    digit.java:37: cannot resolve symbol
    symbol : variable L
    location: class digit.ButtonHandler
    else if (charEntered == J || K || L)
    ^
    digit.java:39: cannot resolve symbol
    symbol : variable M
    location: class digit.ButtonHandler
    else if (charEntered == M || N || O)
    ^
    digit.java:39: cannot resolve symbol
    symbol : variable N
    location: class digit.ButtonHandler
    else if (charEntered == M || N || O)
    ^
    digit.java:39: cannot resolve symbol
    symbol : variable O
    location: class digit.ButtonHandler
    else if (charEntered == M || N || O)
    ^
    digit.java:41: cannot resolve symbol
    symbol : variable P
    location: class digit.ButtonHandler
    else if (charEntered == P || R || S)
    ^
    digit.java:41: cannot resolve symbol
    symbol : variable R
    location: class digit.ButtonHandler
    else if (charEntered == P || R || S)
    ^
    digit.java:41: cannot resolve symbol
    symbol : variable S
    location: class digit.ButtonHandler
    else if (charEntered == P || R || S)
    ^
    digit.java:43: cannot resolve symbol
    symbol : variable T
    location: class digit.ButtonHandler
    else if (charEntered == T || U || V)
    ^
    digit.java:43: cannot resolve symbol
    symbol : variable U
    location: class digit.ButtonHandler
    else if (charEntered == T || U || V)
    ^
    digit.java:43: cannot resolve symbol
    symbol : variable V
    location: class digit.ButtonHandler
    else if (charEntered == T || U || V)
    ^
    digit.java:45: cannot resolve symbol
    symbol : variable W
    location: class digit.ButtonHandler
    else if (charEntered == W || X || Y)
    ^
    digit.java:45: cannot resolve symbol
    symbol : variable X
    location: class digit.ButtonHandler
    else if (charEntered == W || X || Y)
    ^
    digit.java:45: cannot resolve symbol
    symbol : variable Y
    location: class digit.ButtonHandler
    else if (charEntered == W || X || Y)
    ^
    digit.java:79: cannot resolve symbol
    symbol : class Buttonhandler
    location: class digit
    operation = new Buttonhandler();
    ^
    25 errors
    I don't get what's wrong... I know it's something with the "equals" method.. but I can't get a grip on it.

    Hi again,
    Thanks, I'm beginning to understand the structure... charAt(0) means take character at index 0, i.e the first character.
    I also understood how the || works, and I managed to compile the thing without errors. Now my code looks like this:
    import java.awt.*;
    import java.awt.event.*;
    public class digit
        // Define action listener for alphabetic buttons
        private static class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent event)
         char  charEntered;    // Holds the character entered
         String whichButton;  // Button's name
         // Get the right button
         charEntered = inputField.getText().charAt(0);
         whichButton = event.getActionCommand();
         // If-Else procedures, to determine which button is pressed and what action to perform
         if (whichButton.equals("ok"))
              if (charEntered == 'A' || charEntered == 'B' || charEntered ==  'C')
             outputLabel.setText("Your digit is 2");
         else if (charEntered == 'D' || charEntered == 'E' || charEntered ==  'F')
             outputLabel.setText("Your digit is 3");
         else if (charEntered == 'G' || charEntered == 'H' || charEntered ==  'I')
             outputLabel.setText("Your digit is 4");
         else if (charEntered == 'J' || charEntered == 'K' || charEntered ==  'L')
             outputLabel.setText("Your digit is 5");
         else if (charEntered == 'M' || charEntered == 'N' || charEntered ==  'O')
             outputLabel.setText("Your digit is 6");
         else if (charEntered == 'P' || charEntered == 'R' || charEntered ==  'S')
             outputLabel.setText("Your digit is 7");
         else if (charEntered == 'T' || charEntered == 'U' || charEntered ==  'V')
             outputLabel.setText("Your digit is 8");
         else if (charEntered == 'W' || charEntered == 'X' || charEntered ==  'Y')
             outputLabel.setText("Your digit is 9");
         else outputLabel.setText("An error occured.");
    private static class ButtonHandler2 implements ActionListener
        public void actionPerformed(ActionEvent event)
         dFrame.dispose();
         System.exit(0);
    private static TextField inputField; // Input field
    private static Label outputLabel; // Output Label
    private static Frame dFrame; // Frame
    public static void main(String [] args)
        // Declare alphabetic listener
        ButtonHandler operation; 
        ButtonHandler2 quitOperation;
        Label entryLabel; // Label for inputfield
        Label outputLabel_label;  // Label for outputfield
        Button ok; // Ok Button
        Button quit; // quit button
        operation = new ButtonHandler();
        quitOperation = new ButtonHandler2();
        // New frame
        dFrame = new Frame();
        dFrame.setLayout(new GridLayout(4,2));
        entryLabel = new Label("Enter letter here");
        outputLabel_label = new Label("The result is");
        outputLabel = new Label("0");
        // Instantiate buttons
        ok = new Button("Ok");
        quit = new Button("Quit");
        // Name the button events
        ok.setActionCommand("ok");
        quit.setActionCommand("quit");
        // Register the button listeners
        ok.addActionListener(operation);
        quit.addActionListener(operation);
        // Add interface to the Frame
        dFrame.add(entryLabel);
        dFrame.add(inputField);
        dFrame.add(outputLabel_label);
        dFrame.add(outputLabel);
        dFrame.add(ok);
        dFrame.add(quit);
        dFrame.pack();
        dFrame.show();
        dFrame.addWindowListener(new WindowAdapter()
             public void windowClosing(WindowEvent event)
              dFrame.dispose();
              System.exit(0);
    }And I get this error while I'm trying to run it:
    fnatte:~/inda/java/chapter6>java digit
    Exception in thread "main" java.lang.NoSuchMethodError: main

  • Help - What is wrong with my code ?

    I have a cfform that does a db search, using a field and a
    search criteria selected by the user. Here is my code :
    <tr>
    <td align="center" colspan="2">
    <font size="3" face="Arial, Helvetica, sans-serif"
    color="003366">
    <b>Pick Request
    Number: </b></font>
    <input type="text" name="prNumber">
    <select name="search_type">
    <option value="Contains">Contains</option>
    <option value="Begins With">Begins With</option>
    <option value="Ends With">Ends With</option>
    <option value="Is">Is</option>
    <option value="Is Not">Is Not</option>
    <option value="Before">Before</option>
    <option value="After">After</option>
    </select>
    </td>
    </tr>
    Here is the query that I am using :
    <cfquery name="getPRNum" datasource="docuTrack">
    SELECT prNumber, fileName
    FROM dbo.psFileInventory
    <cfif form.search_type is "Contains">
    Where dbo.psFileInventory.prNumber like '%#form.prNumber#%'
    </cfif>
    <cfif form.search_type is "Begins With">
    Where dbo.psFileInventory.prNumber like '#form.prNumber#%'
    </cfif>
    <cfif form.search_type is "Ends With">
    Where dbo.psFileInventory.prNumber like '%#form.prNumber#'
    </cfif>
    <cfif form.search_type is "Is">
    Where dbo.psFileInventory.prNumber = '#form.prNumber#'
    </cfif>
    <cfif form.search_type is "Is Not">
    Where dbo.psFileInventory.prNumber <>
    '#form.prNumber#'
    </cfif>
    <cfif form.search_type is "Before">
    Where dbo.psFileInventory.prNumber <= '#form.prNumber#'
    </cfif>
    <cfif form.search_type is "After">
    Where dbo.psFileInventory.prNumber >= '#form.prNumber#'
    </cfif>
    </cfquery>
    It cannot find any records with any of the search criteria
    except for the = sign. However, when I do each criteria
    individually, it works. For example, lif I enter 'PR8' in the form,
    then like '#form.prNumber#%' in the query will give me all part
    numbers that begin with PR8...etc, so I am pretty sure each of the
    search criteria work.
    But when I run it combined, it cannot find anything except
    for the 'is' (=) criteria.
    Can somebody please tell me what I am doing wrong ? I just
    cannot see it.
    Thanks

    quote:
    ...but wouldn't the query be in the action page ?
    I'm not quite sure what you are asking here. Are
    you asking if you have to run the query again in the action page?
    If that is the question, then the answer is no, because that is why
    I have you assign the query results on your query page
    to a session variable so that you can make it available to
    use just like you would the results of a cfquery on your action
    page. In other words, if you did something like this
    <cfset session.getPRNum_qry = getPRNum> on your query
    page, you can do something like this on your action page...
    <cfif IsDefined("session.getPRNum_qry.prNumber")>
    <cfoutput query = "session.getPRNum_qry">
    #prNumber# #fileName#
    </cfoutput>
    </cfif>
    ... which would loop through your "query" and display your
    prNumber and fileName values for all rows returned. What you do
    with them is up to you.....
    Phil

  • What is wrong with this program segment? I could not understand the error..

    public class Hmw3
         public static char[] myMethod(char[]p1,int p2, char p3)
         {                             //13 th row
              if(p2<p1.length)
                   p1[p2]=p3;
                   System.out.println(p1);
         public static void main(String[] args)
              String sentence="It snows";
              char[] tmp=sentence.toCharArray();
              System.out.println(tmp);
              myMethod(tmp,3,'k');
              sentence=String.copyValueOf(tmp);
              System.out.println(sentence);     
    i wrote this program segment and compiler gave this error:
    C:\Program Files\Xinox Software\JCreator LE\MyProjects\hmw3\Hmw3.java:13: missing return statement
    What is wrong???

    Your method signature states that myMethod should return an array for chars.
    But in ur implementation of myMethod, there is nothing returned.
    Just add a return statement like "return p1"

  • Help, what's wrong with my upload function

    Hi,
    I want to write a java Bean (FileUploadBean) to upload the image files. I use a very simple txt file to test my Bean code, I've already know the syntax of the entity body of httpServletRequest object, it's like below:
    "-----------------------------7d327203032e
    Content-Disposition: form-data; name="toefl_form"; filename="C:\transfer\Picasso_ljm\jakarta-tomcat-4.0.1\webapps\junmin\image\test.txt"
    Content-Type: text/plain
    hi, this is a test;
    -----------------------------7d327203032e--
    My original test.txt file is only a line without '\r', '\n'.
    "hi, this is a test."
    But after call my upload function, the saved file is:
    hi, this is a test.
    There are 4 more bytes than the original file. Below is my FileUploadBean file, does anyone can figure out what's wrong in my upload function? Does the readLine read the return carriage and new line charactor too? Thank you very much!
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.ServletInputStream;
    import java.util.Dictionary;
    import java.util.Hashtable;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class FileUploadBean {
    private String savePath, saveFilename, filepath, filename, contentType;
    // private Dictionary fields;
    public String getFilename() {
    return filename;
    public String getFilepath() {
    return filepath;
    public void setSavePath(String savePath) {
    this.savePath = savePath;
    public void setSaveFilename(String saveFilename) {
    this.saveFilename = saveFilename;
    public String getContentType() {
    return contentType;
    private void setFilename(String s) {
    if (s==null)
    return;
    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
    filepath = s.substring(pos+10, s.length()-1);
    // Windows browsers include the full path on the client
    // But Linux/Unix and Mac browsers only send the filename
    // test if this is from a Windows browser
    pos = filepath.lastIndexOf("\\");
    if (pos != -1)
    filename = filepath.substring(pos + 1);
    else
    filename = filepath;
    private void setContentType(String s) {
    if (s==null)
    return;
    int pos = s.indexOf(": ");
    if (pos != -1)
    contentType = s.substring(pos+2, s.length());
    public void doUpload(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();
    // read boundary
    byte[] line = new byte[256];
    int i = in.readLine(line, 0, 256);
    if (i < 3)
    return;
    int boundaryLength = i - 2;
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    String newLine = new String(line, 0, i);
    if (newLine.startsWith("Content-Disposition: form-data; name=\""))
    if (newLine.indexOf("filename=\"") != -1) {
    setFilename(new String(line, 0, i-2));
    if (filename==null)
    return;
    //this is the file content
    i = in.readLine(line, 0, 256);
    setContentType(new String(line, 0, i-2));
    // blank line
    i = in.readLine(line, 0, 256);
    // read the first byte of the file
    i = in.read();
    FileOutputStream fo = new FileOutputStream((savePath==null? "" : savePath) + saveFilename);
    while (i != -1) {
    // if this byte is equal to the first byte of the boundary, then first mark this place, and
    // go ahead to check if it encounter the ending boundary. If it belongs to the file, then reset
    // the read position and reread.
    if( (char)i == '\r') {
    in.mark(256);
    i = in.read();
    char c1 = (char)i;
    i = in.read();
    char c2 = (char)i;
    i = in.readLine(line, 0, 256);
    // if it is the end of request body, then close the OutputStream. Since the first byte is
    // read already, then the final boundary size if +3
    if ( (c1 == '\n') && (c2 == '-') && (i==boundaryLength+3) // + 3 is eof
    && (new String(line, 0, i).startsWith(boundary.substring(1)))) {
    i = in.read();
    else {
    // it is not the eof, then write this byte into the outputStream and reset the read position
    fo.write(i);
    in.reset();
    i = in.read();
    } // end if
    // else if (char)i != '-', then write directly to the fileOutputStream
    else {
    fo.write(i);
    i= in.read();
    } // end while
    // close the fileOutputStream
    fo.close();
    }// end function

    HI,
    I find a bug myself. I add a line "i = in.read(line, 0, 256);" in doUpload function in the following position:
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    i = in.read(line, 0, 256);
    String newLine = new String(line, 0, i);
    But still, when I was trying to read a image file, it even didn't finish reading and quit already! Still has bugs, need help!
    Junmin

  • Help me please, what's wrong with my program...

    My program has no problem writing data into file. But, I get garbages when my program retrieved data from file. How to solve this, anyone? I tried last 4 days still can't figure out. :(
    /* myDate.java */
    import java.util.*;
    public class myDate extends Object{
    private int year;
    private int month;
    private int day;
    public myDate(String newDate) {
    StringTokenizer st = new StringTokenizer(newDate, "/");
    try {
    this.day = Integer.parseInt(st.nextToken());
    this.month = Integer.parseInt(st.nextToken());
    this.year = Integer.parseInt(st.nextToken());
    }catch (NumberFormatException nfe) {
    System.out.println("Incorrect Date Format!!!");
    System.out.println(nfe.getMessage());
    public void setDay (int Day) { this.day = Day; }
    public void setMonth (int Month) { this.month = Month; }
    public void setYear (int Year) { this.year = Year; }
    public String toString() {
    return day + "/" + month + "/" + year;
    public int getDay() { return day; }
    public int getMonth() { return month; }
    public int getYear() { return year;  }
    /* Inventory.java
    * Book Name: 30 bytes Characters
    * Book ISBN: 10 bytes Characters
    * Book Author: 30 bytes Characters
    * Book Genre : 30 bytes Characters
    * Book Quantity : 4 bytes integer
    * Date of the book purchased : 10 bytes Characters.
    import java.io.*;
    class Inventory{
    private String bookName, bookISBN, bookAuthor, bookGenre;
    private int quantity;
    private myDate datePurchased;
    public Inventory() {
    this.bookName = "";
    this.bookISBN = "";
    this.bookAuthor = "";
    this.bookGenre = "";
    this.quantity = 0;
    this.datePurchased = new myDate("00/00/0000");
    public void setBookName(String bookname) {
    this.bookName = bookname;
    public void setISBN(String BookISBN) {
    this.bookISBN = BookISBN;
    public void setAuthor(String author) {
    this.bookAuthor = author;
    public void setGenre(String genre) {
    this.bookGenre = genre;
    public void setQuantity(int qty) {
    this.quantity = qty;
    public void setPurchaseDate(String dateOfPurchase) {
    this.datePurchased = new myDate(dateOfPurchase);
    public String getBookName() { return bookName;}
    public String getISBN() { return bookISBN;}
    public String getAuthor() { return bookAuthor;}
    public String getGenre() { return bookGenre;}
    public int getQuantity() { return quantity;}
    public String getPurchaseDate() { return datePurchased.toString();}
    public String toString() {
    return bookName + "\n" + bookISBN + "\n" + bookAuthor + "\n" +
    bookGenre + "\n" + quantity + "\n" + datePurchased.toString() +
    "\n";
    public String fillData(RandomAccessFile raf, int len) throws
    IOException {
    char data[] = new char[len];
    char temp;
    for(int i = 0; i < data.length; i++) {
    temp = raf.readChar();
    data[i] = temp;
    return new String(data).replace('\0', ' ');
    public void writeStr(RandomAccessFile file, String data, int len)
    throws IOException {
    StringBuffer buf = null;
    if(data != null)
    buf = new StringBuffer(data);
    else
    buf = new StringBuffer(len);
    buf.setLength(len);
    file.writeChars(buf.toString());
    public void writeRecord(RandomAccessFile rafile) throws
    IOException {
    writeStr(rafile, getBookName(), 30);
    writeStr(rafile, getISBN(), 10);
    writeStr(rafile, getAuthor(), 30);
    writeStr(rafile, getGenre(), 30);
    rafile.writeInt(getQuantity());
    writeStr(rafile, getPurchaseDate(), 10);
    public void readRecord(RandomAccessFile rafile) throws
    IOException {
    setBookName(fillData(rafile, 30));
    setISBN(fillData(rafile, 10));
    setAuthor(fillData(rafile, 30));
    setGenre(fillData(rafile, 30));
    setQuantity(rafile.readInt());
    setPurchaseDate(fillData(rafile, 10));
    public final static int size() {
    return 114;
    /* btnPanel.java */
    import javax.swing.*;
    import java.awt.*;
    class btnPanel extends JPanel {
    JButton btnSave, btnCancel;
    public btnPanel() {
    btnSave = new JButton("Save Changes");
    btnCancel = new JButton("Cancel");
    add(btnSave);
    add(btnCancel);
    /* inpPanel2.java */
    import javax.swing.*;
    import java.awt.*;
    class inpPanel2 extends JPanel{
    JTextField tfBookName, tfBookISBN, tfGenre, tfQuantity,
    tfAuthor, tfDatePurchased;
    JLabel lblBookName, lblBookISBN, lblAuthor, lblGenre,
    lblQuantity, lblDatePurchased;
    public inpPanel2() {
    tfBookName = new JTextField("",30);
    tfBookISBN = new JTextField("",10);
    tfGenre = new JTextField("",30);
    tfAuthor = new JTextField("",30);
    tfQuantity = new JTextField("",10);
    tfDatePurchased = new JTextField("",10);
    lblBookName = new JLabel("Book Name ");
    lblBookISBN = new JLabel("ISBN ");
    lblAuthor = new JLabel("Author ");
    lblGenre = new JLabel("Genre ");
    lblQuantity = new JLabel("Quantity ");
    lblDatePurchased = new JLabel("Date Purchased ");
    setLayout(new GridLayout(6,2));
    add(lblBookName);
    add(tfBookName);
    add(lblBookISBN);
    add(tfBookISBN);
    add(lblAuthor);
    add(tfAuthor);
    add(lblGenre);
    add(tfGenre);
    add(lblQuantity);
    add(tfQuantity);
    add(lblDatePurchased);
    add(tfDatePurchased);
    /* InventoryAdd.java */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    class InventoryAdd extends JFrame {
    btnPanel buttonPanel;
    inpPanel2 inputPanel;
    Inventory bookInventory;
    RandomAccessFile rafile;
    public InventoryAdd() {
    super("Book Inventory - Add");
    buttonPanel = new btnPanel();
    buttonPanel.btnSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
    openFile();
    bookInventory = new Inventory();
    bookInventory.setBookName(inputPanel.tfBookName.getText());
    bookInventory.setISBN(inputPanel.tfBookISBN.getText());
    bookInventory.setAuthor(inputPanel.tfAuthor.getText());
    bookInventory.setGenre(inputPanel.tfGenre.getText());
    bookInventory.setQuantity(
    Integer.parseInt(
    inputPanel.tfQuantity.getText()));
    bookInventory.setPurchaseDate(inputPanel.tfDatePurchased.getText());
    try {
    bookInventory.writeRecord(rafile);
    }catch(IOException ioe) {
    System.out.println("Cannot Write Record into file...");
    System.out.println(ioe.getMessage());
    clearInput();
    closeFile();
    System.out.println(bookInventory.toString());
    buttonPanel.btnCancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
    clearInput();
    inputPanel = new inpPanel2();
    Container c = getContentPane();
    c.setLayout(new BorderLayout());
    c.add(inputPanel, BorderLayout.CENTER);
    c.add(buttonPanel, BorderLayout.SOUTH);
    setSize(350, 190);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    public void clearInput() {
    inputPanel.tfBookName.setText("");
    inputPanel.tfBookISBN.setText("");
    inputPanel.tfAuthor.setText("");
    inputPanel.tfGenre.setText("");
    inputPanel.tfQuantity.setText("");
    inputPanel.tfDatePurchased.setText("");
    public void openFile() {
    try {
    rafile = new RandomAccessFile("BOOK_INV.DAT","rw");
    rafile.seek(rafile.length());
    }catch(IOException ioe) {
    System.out.println("Error, Cannot open File");
    public void closeFile() {
    try{
    rafile.close();
    }catch(IOException ioe) {
    System.out.println("Error, Cannot Close File");
    public static void main(String args[]) {
    new InventoryAdd();
    /* ReadInv.java */
    import java.io.*;
    class ReadInv {
    RandomAccessFile rafile;
    Inventory bookInv;
    public ReadInv() {
    bookInv = new Inventory();
    try {
    rafile = new RandomAccessFile("BOOK_INV.DAT","r");
    rafile.seek(0);
    for(int i=0; i < (rafile.length()/bookInv.size()); i++) {
    bookInv.readRecord(rafile);
    System.out.println(bookInv.toString());
    }catch(IOException ioe) {}
    public static void main(String args[]) {
    new ReadInv();

    it's hard to read. please use code tag.
    why don't u use object serialization by implements Serializable?
    import java.io.Serializable;
    public class Inventory implements Serializable {
        // u don't need to change ur code here
    }when saving & loading inventory, u can use ObjectOutputStream & ObjectInputStream.
    here is an example:
    Inventory i = new Inventory();
    // set your inventory here
    // save to file
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
       "InventoryFile.dat")); // file name
    out.writeObject(i);
    // u can write many object to one single file.
    out.close();
    // load the file
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(
       "InventoryFile.dat"));
    Inventory i = (Inventory) in.readObject();

  • I need Help what is wrong with my code?

    Hi, well I am doing a class and a driver for a sphere. I need to compute the volume and surface area of the sphere I have the formula but when I run the program I don't get a result for neither. I would like to know what am I doing wrong? Here is my code. Thanks.
    This is my class
    import java.text.DecimalFormat;
        public class Sphere
       //Variable Declarations.
          private int diameter;
          private double radius;
       //Constructor: Accepts and initialize instance data.
           public Sphere(int sp_diameter)
             diameter = sp_diameter;
       //Set methods: Diameter
           public void setDiameter(int new_diameter)
             diameter = new_diameter;
       //Get methods: Diameter
           public int getDiameter()
             return diameter;
       //Compute volume and surface area of the sphere
           public double getVolume()
             return  4 * Math.PI * radius * radius * radius / 3;
           public double getArea()
             return  4 * Math.PI * radius * radius;
       //toString method will return one line description of the sphere
           public String toString()
             DecimalFormat fmt =new DecimalFormat("0.###");
             String sphere = " " + fmt.format(diameter) +fmt.format(getVolume()) + fmt.format(getArea());        
             return sphere;
    Here is the driver
    public static void main(String[]args)
             Sphere sphere1, sphere2, sphere3;
             sphere1 = new Sphere(10);
             sphere2 = new Sphere(12);
             sphere3 = new Sphere(20);
             System.out.println("The sphere diameter are: ");
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: " + sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + " " + sphere1.getVolume() + " " + sphere1.getArea());
             System.out.println("\tSphere2: " + " " + sphere2.getVolume() + " " + sphere2.getArea());
             System.out.println("\tSphere3: " + " " + sphere3.getVolume() + " " + sphere3.getArea());
          //Change the diameter of the sphere.
             sphere1.setDiameter(11);
             sphere2.setDiameter(15);
             sphere3.setDiameter(25);
             System.out.println("\nNew diameter is: ");
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: " + sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + " " + sphere1.getVolume() + " " + sphere1.getArea());
             System.out.println("\tSphere2: " + " " + sphere2.getVolume() + " " + sphere2.getArea());
             System.out.println("\tSphere3: " + " " + sphere3.getVolume() + " " + sphere3.getArea());
          //Using the toString Method.
             System.out.println("\nFirst sphere: " + sphere1);
       }

    Maybe try a different constructor for sphere...
    public Sphere(int sp_diameter, int sp_radius)
    diameter = sp_diameter;
    }nd maybe even a setRadius(int newRadius) and
    getRadius().
    Hope that helpsYou should not do it this way. The reason.. The radius is 1/2 the diameter. if you have seperate methods, then the programmer can set the diameter to X and the radius to 10X. not good.
    A better way for the c'tor would be:
        //Constructor: Accepts and initialize instance data.
        public Sphere(int sp_diameter) {
            diameter = sp_diameter;
            radius = (double) diameter/2.0;  //<-- I added this
        }something similar in the setDiameter..

  • What's wrong with this program that about socket

    package example;
    import java.net.*;
    import java.io.*;
    public class Server implements Runnable{
        Thread t;
        ServerSocket sSocket;
        int sPort=6633;
        public Server(){
            try{
                sSocket=new ServerSocket(sPort);
                System.out.println("server start....");
            }catch(IOException e){
                e.printStackTrace();
            t=new Thread(this);
            t.start();
        public void run(){
            try{
                while(true){
                    Socket cSocket=sSocket.accept();
                    ClientThread cThread=new ClientThread(cSocket);
                    cThread.start();
            }catch(IOException e){
                e.printStackTrace();
       public static void main(String[] args){
            new Server();
    package example;
    import java.net.*;
    import java.io.*;
    public class ClientThread extends Thread{
        Socket cSocket;
        PrintStream writer;
        BufferedReader reader;
        public ClientThread(Socket s){
            cSocket=s;
            try{
                writer=new PrintStream(cSocket.getOutputStream());
                reader=new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
            }catch(IOException e){
                e.printStackTrace();
        public void run(){
            try{
                while(true){
                    String message=reader.readLine();
                    System.out.println("Server get:"+message);
            }catch(IOException e){
                e.printStackTrace();
    package example;
    import java.net.*;
    import java.io.*;
    public class Client{
        public static void main(String[] args){
            String ipaddr="localhost";
            PrintStream writer;
            try{
                Socket  cSocket=new Socket(ipaddr,6633);
                System.out.println(cSocket);
                writer=new PrintStream(cSocket.getOutputStream());
                System.out.println("client send:hello");
                writer.print("hello");
            catch(Exception e){
                e.printStackTrace();
    }first,I run Server,and then I run Client,
    output at Server:
    server start....
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.net.SocketInputStream.read(SocketInputStream.java:90)
    at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:285)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at example.ClientThread.run(ClientThread.java:20)
    what' wrong??????

    In your Client class, after doing writer.print("hello"); you should flush
    the output stream. As it is now, you attempt to write something (without actually
    sending something to your server) and main simply terminates. The server,
    still waiting for some input (you didn't flush on the client side), is confronted with
    a closed client socket (main on the client side terminated and implicitly closed
    the client socket), hence the 'connection reset' exception on the server side.
    kind regards,
    Jos

  • Help - what is wrong with my iMac ?

    Hello
    I'd really appreciate some help and advice with by iMac !
    I'm having a really strange issue and I've no idea whats casuing it.
    After using it for a while whichever window is open starts to black out - you can shut the window down but it remains there - if you click you mouse onto the screen you can pull a square out and it reveals the desktop wall paper underneath !
    You cant force quit the open screens, the only way to stop it is to restart.
    I have posted some photos for you to see - I hope someone can help !
    [url=http://www.flickr.com/photos/52989912@N02/8686257908/][img]http://farm9.staticflickr.com/8538/8686257908_fa4d265b87_c.jpg[/img][/url]
    [url=http://www.flickr.com/photos/52989912@N02/8686257908/]
    [url=http://www.flickr.com/photos/52989912@N02/8685138651/][img]http://farm9.staticflickr.com/8123/8685138651_3fee66c385_c.jpg[/img][/url]
    [url=http://www.flickr.com/photos/52989912@N02/8685138651/]
    thanks

    thanks for replying
    unfortunatle I blew the dust out of the vents before running temperature monitor so I can only say what the temps are now !
    Ambient 16c
    CPU A heatsink 31c
    Graphics processor chip 1 41c
    Graphics processor heatsink 1 41c
    Graphics Processor temp diode 45c
    Power supply 54c
    Just to state again I blew a heck of a lot of dust out (with a compressor) - really amazed at how much there was
    I probably blew too hard though as some dust has gone behind the screen but luckily you cant see it when the screen is on..
    thanks

  • Help: what's wrong with my code?

    Hi. I'm using JNDI to connect to an SQL Server Database.
    My machine can only handle jcreator or netbeans 4.1
    is it possible for me to deploy or create such connection?
    Please help me.
    All suggestions would be very much appreciated.
    import javax.sql.*;
    import java.sql.*;
    import java.io.*;
    import javax.naming.*;
    import java.util.*;
    public class Test {
        public static void main(String[] args) {
            System.out.println("Starting test.");
            setJVMProperties();
            bindDataSource();
            testDataSource();
            System.out.println("Test finished.");
        public static void setJVMProperties() {
            Properties p = new Properties(System.getProperties());
            p.setProperty("java.naming.factory.initial",
    "com.sun.jndi.fscontext.RefFSContextFactory");
            p.setProperty("java.naming.provider.url", "com.ibm.websphere.naming.WsnInitialContextFactory");
            System.setProperties(p);
        public static void bindDataSource() {
            Context ctx = null;
            try {
    // On the 3 lines below, I get the error: package com.microsoft.jdbc.sqlserver does not exist
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    com.microsoft.jdbc.sqlserver.SQLServerDriver sqlServerDS = new
    com.microsoft.jdbc.sqlserver.SQLServerDriver();
                sqlServerDS.setServerName("PSERVER\\PINST");
                sqlServerDS.setPortNumber("9080");
                sqlServerDS.setDatabaseName("Customer");
                sqlServerDS.setUser("neil");
                sqlServerDS.setPassword("123");
                ctx = new InitialContext();
                ctx.rebind("jdbc/Name", sqlServerDS);
            } catch (Exception e) {
                System.err.println("Error binding datasource with jndi. " +e);
        public static void testDataSource() {
            try {
                 int id;
                Context ctx = new InitialContext();
                DataSource ds = (DataSource)ctx.lookup("jdbc/Name");
                Connection con = ds.getConnection();
                CallableStatement cs = con.prepareCall("{? = Call Login(?,?)}");
                cs.registerOutParameter(1, Types.INTEGER);
                cs.setString(2, "123");
                cs.setString(3, "123");
                cs.execute();
                id = cs.getInt(1);
                System.out.println(id);
               try {
                        cs.close();
                        con.close();
                } catch (Exception e) {System.err.println(e);}
            } catch (Exception e) {
                System.err.println("Problem running db stuff." +e);
    }

    hi. thanks so much for your tip. i followed it and finally my
    com.microsoft.jdbc.sqlserver.SQLServerDriver sqlServerDS = new
    com.microsoft.jdbc.sqlserver.SQLServerDriver();line is now recognized...
    However, i get errors on the next 5 lines
       sqlServerDS.setServerName("PSERVER\\PINST");
                sqlServerDS.setPortNumber("9080");
                sqlServerDS.setDatabaseName("Customer");
                sqlServerDS.setUser("neil");
                sqlServerDS.setPassword("123");the errors i get are something like: cannot find symbol
    symbol : method setUser(java.lang.String)
    location: class com.microsoft.jdbc.sqlserver.SQLServerDriver
    sqlServerDS.setUser("neil");
    as you might have noticed, i'm really new to java programming and i would very much appreciate all the help i can get.

  • When measuring 6 voltage signals in labview I found that there was a difference in voltage signals in my program but not in the test panel. The test panel is correct. What is wrong with my program?

    My labview program is not displaying equivelent voltages, but labview test panel is. So the computer is seeing the correct signals. My program is displaying a small difference in 3 out of 6 channels. All channels should be equal.

    G'Day Pops,
    You haven't really given us enough to go on - could you please post your VI so we can have a look at it?
    cheers,
    Christopher
    Christopher G. Relf
    Certified LabVIEW Developer
    [email protected]
    Int'l Voicemail & Fax: +61 2 8080 8132
    Aust Voicemail & Fax: (02) 8080 8132
    EULA
    1) This is a private email, and although the views expressed within it may not be purely my own, unless specifically referenced I do not suggest they are necessarily associated with anyone else including, but not limited to, my employer(s).
    2) This email has NOT been scanned for virii - attached file(s), if any, are provided as is. By copying, detaching and/or opening attached files, you agree to indemnify the sender of such responsibility.
    3) B
    ecause e-mail can be altered electronically, the integrity of this communication cannot be guaranteed.
    Copyright © 2004-2015 Christopher G. Relf. Some Rights Reserved. This posting is licensed under a Creative Commons Attribution 2.5 License.

  • What is wrong with this program?

    When I run a get these messages:
    ^
    MULTIPLYIMP.java:25: 'class' or 'interface' expected
    ^
    MULTIPLYIMP.java:7: cannot resolve symbol
    symbol : class UnicastRemoteObject
    location: class MULTIPLYIMP
    UnicastRemoteObject implements multiply {
    ^
    MULTIPLYIMP.java:6: MULTIPLYIMP should be declared abstract; it does not define
    greet() in MULTIPLYIMP
    public class MULTIPLYIMP extends
    ^
    MULTIPLYIMP.java:11: cannot resolve symbol
    symbol : method supa ()
    location: class MULTIPLYIMP
    supa (); //Export
    ^
    MULTIPLYIMP.java:15: missing method body, or declare abstract
    public int mult (int a,int b) throws RemoteException
    ^
    9 errors
    //MULTIPLYIMPL.JAVA
    import java.rmi.*;
    import .rmi.server.*;
    public class MULTIPLYIMP extends
    unicastRemoteObject implements multiply {
    public MULTIPLYIMPL () throwsRemoteException {
    supa (); //Export
    public int mult (int a,int b) throws RemoteException
    return (a * b)
    public String greet () throws RemoteException
    return("CCM 3061");

    When I run a get these messages:
    ^
    MULTIPLYIMP.java:25: 'class' or 'interface' expected
    ^
    MULTIPLYIMP.java:7: cannot resolve symbol
    symbol : class UnicastRemoteObject
    location: class MULTIPLYIMP
    UnicastRemoteObject implements multiply {
    ^
    You haven't imported the right package.
    You need to import
    java.rmi.server.UnicastRemoteObject
    or
    java.rmi.server.*
    MULTIPLYIMP.java:6: MULTIPLYIMP should be declared
    abstract; it does not define
    greet() in MULTIPLYIMP
    public class MULTIPLYIMP extends
    ^
    It says that you don't define greet() because it doesn't have curly braces after the method name.
    I'm reasonably sure
    public String greet () throws RemoteException
    return("CCM 3061");is not acceptable, usepublic String greet () throws RemoteException
    return("CCM 3061");
    MULTIPLYIMP.java:11: cannot resolve symbol
    symbol : method supa ()
    location: class MULTIPLYIMP
    supa (); //Export
    ^
    MY GOD MAN, SUPER(), SUPER!!!!!!
    MULTIPLYIMP.java:15: missing method body, or declare
    abstract
    public int mult (int a,int b) throws RemoteException
    ^
    9 errors
    Same with mult(), need to have curly braces around the method body
    //MULTIPLYIMPL.JAVA
    import java.rmi.*;
    WHAT IS THIS LINE?
    import java.rmi.server.*
    import .rmi.server.*;
    public class MULTIPLYIMP extends
    unicastRemoteObject implements multiply {
    public MULTIPLYIMPL () throwsRemoteException {
    supa (); //Export
    public int mult (int a,int b) throws RemoteException
    return (a * b)
    public String greet () throws RemoteException
    return("CCM 3061");
    }Messy messy code mate,
    Good luck,
    Radish21

  • What is wrong with this program it keeps telling me the file doesn't exist?

    this program is supposed to write the file so why does it need the file to already exist?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class NewClass implements ActionListener{
        static List list = new List();
        static TextField input = new TextField(20);
        static Button submit = new Button("Submit");
        static Frame f = new Frame("RealmList editor");
        static File file = new File("/Applications/World of Warcraft/realmlist.wtf");
        static Label status = new Label("");
        static Button selected = new Button("Change to Selected");
        static File config = new File("/Applications/RealmLister/config.txt");
        static File dir = new File("/Applications/RealmLister/");
        public static void main(String[] args) {
            f.setLayout(new BorderLayout());
            f.add(list, BorderLayout.CENTER);
            Panel p = new Panel();
            p.add(input);
            p.add(submit);
            p.add(selected);
            f.add(p, BorderLayout.NORTH);
            f.add(status, BorderLayout.SOUTH);
            new NewClass();
            f.setSize(500,500);
            f.setVisible(true);
            try {
                loadConfig();
            } catch(Exception e) {}
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                    try {
                      writeConfig();
                      System.exit(0);
                    } catch(Exception e) {
                       status.setText("Error: config couldn't be written!("+e+")");
        public NewClass() {
            submit.addActionListener(this);
            input.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                    editRealmlist(input.getText(), true);
                    input.setText("");
                 catch(Exception ex) {
                   status.setText("Error: "+e);
            selected.addActionListener(this);
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == submit) {
                try {
                    editRealmlist(input.getText(), true);
                    input.setText("");
                } catch(Exception ex) {
                   status.setText("Error: "+e);
                   wait(3000);
                   status.setText("");
            if(e.getSource() == selected) {
                try {
                    editRealmlist(list.getSelectedItem(),false);
                } catch(Exception ex) {
                    status.setText("Error: "+e);
                    wait(3000);
                    status.setText("");
        public static void loadConfig() throws Exception{
            if(config.exists()) {
                Scanner scan = new Scanner(config);
                ArrayList<String> al = new ArrayList<String>();
                while(scan.hasNext()) {
                    al.add(scan.nextLine());
                for(int i = 0; i < al.size(); i++) {
                    list.add(al.get(i));
        public static void writeConfig() throws Exception{
            FileWriter fw = new FileWriter(config);
            dir.mkdir();
            config.mkdirs();
            String temp = "";
            for(int i = 0; i < list.getItemCount(); i++) {
                temp += list.getItem(i)+"\n";
            fw.write(temp);
            fw.flush();
            System.gc();
        public static void editRealmlist(String realm, boolean addtoList) throws Exception{
            FileWriter fw = new FileWriter(file);
            fw.write("set realmlist "+realm+"\nset patchlist us.version.worldofwarcraft.com");
            fw.flush();
            status.setText("Editing RealmList.wtf Please Wait...");
            Thread.sleep(3000);
            status.setText("");
            System.gc();
            if(addtoList)
                list.add(realm);
        public void wait(int time) {
            try {
                Thread.sleep(time);
            catch(Exception e) {}
    }

    Erm, you should call mkdirs() on a File object that represents a directory.

Maybe you are looking for

  • File content conversion using SOAP adapter

    Hi,      I'm using a receiver SOAP adapter in my IDOC to file scenario and need to do file content conversion in the receiver side. Are any standard modules available for file content conversion in the SOAP adapter or do I need to write custom EJB mo

  • I can't see all my open tabs from browser 1 in browser 2

    I expected that one the first computer I leave my session, and after the sync on the second computer I will see the same state. I also expected that if I open 1 new and close 1 old tab on the second one, going back to the first computer I will see th

  • App crashes even with OS8.1.1 update

    My Scrabble app just keep crashing and closing ever since OS8 upgrade. Even with 8.1.1 it is just as bad

  • Do macbook pro cases fit on macbook pro with retina display?

    I want to order a really nice speck case for macbook pro 13inch and i have got a macbook pro 13inch with retina display. Does it matter? Is there a difference between the two?

  • Ai doesn't launch, asking to activating an already active font.

    On Ai I had to find a very specific glyph, so I turned off a lot of fonts via FontExplorer. When I finished to dig into all the glyph maps, I turned on the basic fonts families, but now Illustrator doesn't want to launch. It says that "Verdana Font i