New to Java Please, I want to understand..

Hi,
Here is what I am trying to do. I have a *.csv file that I want to put into an arraylist and the see the results on the screen. I get the code to compile but I don't understand the run-time error that is generated. Below is the code I am using plus the *.CSV and the run-time error:
//The code
import java.io.*;
import java.util.*;
public class File2Array {
    public static void main(String[] args) {
        File file = new File("persons_test.csv");
        ArrayList persons = (ArrayList) getPersons(file);
        for (Iterator i = persons.iterator(); i.hasNext(); ) {
            System.out.println(i.next());
    public static List getPersons(File file) {
        ArrayList persons = new ArrayList();
        try {
            BufferedReader buf = new BufferedReader(new FileReader(file));
            while (buf.ready()) {
                String line = buf.readLine();
                StringTokenizer tk = new StringTokenizer(line, ",");
                ArrayList params = new ArrayList();
                while (tk.hasMoreElements()) {
                    params.add(tk.nextToken());
                Person p = new Person(
                        (String) params.get(0),
                        (String) params.get(1),
                        (String) params.get(2),
                        (String) params.get(3),
                        (String) params.get(4));
                persons.add(p);                       
        } catch (IOException ioe) {
            System.err.println(ioe);
        return persons;
class Person {
    private String ID;
    public Person(
        String ID,
        String LastName,
        String FirstName,
        String Phone,
        String Email) {
        this.ID = ID;
    public String toString() {
        return ID;
}//The comma separated values
*.CSV:
ID, LastName, FirstName, Phone, Email
2744, Avanto, Aldo, 562-593-6500, [email protected]
1212, Dewy, Cheatem, 123-456-7890, [email protected]
2345, yez, Wei do, 456-789-0123, [email protected]
//The error
Error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size:
0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at TryReadFileToArray_2.getPersons(TryReadFileToArray_2.java:25)
at TryReadFileToArray_2.main(TryReadFileToArray_2.java:8)

Both of the above 2 posts are right about the line breaks. I tried it and that caused the same exception message. Here is the modified relevant code which fixes that issue (solution suggested by jboeing). After this fix, I can have as many line breaks without any problem.
while (buf.ready()) {
                    String line = buf.readLine();
                    if (!line.equals("")){ //NEW LINE ADDED
                         StringTokenizer tk = new StringTokenizer(line, ",");
                         ArrayList params = new ArrayList();
                         while (tk.hasMoreElements()) {
                              params.add(tk.nextToken());
                         Person p = new Person(
                                   (String) params.get(0),
                                   (String) params.get(1),
                                   (String) params.get(2),
                                   (String) params.get(3),
                                   (String) params.get(4));
                         persons.add(p);      
               }My java file and csv file is a copy/paste job from your first post. My CSV file does not have any line breaks at all. I used Eclipse3 for java. I also tried using Notepad/command prompt combo. Same output from both versions.

Similar Messages

  • How do i undo my IOS 6 update because there is no youtube and I hate the new software.  Please i want to have my older version of software back on my ipad2.

    How do i undo my IOS 6 update because there is no youtube and I hate the new software.  Please i want to have my older version of software back on my ipad2.
    I have installed the youtube app. But i hate it so much i just want my old youtube back.  How can i undo my software update?

    @doclochte
    Well, if you loose functionality und good user experience due to apples and googles quarrels its simply not a matter of bugfixing. If you want to get rid of googles services (Maps, Youtube) you should at least make shure, the user experience stays the same. Without the youtube app custom made for easy iPad use, you need to buy an app to at least get fullscreen view but with a much more complicated navigation (iCabMobile for example). And GoogleMaps is right now still the far better service.
    If google lets me use programs for free (to make advertisements) I'm ok with a beta. If I buy a very expensive apple device I'm definitely NOT ok with this, especially when I'm forbidden to revert to what I had before. PLease let me downgrade to 5.1.1 again at least.

  • New to Java, Please help

    Hi, I was trying to play a game and came up with this java error (below), I uninstalled and reinstalled still no fix. I think i need a new class?, If anyone can explain the potential problem to me and help me fix it, that would be much appreciated. I'm a complete NEWB when it comes to java, I'm not even sure how to edit that code. so please remember to explain in the newbiest of newby answers. I am proficient with features of a computer just not java.
    Java Plug-in 1.6.0_24
    Using JRE version 1.6.0_24-b07 Java HotSpot(TM) Client VM
    User home directory = C:\Users\Ethan
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    load: class loader.class not found.
    java.lang.ClassNotFoundException: loader.class
    at sun.plugin2.applet.Applet2ClassLoader.fi… Source)
    at sun.plugin2.applet.Plugin2ClassLoader.lo… Source)
    at sun.plugin2.applet.Plugin2ClassLoader.lo… Source)
    at sun.plugin2.applet.Plugin2ClassLoader.lo… Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.lo… Source)
    at sun.plugin2.applet.Plugin2Manager.create… Source)
    at sun.plugin2.applet.Plugin2Manager$Applet… Source)
    at java.lang.Thread.run(Unknown Source)
    Exception: java.lang.ClassNotFoundException: loader.class

    845681 wrote:
    Hi, I was trying to play a game and came up with this java error (below), I uninstalled and reinstalled still no fix. I think i need a new class?, If anyone can explain the potential problem to me and help me fix it, that would be much appreciated. I'm a complete NEWB when it comes to java, I'm not even sure how to edit that code. so please remember to explain in the newbiest of newby answers. I am proficient with features of a computer just not java.If you want to learn how to program java, which is not the same as playing that particular game then you can start with the following link.
    http://download.oracle.com/javase/tutorial/getStarted/index.html

  • Very new to java please help

    i'm very new to java and i'm getting an error in my application. i took 4 applications that compiled and worked separatly and i tried to combine them into one application. i'm getting the error: unreported exception java.io.IOException; must be caught or declared to be thrown, in lines 73,78,83,88,120,146,149,152,155 in the and it points at the keyboard.readLine() but everything i've tried just gives me more errors. please help anything and everything will be greatly appreciated. here it is, sorry about format i dunno how to straighten it in here:
    // ^ ^
    //               (0)(0) A Happy Piggy Application
    // Problems: 2.6,2.8,2.9,2.12 (oo)
    // An application finds the total number of hours, minutes, & seconds, finds the distance
    // between two points, finds the volume and surface area of a sphere, and adds up the change
    // in a jar. First, the total hours, minutes, and seconds problem.
    import java.io.*;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    public class twoptsix
         static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
         public static void main (String[] args) throws IOException
              double hoursa, minutesa, secondsa;
              String hours;
              System.out.print ("Please enter a number of hours: ");
    hours = keyboard.readLine();
    hoursa = Double.parseDouble(hours); //asks programmer friendly user to enter hours
    String minutes;
    System.out.print ("Please enter a number of minutes: ");
    minutes=keyboard.readLine();
    minutesa = Double.parseDouble(minutes); //asks programmer friendly user to enter minutes
    String seconds;
    System.out.print ("Pretty please enter a number of seconds: ");
    seconds = keyboard.readLine();
    secondsa = Double.parseDouble(seconds); //asks programmer friendly user to enter seconds
    double allseconds;
    allseconds = (hoursa * 3600) + (minutesa * 60) + secondsa; //adds up all the seconds of the time entered
    System.out.println ("You have: " + hours + " hours..."); //displays hours
    System.out.println ("" + minutes + " minutes..."); //displays minutes
    System.out.println ("and " + seconds + " seconds..."); //displays seconds
              System.out.println ("to get whatever you need to done!"); //witty attempt at humor
    System.out.println ("The total amount of seconds is: " + allseconds + " seconds."); //displays total seconds
    // An application that finds the distance between two points when the points
    // are given by the user.
              double x1, x2, y1, y2, total, distance;
              String xa;
              System.out.print ("Please enter the 'x' coordinate of first point: ");
              xa = keyboard.readLine();
              x1 = Double.parseDouble(xa); //asks programmer friendly user to enter first x value
              String ya;
              System.out.print ("...also need the 'y' coordinate of first point: ");
              ya = keyboard.readLine();
              y1= Double.parseDouble(ya); //asks programmer friendly user to enter first y value
              String xb;
              System.out.print ("...and the 'x' coordinate of the second point: ");
              xb = keyboard.readLine();
              x2 = Double.parseDouble(xb); //asks programmer friendly user to enter second x value
              String yb;
              System.out.print ("...don't forget the 'y' coordinate of the second point: ");
              yb = keyboard.readLine();
              y2 = Double.parseDouble(yb); //asks programmer friendly user to enter second y value
              total = Math.pow(x2 - x1, 2.0) + Math.pow(y2 - y1, 2.0); //squares the differences of values
              distance = Math.sqrt(total); //finds the square root of the sum of the differences of the values
              System.out.print ("E=mc^2...oh and,");
              System.out.print ("the distance between point (" + xa +"," + ya +") and point("+
              xb + "," + yb + ") is : " + distance);
    // An application that takes the radius of a sphere and finds and prints
    // the spheres volume and surface area.
              double radius,volume,area;
              String rad;
              System.out.print("Please enter the radius of a sphere: ");
              rad = keyboard.readLine();
              radius = Double.parseDouble(rad); //asks programmer friendly user to enter the radius of a sphere
    DecimalFormat fmt = new DecimalFormat ("0.####");
              volume = ((4 * Math.PI * Math.pow(radius,3.0)) / 3) ;
              System.out.println (" The sphere has a volume of:" + fmt.format(volume)); //finds and displays volume
              area = ( 4 * Math.PI * Math.pow(radius, 2.0)) ;
              System.out.print (" The Surface Area of the sphere is: " + fmt.format(area)); //finds and displays surface area
    // An application that finds the total, in dollars and cents, of a number of quarters,
    // nickels, dimes, and pennies in your piggy bank.
              int pennies, nickels, dimes, quarters;
              double money1;
              screen.println("Empty your piggy bank and count the change, how many quarters ya have?: ");
              int q = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of quarters
              screen.println("How many dimes?: ");
              int d = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of dimes
              screen.println("How many nickels?: ");
              int n = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of nickels
              screen.println("How many pennies?: ");
              int p = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of pennies
              NumberFormat money = NumberFormat.getCurrencyInstance();
              money1 = (.25 * q) + (.1 * d) + (.05 * n) + (.01 * p);
              screen.println("You're rich! Total, you've got: " + money.format(money1));//finds and displays total money

    Ok here is the working code as one long function:
    // ^ ^
    // (0)(0) A Happy Piggy Application
    // Problems: 2.6,2.8,2.9,2.12 (oo)
    // An application finds the total number of hours, minutes, & seconds, finds the distance
    // between two points, finds the volume and surface area of a sphere, and adds up the change
    // in a jar. First, the total hours, minutes, and seconds problem.
    import java.io.*;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    public class twoptsix
        static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
        static PrintWriter screen = new PrintWriter(System.out, true);
        public static void main (String[] args) throws IOException
    double hoursa, minutesa, secondsa;
    String hours;
    System.out.print ("Please enter a number of hours: ");
    hours = keyboard.readLine();
    hoursa = Double.parseDouble(hours); //asks programmer friendly user to enter hours
    String minutes;
    System.out.print ("Please enter a number of minutes: ");
    minutes=keyboard.readLine();
    minutesa = Double.parseDouble(minutes); //asks programmer friendly user to enter minutes
    String seconds;
    System.out.print ("Pretty please enter a number of seconds: ");
    seconds = keyboard.readLine();
    secondsa = Double.parseDouble(seconds); //asks programmer friendly user to enter seconds
    double allseconds;
    allseconds = (hoursa * 3600) + (minutesa * 60) + secondsa; //adds up all the seconds of the time entered
    System.out.println ("You have: " + hours + " hours..."); //displays hours
    System.out.println ("" + minutes + " minutes..."); //displays minutes
    System.out.println ("and " + seconds + " seconds..."); //displays seconds
    System.out.println ("to get whatever you need to done!"); //witty attempt at humor
    System.out.println ("The total amount of seconds is: " + allseconds + " seconds."); //displays total seconds
    // }  <----- MAIN FUNCTION USED TO END HERE!!!
    //but we want to keep going so remove the bracket!
    // An application that finds the distance between two points when the points
    // are given by the user.
    // {  <-- other function used to start here, but now it continues
    double x1, x2, y1, y2, total, distance;
    String xa;
    System.out.print ("Please enter the 'x' coordinate of first point: ");
    xa = keyboard.readLine();
    x1 = Double.parseDouble(xa); //asks programmer friendly user to enter first x value
    String ya;
    System.out.print ("...also need the 'y' coordinate of first point: ");
    ya = keyboard.readLine();
    y1= Double.parseDouble(ya); //asks programmer friendly user to enter first y value
    String xb;
    System.out.print ("...and the 'x' coordinate of the second point: ");
    xb = keyboard.readLine();
    x2 = Double.parseDouble(xb); //asks programmer friendly user to enter second x value
    String yb;
    System.out.print ("...don't forget the 'y' coordinate of the second point: ");
    yb = keyboard.readLine();
    y2 = Double.parseDouble(yb); //asks programmer friendly user to enter second y value
    total = Math.pow(x2 - x1, 2.0) + Math.pow(y2 - y1, 2.0); //squares the differences of values
    distance = Math.sqrt(total); //finds the square root of the sum of the differences of the values
    System.out.print ("E=mc^2...oh and,");
    System.out.print ("the distance between point (" + xa +"," + ya +") and point("+
         xb + "," + yb + ") is : " + distance);
    //second function used to end here...
    //} <--- COMMENT OUT BRACKET SO WE CONTINUE
    // An application that takes the radius of a sphere and finds and prints
    // the spheres volume and surface area.
    //{ <--- ANOTHER ONE TO COMMENT OUT
    double radius,volume,area;
    String rad;
    System.out.print("Please enter the radius of a sphere: ");
    rad = keyboard.readLine();
    radius = Double.parseDouble(rad); //asks programmer friendly user to enter the radius of a sphere
    DecimalFormat fmt = new DecimalFormat ("0.####");
    volume = ((4 * Math.PI * Math.pow(radius,3.0)) / 3) ;
    System.out.println (" The sphere has a volume of:" + fmt.format(volume)); //finds and displays volume
    area = ( 4 * Math.PI * Math.pow(radius, 2.0)) ;
    System.out.print (" The Surface Area of the sphere is: " + fmt.format(area)); //finds and displays surface area
    // } <----- COMMENTED OUT FOR THE SAME REASON
    // An application that finds the total, in dollars and cents, of a number of quarters,
    // nickels, dimes, and pennies in your piggy bank.
    //{ <----AND ANOTHER
    int pennies, nickels, dimes, quarters;
    double money1;
    screen.println("Empty your piggy bank and count the change, how many quarters ya have?: ");
    int q = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of quarters
    screen.println("How many dimes?: ");
    int d = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of dimes
    screen.println("How many nickels?: ");
    int n = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of nickels
    screen.println("How many pennies?: ");
    int p = (new Integer(keyboard.readLine())).intValue();//asks programmer friendly user to enter a number of pennies
    NumberFormat money = NumberFormat.getCurrencyInstance();
    money1 = (.25 * q) + (.1 * d) + (.05 * n) + (.01 * p);
    screen.println("You're rich! Total, you've got: " + money.format(money1));//finds and displays total money
    }P.S. To make the code formatted better put [ code ] before and [ /code ] after. It's not perfect, but a little better...

  • Totally New in Java - Please help!!

    Hi Dear all,
    l am totally new in Java, and l facing one problem,and really hope can get some help from yours,please!
    l need to write this program:
    The program should do the following:
    1. Input two fields: action (action: add / delete), and account number (any
    digit or character)
    2. if the action is "add" then the program adds one text line to a text
    file.
    "New account is <account number>"
    3. create the text file if it is not already exist (in c:\)
    4. When program runs again with new input values, a new line will be
    appended to the same file.
    5. if the action is "delete" then the program finds the record and removes
    the text line from the file.
    My problem is :
    l just know that l need to create the user interface first,but l don't know how to go on??
    Would you please show me some step how to solve these problem?
    Many many thanks!!
    BaoBao

    I don't know about Swing. I never use it.
    The stuff to create and manipulate files is in the java.io package.
    You'll probably want to use java.io.FileReader and java.io.FileWriter.
    Note that FileWriter has a constructor that lets you append and not overwrite.
    I'll start you off with a test.
    public class AccountListAddTest() {
      public static void main(String[] argv) {
        AccountList accts = new AccountList();
        accts.add("abcdefg12345"); // arg is a hypothetical account number
    }Write an AccountList class that'll work if you compile and run this test. After you run this test for the first time, the file should contain the string
    New account is abcdefg12345.
    This test assumes that the filename is hardcoded into the AccountList class. To keep it simple, make the add method create a new appending FileWriter each time, write, then close the writer.

  • M new to this forum + new to java please help me with file handling program

    hi i want to make a file handling program where in i want to input a text file say f1 whose style is mentioned as below
    aaa...bcd
    aaabbc
    acdce
    a..dd
    abbcd
    now i want to write d out put of file f1 to file f2 but only those string entries widout any ... in them how to do that :-(( please help :((

    import java.io.*;
    import java.lang.*;
    class javcsse{
             void javsce (){
              BufferedReader in;
            PrintWriter out;
            String line;
            try
                in = new BufferedReader(new FileReader("e:\\cntcs\\n7.txt"));
                out = new PrintWriter("e:\\cntcs\\n8.txt");
               line = in.readLine();
               while(line != null)
                     if(line.contains("...") && line.contains("....")){
                         break ;                
                         else{
                               if(line.contains("cc"))
                              System.out.println(line+"\n");
                                      out.println(line);
                    line = in.readLine();
                in.close();
                out.close();
            } catch (Exception ex)
                System.err.println(ex.getMessage());
      public class javcse{
        public static void main(String[] args) {
            new javcsse();
    }hey i wrote this code yet could u tell y is it still not working :((

  • I am new to java please help!!

    please help ive got a method thta i wanto to use it in another class, but it does not work.
    //prueba.java
    import java.io.*;
    public class prueba
    public int numero3;
    public int suma(int numero1,int numero2)
    int numero3=numero1+numero2;
    return numero3;
    //prueba1.java
    import javax.servlet.*;
    import java.io.*;
    import javax.servlet.http.*;
    import prueba;
    public class prueba1 extends HttpServlet
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    PrintWriter out = res.getWriter();
    int num1=1;
    int num2=1;
    prueba uno=new prueba();
    out.println(uno.suma(2,3));
    when i ty to complie this file it throws me thie errors:
    C:\resin-2.0.b2\doc\content-manager\admin\web-inf\classes\prueba1.java:4: cannot resolve symbol
    symbol: class prueba
    import prueba;
    ^
    C:\resin-2.0.b2\doc\content-manager\admin\web-inf\classes\prueba1.java:15: cannot resolve symbol
    symbol : class prueba
    location: class prueba1
    prueba uno=new prueba();
    ^
    C:\resin-2.0.b2\doc\content-manager\admin\web-inf\classes\prueba1.java:15: cannot resolve symbol
    symbol : class prueba
    location: class prueba1
    prueba uno=new prueba();
    ^
    3 errors
    Tool completed with exit code 1
    both , prueba1.java and prueba.java are in the same folder.

    C:\resin-2.0.b2\doc\content-manager\admin\web-inf\classes\prueba1.java:15: cannot resolve symbol
    symbol : class prueba
    location: class prueba1
         prueba uno=new prueba();
    ^
    C:\resin-2.0.b2\doc\content-manager\admin\web-inf\classes\prueba1.java:15: cannot resolve symbol
    symbol : class prueba
    location: class prueba1
         prueba uno=new prueba();
    ^
    2 errors

  • New to java, please help me :(

    hi, i have to complete a BMI calculator with arrays and switch, i need it so that if input a / b is selected it will calculate metric / imperial (i know that both calcs are the same, its just a placeholder for the time being). once thats selected users are asked to input name, age, height and weight, then looped again for another user to input into the array.
    once completed the name and age along with the BMI calculation for all the users that have inputted are displayed
    the problem is, the calculations are wrong, where it should be outputting a BMI of between 20-23ish im getting 0.3
    i think i had this problem when i done the switch example previously, but to fix that i just lumped all the code (inputs and calcs) into each case. in this method im guessing that would be an incorrect approach ?
    btw, sorry for my layout, ive been debugging for ages now and havnt had time to clean it up :/
    thank you in advance and heres my code:-
    package bmicalculationex;
    import javax.swing.*;
    public class Main {
    public static void main(String[] args) {
    String output;
    double Hfeet=0, Wstone=0, Hinches=0, Wlbs=0;
    String Hfeetstr, Wstonestr, Hinchesstr, Wlbsstr, age;
    String name;
    double bmiweight=0, bmiheight=0, BMI=0;
    Item[] myItemArray = new Item[2];
    for(int i = 0;i<2;i++){
    myItemArray[i] = new Item();
    String input = JOptionPane.showInputDialog(
    "Welcome to Chunks BMI calculator\n"+
    "a) Metric.\n"+
    "b) Imperial\n"+
    "q) Quit\n"+
    "\nPlease enter letter code" );
    char code = input.charAt(0);
    switch(code){
    case 'a':
    output= "Imperial.";
    Wlbs = Wlbs * 0.45359237;
    Hinches = Hinches * 0.0254;
    Hfeet = Hfeet * 0.3048;
    Wstone = Wstone * 6.35029318;
    break;
    case 'b': output= "Metric.";
    Wlbs = Wlbs * 0.45359237;
    Hinches = Hinches * 0.0254;
    Hfeet = Hfeet * 0.3048;
    Wstone = Wstone * 6.35029318;
    break;
    default: output= "Error.";
    JOptionPane.showMessageDialog(null,"Invalid Selection.\n"+ "Please try again.");
    JOptionPane.showMessageDialog(null, "You have selected :- " + output + "\n\n" +" Thank you.");
    //User In-
    for(int c=0;c<2;c++){
    name = JOptionPane.showInputDialog("enter your name");
    age = JOptionPane.showInputDialog("enter your age");
    Hfeetstr = JOptionPane.showInputDialog("enter your Height");
    Hinchesstr = JOptionPane.showInputDialog("enter the remainder");
    Wstonestr = JOptionPane.showInputDialog("enter your weight");
    Wlbsstr = JOptionPane.showInputDialog("enter the remainder");
    Hfeet = Float.parseFloat(Hfeetstr);
    Wstone = Float.parseFloat(Wstonestr);
    Hinches = Float.parseFloat(Hinchesstr);
    Wlbs = Float.parseFloat(Wlbsstr);
    bmiweight = Wstone + Wlbs;
    bmiheight = Hinches + Hfeet;
    BMI = bmiweight / (bmiheight*bmiheight);
    myItemArray[c].setname(name);
    myItemArray[c].setyear(age);
    myItemArray[c].setBMII(BMI);
    String message = "";
    for(int n=0;n<2;n++){
    message = message + "Name :- " + myItemArray[n].getname() + " " + "Age :- " + " " + myItemArray[n].getaged() + "BMI :- " + " " +myItemArray[n].getBMI() +"\n";
    JOptionPane.showMessageDialog(null, message);
    }//end of main method
    }//end of main class
    class Item{
    private String namea;
    private String agea;
    private double BMIa;
    public Item(){
    agea = "";
    BMIa = 0;
    namea = "";
    public Item(String nameb, String ageb, double BMIb){
    namea = nameb;
    agea = ageb;
    BMIa = BMIb;
    public String getname(){
    return namea;
    public String getaged(){
    return agea;
    public double getBMI(){
    return BMIa;
    public String setname (String nameb){
    namea = nameb;
    return nameb;
    public void setyear(String ageb){
    agea = ageb;
    public void setBMII(double BMIb){
    BMIa = BMIb;
    }

    yush !
    i done it :D
    i just ended up lumping all the code into each case like i did last time, as when i had the calculations outside of the cases it wasnt taking the values from inside the case. nevermind....
    another problem i do have though, i need a loop so that once the program finishes it repeats itself until an X is entered, im not very good with loops :S
    i tend to try it like this
    quit = 1;
    while (quit<2){
    then just have one of the cases as quit +1
    so in mine it looks liek this:
    int quit=1;
    while (quit<2){
    String input = JOptionPane.showInputDialog(
    "Welcome to Chunks BMI calculator\n"+
    "a) Metric.\n"+
    "b) Imperial\n"+
    "q) Quit\n"+
    "\nPlease enter letter code" );
    char code = input.charAt(0);
    switch(code){
    case 'a':
    JOptionPane.showMessageDialog(null, "You have selected imperial. "+"\n\n" +" Thank you.");
    for(int c=0;c<2;c++){
    name = JOptionPane.showInputDialog("enter your name");
    age = JOptionPane.showInputDialog("enter your age");
    Hfeetstr = JOptionPane.showInputDialog("enter your Height in feet");
    Hinchesstr = JOptionPane.showInputDialog("enter the remaining inches");
    Wstonestr = JOptionPane.showInputDialog("enter your weight in stone");
    Wlbsstr = JOptionPane.showInputDialog("enter the remaining lbs");
    Hfeet = Float.parseFloat(Hfeetstr);
    Wstone = Float.parseFloat(Wstonestr);
    Hinches = Float.parseFloat(Hinchesstr);
    Wlbs = Float.parseFloat(Wlbsstr);
    Wlbs = Wlbs * 0.45359237;
    Hinches = Hinches * 0.0254;
    Hfeet = Hfeet * 0.3048;
    Wstone = Wstone * 6.35029318;
    bmiweight = Wstone + Wlbs;
    bmiheight = Hinches + Hfeet;
    BMI = bmiweight / (bmiheight*bmiheight);
    String cat="";
    if (BMI <18.5) cat = ("Posh spice");
    else if (BMI >= 18.5 && BMI <=25) cat = ("Fit !");
    else if (BMI >25 && BMI <=30) cat = ("Fatty !");
    else if (BMI >30)cat = ("Super Fatty");
    myItemArray[c].setcat(cat);
    myItemArray[c].setname(name);
    myItemArray[c].setyear(age);
    myItemArray[c].setBMII(BMI);
    break;
    case 'b': output= "Metric.";
    etc.....
    this is causing me the problems:
    for(int i = 0;i<2;i++){
    myItemArray[i] = new Item();
    says a non static variable cannot be referenced from a static context, i know im being stupid with my implementation, but whats a better way ?
    thanks again :)
    Edited by: Clunk on Nov 17, 2008 4:05 PM

  • HI, I am new to java.Please tell me which is the latest version of Java

    Is Java SE7 the latest version of Java? Also, please tell me that what advantages it has compared to its previous version.

    0b5fc302-7c76-48af-be15-6146a99280a8 wrote:
    Is Java SE7 the latest version of Java? Also, please tell me that what advantages it has compared to its previous version.
    The Oracle Java download page has the answers to both of those questions.,
    http://www.oracle.com/technetwork/java/javase/downloads/index.html

  • New to Java RMI

    I am having problems with the following code that I am currently trying to understand RMI from Java head First, the following are meant to be part of an universal browser that the browser downloads and displays interactive Java GUIs. Can someone explain what I am doing wrong as I am still new to Java please?
    import java.awt.*;
    import javax.swing.*;
    import java.rmi.*;
    import java.awt.event.*;
    public class ServiceBrowser {
       JPanel mainPanel;
       JComboBox serviceList;
       ServiceServer server;
       public void buildGUI() {
          JFrame frame = new JFrame("RMI Browser");
          mainPanel = new JPanel();
          frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
          Object[] services = getServicesList();
          serviceList = new JComboBox(services);
          frame.getContentPane().add(BorderLayout.NORTH, serviceList);
          serviceList.addActionListener(new MyListListener());    
          frame.setSize(500,500);
          frame.setVisible(true);
       void loadService(Object serviceSelection) {
           try {
              Service svc = server.getService(serviceSelection);
              mainPanel.removeAll();
              mainPanel.add(svc.getGuiPanel());
              mainPanel.validate();
              mainPanel.repaint();
            } catch(Exception ex) {
               ex.printStackTrace();
       Object[] getServicesList() {
          Object obj = null;
          Object[] services = null;
          try {
              obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");   
         catch(Exception ex) {
           ex.printStackTrace();
         server = (ServiceServer) obj;
          try {
            services = server.getServiceList();
          } catch(Exception ex) {
             ex.printStackTrace();
         return services;
       class MyListListener implements ActionListener {
          public void actionPerformed(ActionEvent ev) {
              // do things to get the selected service
              Object selection =  serviceList.getSelectedItem();
              loadService(selection);
      public static void main(String[] args) {
         new ServiceBrowser().buildGUI();
    }I am able to compile the code but come up with the following error messages at runtime
    java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
         java.net.ConnectException: Connection refused
         at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:601)
         at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198)
         at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184)
         at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:322)
         at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
         at java.rmi.Naming.lookup(Naming.java:84)
         at ServiceBrowser.getServicesList(ServiceBrowser.java:53)
         at ServiceBrowser.buildGUI(ServiceBrowser.java:19)
         at ServiceBrowser.main(ServiceBrowser.java:82)
    Caused by: java.net.ConnectException: Connection refused
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
         at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
         at java.net.Socket.connect(Socket.java:529)
         at java.net.Socket.connect(Socket.java:478)
         at java.net.Socket.<init>(Socket.java:375)
         at java.net.Socket.<init>(Socket.java:189)
         at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:22)
         at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:128)
         at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:595)
         ... 8 more
    java.lang.NullPointerException
         at ServiceBrowser.getServicesList(ServiceBrowser.java:64)
         at ServiceBrowser.buildGUI(ServiceBrowser.java:19)
         at ServiceBrowser.main(ServiceBrowser.java:82)
    Exception in thread "main" java.lang.NullPointerException
         at javax.swing.DefaultComboBoxModel.<init>(DefaultComboBoxModel.java:53)
         at javax.swing.JComboBox.<init>(JComboBox.java:175)
         at ServiceBrowser.buildGUI(ServiceBrowser.java:21)
         at ServiceBrowser.main(ServiceBrowser.java:82)
    The code for the remote implementation compile and runs, but the other code for services compiles but come back with the following error message at runtime:
    Exception in thread "main" java.lang.NoSuchMethodError: main
    I have included one of the services code below this happens with:
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    public class DiceService implements Service {
        JLabel label;
        JComboBox numOfDice;
        public JPanel getGuiPanel() {
           JPanel panel = new JPanel();
           JButton button = new JButton("Roll 'em!");
           String[] choices = {"1", "2", "3", "4", "5"};
           numOfDice = new JComboBox(choices);
           label = new JLabel("dice values here");
           button.addActionListener(new RollEmListener());
           panel.add(numOfDice);
           panel.add(button);
           panel.add(label);
           return panel;
       public class RollEmListener implements ActionListener {
          public void actionPerformed(ActionEvent ev) {
             // roll the dice
             String diceOutput = "";
             String selection = (String)  numOfDice.getSelectedItem();
             int numOfDiceToRoll = Integer.parseInt(selection);
             for (int i = 0; i < numOfDiceToRoll; i++) {
                int r = (int) ((Math.random() * 6) + 1);
                diceOutput += (" " + r);
            label.setText(diceOutput);
    }

    how I do get suitable server running, can I not test the code on a local ip address first, i have included the remote implementation code below, can you advise how I can resolve this please or point me in the right direction?
    import java.rmi.*;
    import java.util.*;
    import java.rmi.server.*;
    public class ServiceServerImpl extends UnicastRemoteObject implements ServiceServer  {
        HashMap<String, Service> serviceList;
        public ServiceServerImpl() throws RemoteException {
           // start and set up services
           setUpServices();
       private void setUpServices() {
           serviceList = new HashMap<String, Service>();
           serviceList.put("Dice Rolling Service", new DiceService()); 
           serviceList.put("Day of the Week Service", new DayOfTheWeekService()); 
           serviceList.put("Visual Music Service", new MiniMusicService());  
        public Object[] getServiceList() {
           System.out.println("in remote");
           return serviceList.keySet().toArray();
        public Service getService(Object serviceKey) throws RemoteException {       
           Service theService = (Service) serviceList.get(serviceKey);      
           return theService;
        public static void main (String[] args) {
           try {
             Naming.rebind("ServiceServer", new ServiceServerImpl());
            } catch(Exception ex) { }
            System.out.println("Remote service is running");
    }

  • New to Java and need help with this program..please!

    I'd really appreciate any helpful comments about this program assignment that I have to turn in a week from Friday. I'm taking a class one night a week and completely new to Java. I'd ask my professor for help, but we can't call him during the week and he never answers e-mails. He didn't tell us how to call from other classes yet, and I just can't get the darn thing to do what I want it to do!
    The assignment requirements are:
    1. Change a card game application that draws two cards
    and the higher card wins, to a Blackjack application
    2. Include a new class called Hand
    3. The Hand class should record the number of draws
    4. The application should prompt for a number of draws
    5. The game is played against the Dealer
    6. The dealer always draws a card if the dealer's hand total is <= 17
    7. Prompt the player after each hand if he wants to quit
    8. Display the total games won by the dealer and total and the total games wond by the player after each hand
    9. Display all of the dealer's and player's cards at the
    end of each hand
    10. Player has the option of drawing an additional card after the first two cards
    11. The Ace can have a value of 11 or 1
    (Even though it's not called for in the requirements, I would like to be able to let the Ace have a value of 1 or an 11)
    The following is my code with some comments about a few things that are driving me nuts:
    import java.util.*;
    import javax.swing.*;
    import java.text.*;
    public class CardDeck
    public CardDeck()
    deck = new Card[52];
    fill();
    shuffle();
    public void fill()
    int i;
    int j;
    for (i = 1; i <= 13; i++)
    for (j = 1; j <= 4; j++)
    deck[4 * (i - 1) + j - 1] = new Card(i, j);
    cards = 52;
    public void shuffle()
    int next;
    for (next = 0; next < cards - 1; next++)
    int rand = (int)(Math.random()*(next+1));
    Card temp = deck[next];
    deck[next] = deck[rand];
    deck[rand] = temp;
    public final Card draw()
    if (cards == 0)
    return null;
    cards--;
    return deck[cards];
    public int changeValue()
    int val = 0;
    boolean ace = false;
    int cds;
    for (int i = 0; i < cards; i++)
    if (cardValue > 10)
    cardValue = 10;
    if (cardValue ==1)     {
    ace = true;
    val = val + cardValue;
    if ( ace = true && val + 10 <= 21 )
    val = val + 10;
    return val;
    public static void main(String[] args)
    CardDeck d = new CardDeck();
    int x = 3;
    int i;
    int wins = 1;
    int playerTotal = 1;
    do {
    Card dealer = (d.draw());
    /**I've tried everything I can think of to call the ChangeValue() method after I draw the card, but nothing is working for me.**/
    System.out.println("Dealer draws: " + dealer);
    do {
    dealer = (d.draw());
    System.out.println(" " + dealer);
    }while (dealer.rank() <= 17);
    Card mine = d.draw();
    System.out.println("\t\t\t\t Player draws: "
    + mine);
    mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
    do{
    String input = JOptionPane.showInputDialog
    ("Would you like a card? ");
    if(input.equalsIgnoreCase("yes"))
         mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
         playerTotal++;
         else if(input.equalsIgnoreCase("no"))
    System.out.println("\t\t\t\t Player stands");
         else
    System.out.println("\t\tInvalid input.
    Please try again.");
    I don't know how to go about making and calling a method or class that will combine the total cards delt to the player and the total cards delt to the dealer. The rank() method only seems to give me the last cards drawn to compare with when I try to do the tests.**/
    if ((dealer.rank() > mine.rank())
    && (dealer.rank() <= 21)
    || (mine.rank() > 21)
    && (dealer.rank() < 22)
    || ((dealer.rank() == 21)
    && (mine.rank() == 21))
    || ((mine.rank() > 21)
    && (dealer.rank() <= 21)))
    System.out.println("Dealer wins");
    wins++;
         else
    System.out.println("I win!");
    break;
    } while (playerTotal <= 1);
    String stop = JOptionPane.showInputDialog
    ("Would you like to play again? ");
    if (stop.equalsIgnoreCase("no"))
    break;
    if (rounds == 5)
    System.out.println("Player wins " +
    (CardDeck.rounds - wins) + "rounds");
    } while (rounds <= 5);
    private Card[] deck;
    private int cards;
    public static int rounds = 1;
    public int cardValue;
    /**When I try to compile this nested class, I get an error message saying I need a brace here and at the end of the program. I don't know if any of this code would work because I've tried adding braces and still can't compile it.**/
    class Hand()
    static int r = 1;
    public Hand() { CardDeck.rounds = r; }
    public int getRounds() { return r++; }
    final class Card
    public static final int ACE = 1;
    public static final int JACK = 11;
    public static final int QUEEN = 12;
    public static final int KING = 13;
    public static final int CLUBS = 1;
    public static final int DIAMONDS = 2;
    public static final int HEARTS = 3;
    public static final int SPADES = 4;
    public Card(int v, int s)
    value = v;
    suit = s;
    public int getValue() { return value; }
    public int getSuit() { return suit;  }
    public int rank()
    if (value == 1)
    return 4 * 13 + suit;
    else
    return 4 * (value - 1) + suit;
    /**This works, but I'm confused. How is this method called? Does it call itself?**/
    public String toString()
    String v;
    String s;
    if (value == ACE)
    v = "Ace";
    else if (value == JACK)
    v = "Jack";
    else if (value == QUEEN)
    v = "Queen";
    else if (value == KING)
    v = "King";
    else
    v = String.valueOf(value);
    if (suit == DIAMONDS)
    s = "Diamonds";
    else if (suit == HEARTS)
    s = "Hearts";
    else if (suit == SPADES)
    s = "Spades";
    else
    s = "Clubs";
    return v + " of " + s;
    private int value; //Value is an integer, so how can a
    private int suit; //string be assigned to an integer?
    }

    Thank you so much for offering to help me with this Jamie! When I tried to call change value using:
    Card dealer = (d.changeValue());
    I get an error message saying:
    Incompatible types found: int
    required: Card
    I had my weekly class last night and the professor cleared up a few things for me, but I've not had time to make all of the necessary changes. I did find out how toString worked, so that's one question out of the way, and he gave us a lot of information for adding another class to generate random numbers.
    Again, thank you so much. I really want to learn this but I'm feeling so stupid right now. Any help you can give me about the above error message would be appreciated.

  • New to Java. Want to write a simple applet for a mobile phone.

    Hello,
    I want to write a simple java applet for a mobile phone. currently I am in the stage of thinking about whether this is possible in a timeframe of about a month. I have very little java experience from a while back so I'm pretty much starting from scratch.
    All I want is an applet that lets you send 2 or 3 variables to an online server. The server will then reposition telescopes.
    All i'm concerned with is the mobile phone part, which doesn't have to be secure or impressive. Just a simple interface.
    Ideally it should work on my nokia 6070, which occording to the official specs has the following java technology:
    MIDP 2.0
    CLDC 1.1
    JSR 120 Wireless Messaging API
    JSR 135 Mobile Media API
    Nokia UI API
    (I don't know what any of this means but am a good learner).
    Can anyone offer me any advice? Is this possible in my timeframe? where should I start? I need a editor and compiler also (I'm using windows XP).
    Many thanks and kind regards,
    Jason

    Actually it is working on my phone now.
    I changed the target platform in the wireless toolkit settings to MIDP 1.0
    Now to create the fields coordinate fields etc. I don't have much of a clue really.
    Current I have:
    import java.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class AtmosMIDlet extends MIDlet implements CommandListener
    Form WelcomeForm = new Form("AtmosMIDlet");
    StringItem WelcomeMes = new StringItem(null, "Please enter coordinates:");
    TextField Longitude = new TextField("Longitude", "", 3, TextField.NUMERIC);
    TextField Lattitude = new TextField("Lattitude", "", 3, TextField.NUMERIC);
    public AtmosMIDlet()
    try
    ImageItem logo = new ImageItem(Image.createImage("/logo.png"));
    WelcomeForm.append(logo);
    catch (java.io.IOException x)
    throw new RuntimeException ("Image not found");
    WelcomeForm.append(WelcomeMes);
    WelcomeForm.append(Longitude);
    WelcomeForm.append(Lattitude);
    WelcomeForm.addCommand(new Command("Exit", Command.EXIT, 0));
    WelcomeForm.setCommandListener(this);
    public void startApp()
    Display.getDisplay(this).setCurrent(WelcomeForm);
    public void pauseApp() {}
    public void destroyApp(boolean unconditional) {}
    public void commandAction(Command c, Displayable s)
    notifyDestroyed();
    I'm trying to get the image logo.png to display at the top but I get the error:
    C:\WTK25\apps\AtmosSpec\src\AtmosMIDlet.java:19: cannot find symbol
    symbol : constructor ImageItem(javax.microedition.lcdui.Image)
    location: class javax.microedition.lcdui.ImageItem
    ImageItem logo = new ImageItem(Image.createImage("/logo.png"));
    ^
    1 error
    com.sun.kvem.ktools.ExecutionException
    Build failed
    When I try to build.. Any help would be great.
    Ideally the image would be on a seperate screen for a couple of seconds.

  • Hi. I brought a new iphone 5 and I wanted to restore it to one of my previous iclouds but it's not letting me - the icloud backup is a iphone 5 6.1 ios and my current is iphone 6.0.1 - please advise what i should do...

    Hi. I brought a new iphone 5 and I wanted to restore it to one of my previous iclouds but it's not letting me - the icloud backup is a iphone 5 6.1 ios and my current is iphone 6.0.1 ios - please advise what i should do...

    Hi ldyazch,
    You will need to set it up as a new phone, not from a backup, first. Then, after setup is complete, go to Settings > General > Software Update. Make sure you are connected to Wi-Fi and have at least 50% battery power. After then update downloads and installs, you can go to Settings > General > Reset > Erase All Content and Settings.
    This will let you go through the setup again, and this time you can choose your backup.

  • Hello everyone!  i have a new macbook pro and i want to download aperture.  my app store says it is already installed (on my old macbook pro).  how do i install aperture from the app store in this instance please?

    hello everyone!  i have a new macbook pro and i want to download aperture.  my app store says it is already installed (on my old macbook pro).  how do i install aperture from the app store in this instance please?

    Are yoy sure that Apeture is not in the Applications folder of the new system? If it is move it to the trash and the App Store will let you download Aperture from it.
    You will need to make sure you use the same Apple ID you used to purchase it in the past.
    regards

  • Hi, please help with the installation of Lightroom 4, I bought a new Mac (Apple) and I want to install a software that I have on the album cd. My new computer does not have the drives. Can I download software from Adobe? Is my license number just to be ab

    Hi, please help with the installation of Lightroom 4, I bought a new Mac (Apple) and I want to install a software that I have on the album cd. My new computer does not have the drives. Can I download software from Adobe? Is my license number just to be able to download the srtony adobe.

    Adobe - Lightroom : For Macintosh
    Hal

Maybe you are looking for

  • Jstack shows a thread waiting for monitor entry but it's already acquired

    I have a heavy load website powered by tomcat-6.0.14 and jdk1.6.0_02-b05(amd64) on a 2 dual-core amd Opteron. When tomcat started, and I directed the http request(~200/s) abruptly to tomcat, it looks choked for over one minute, and if I took off the

  • Upgraded to Mavericks - System errors popping up in /private/var/tmp ... Help!!

    Hi there, Ever since I upgraded to Mavericks, and installed my standard software, I'm getting some odd behaviour. Every so often (no discernable pattern so far) my Finder pops up with a new window in /private/var/tmp.  There is a huge system stacktra

  • Help plz regarding array and DB

    hi , i have a problem regarding sorting. I have 1 million records in my DB table. When i open my swing application i sort the records in table [ORDER BY col1,col3,col4] like that and want that order record ids . upto here no problem.i am getting the

  • Third part PR & PO - for structured article (BOM containing LEER article)

    We have an interesting case: Our article masters are as follows: VOLL (main article) has sales order and purchase order unit CAR, while base unit of measure is PC. This VOLL article has a LEER component (BOM) article defined in it. The BOM component

  • Release strategy for PREQs created from PM work order

    Hi All, I have an issue with determining  release strategy for purchase requisition for external services created via PM work order (iw31 transaction). We have activated release strategy for Purchase requisition based on the following characteristics