Simple array program help

Hello could I please have some hints as to how to get this program working e.g. would it better to use a while loop for this? and how would I make the program stop when it has read 100 names?
cheers anyone
import java.util.*;
import java.io.*;
* The problem with files is generally you don`t know how many values
* are in there. Develop a program to read names from a file - it carries
* on and reads names until either 100 is reached or there is no more
* data in the file. Display all the names read in together with the
* count of how many names have been read.
class Names100
     public void process (String[] argStrings)throws Exception
          int namesRead = 0;
          Scanner sc = new Scanner(new File("names.txt"));
          String[] namesArray = new String[100];
          for(int i = 0; i <= 100; i++)
               namesArray[i] = sc.next();
               System.out.println(namesArray);
               namesRead++;
          System.out.println();
          System.out.println("Names read: " + namesRead);
          sc.close();

> Thanks, the way that I have been taught at UNI means
that I have a separate file called names100App (this
is used to run the program).
Ok, I understand.
> The scanner is to get
the content of the file although I could have used
other things I guess.
Yes, but the Scanner class is mighty handy.
> Also I will check out what you said.
>
cheers
John
Good, and while you're at it, take a look at the ArrayList class (resizable-array implementation):
http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html
Good luck.

Similar Messages

  • Need Help with simple array program!

    Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
    What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
    Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
    import B102.*;
    class Letters
         static int GetSize()
              int size = 0;
              boolean err = true;
              while(err == true)
                   Screen.out.println("How Many Letters would you like to read in?");
                   size = Keybd.in.readInt();
                   err = Keybd.in.fail();
                   Keybd.in.clearError();
                   if(size <= 0)
                        err = true;
                        Screen.out.println("Invalid Input");
              return(size);
         static char[] ReadInput(int size)
              char input;
              char[] letter = new char[size];
              for(int start = 1; start <= size; start++)
                   System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                   input = Keybd.in.readChar();
                   while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
                        Screen.out.println("Invalid Input");
                        System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                        input = Keybd.in.readChar();
                                    while(input == '#')
                                                 start == size;
                                                 break;
                   for(int i = 0; i < letter.length; i++)
                        letter[i] = input;
              return(letter);
         static int CountA(char[] letter)
              int acount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'a')
                        acount++;
              return(acount);
         static int CountB(char[] letter)
              int bcount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'b')
                        bcount++;
              return(bcount);
         static int CountC(char[] letter)
              int ccount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'c')
                        ccount++;
              return(ccount);
         static int SearchA(char[] letter)
              int ia;
              for(ia = 0; ia < letter.length; ia++)
                   if(letter[ia] == 'a')
                        return(ia);
              return(ia);
         static int SearchB(char[] letter)
              int ib;
              for(ib = 0; ib < letter.length; ib++)
                   if(letter[ib] == 'b')
                        return(ib);
              return(ib);
         static int SearchC(char[] letter)
              int ic;
              for(ic = 0; ic < letter.length; ic++)
                   if(letter[ic] == 'c')
                        return(ic);
              return(ic);
         static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
              if(ia <= 1)
                   System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
              else
                   System.out.println("There are no a's found");
              if(ib <= 1)
                   System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
              else
                   System.out.println("There are no b's found");
              if(ic <= 1)
                   System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
              else
                   System.out.println("There are no c's found");
              return;
         public static void main(String args[])
              int size;
              char[] letter;
              int acount;
              int bcount;
              int ccount;
              int ia;
              int ib;
              int ic;
              size = GetSize();
              letter = ReadInput(size);
              acount = CountA(letter);
              bcount = CountB(letter);
              ccount = CountC(letter);
              ia = SearchA(letter);
              ib = SearchB(letter);
              ic = SearchC(letter);
              PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
              return;
    }     Some errors i get with my program are:
    When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
    Example Testing: How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): b
    Enter letter (a, b or c) (# to quit): c
    It prints "There are no a's'" (there should be 1 a at index 0)
    "There are no b's" (there should be 1 b at index 1)
    and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
    The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
    Example Testing:How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): #
    It prints "There are no a's'" (should have been 1 a at index 0)
    "There are no b's"
    and "There are no c's"
    Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
    Thanks
    lou87.

    Without thinking too much...something like this
    for(int start = 0; start < size; start++) {
                System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                input = Keybd.in.readChar();
                while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
                    Screen.out.println("Invalid Input");
                    System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                    input = Keybd.in.readChar();
                if(input == '#') {
                        break;
                letter[start] = input;
            }you dont even need to do start = size; coz with the break you go out of the for loop.

  • Help with simple array program

    my program compiles and runs but when after i enter in 0 it says that the total cost is 0.0 any help would be great thanks
    /**Write a program that asks the user for the price and quantity of up to 10 items. The program accepts input until the user enters a price of 0. 
    *The program applies a 7% sales tax and prints the total cost.
    Sample
    Enter price 1:
    1.95
    Enter quantity 1:
    2
    Enter price 2:
    5.00
    Enter quantity 2:
    1
    Enter price 3:
    0
    Your total with tax is 9.52
    import java.util.*;
    public class Cashregister
    static Scanner input = new Scanner(System.in);
    static double userinput = 1;
    public static void main(String[] args)
      int anykey;
      int howmanyproducts;
      System.out.println("This Program will allow you to enter the price and quanity of a set of items until you press zero, and after you press zero it will put the tax on it and give you the subtotal.");
      int whichproduct = 1;//used to say what
      int whichquanity = 1;
      double beforetax = 0;
      double aftertax = 0;
      double [] finalproduct = new double [9];
      double [] finalquant = new double[9];
      double [] finalanswer = new double[9];
      double taxrate = .07;
      int index = 0;
      while(userinput !=0)
       System.out.println("Enter price " + whichproduct + ":");
       userinput = input.nextDouble();
       whichproduct ++;
       if(userinput != 0)
       finalproduct[index] = userinput;
       System.out.println("Enter quanity " + whichquanity + ":");
       userinput = input.nextInt();
       finalquant[index] = userinput;
       whichquanity ++;
       index ++;
      else
      int [] indecies = new int [index];//used for array.length purposes
       for(int j = 0; j<indecies.length; j++)
         finalanswer[index] = finalproduct[index] * finalquant[index];
      for(int k = 0; k < indecies.length; k++)
         finalanswer[k] = finalanswer[k] + finalanswer[k];
         beforetax = finalanswer[k];
         aftertax = beforetax * taxrate;
      System.out.println("The total cost with tax will be $" + aftertax);
    }

    I tried ot indent better so it is more readable and i removed the tax out of my loop along with another thing i knew wasnt supposed to be their. Ran it again and i still got the same total coast = 0.0
    import java.util.*;
    public class Cashregister
    static Scanner input = new Scanner(System.in);
    static double userinput = 1;
    public static void main(String[] args)
      int anykey;
      int howmanyproducts;
      System.out.println("This Program will allow you to enter the price and quanity of a set of items until you press zero, and after you press zero it will put the tax on it and give you the subtotal.");
      int whichproduct = 1;
      int whichquanity = 1;
      double beforetax = 0;
      double aftertax = 0;
      double [] finalproduct = new double [9];
      double [] finalquant = new double[9];
      double [] finalanswer = new double[9];
      double taxrate = .07;
      int index = 0;
      while(userinput !=0)
       System.out.println("Enter price " + whichproduct + ":");
       userinput = input.nextDouble();
       whichproduct ++;
            if(userinput != 0)
                    finalproduct[index] = userinput;
                    System.out.println("Enter quanity " + whichquanity + ":");
                    userinput = input.nextInt();
                    finalquant[index] = userinput;
                    whichquanity ++;
                    index ++;
            else
                    int [] indecies = new int [index];
                    for(int j = 0; j<indecies.length; j++)
                            finalanswer[index] = finalproduct[index] * finalquant[index];
                    for(int k = 0; k < indecies.length; k++)
                           finalanswer[0] = finalanswer[k] + finalanswer[k];
                    beforetax = finalanswer[0];
                    aftertax = beforetax * taxrate;
                    System.out.println("The total cost with tax will be $" + aftertax);
    }

  • Java 2D array program help please?

    Hi - I'm teaching computer science to myself (java, using jGRASP) using some websites online, and one of the activities I have to do is to make an "image smoother" program.
    I just started learning about 2D array, and I think I get what it is (based on what I know of 1D arrays), but I have no clue how to do this activity.
    This is what the description says:
    "A grey-level image is sometimes stores as a list of int values. The values represent the intensity of light as discrete positions in the image.
    An image may be smoothed by replacing each element with the average of the element's neighboring elements.
    Say that the original values are in the 2D array "image". Compute the smoothed array by doing this: each value 'smooth[r][c]' is the average of nine values:
    image [r-1][c-1], image [r-1][c ], image [r-1][c+1],
    image [r ][c-1], image [r ][c ], image [r ][c+1],
    image [r+1][c-1], image [r+1][c ], image [r+1][c+1].
    Assume that the image is recangular, that is, all rows have the same number of locations. Use the interger arithmetic for this so that the values in 'smooth' are integers".
    and this is what the website gives me along with the description above:
    import java.io.*;
    class Smooth
    public static void main (String [] args) throws IOException
    int [][] image = {{0,0,0,0,0,0,0,0,0,0,0,0,},
    {0,0,0,0,0,0,0,0,0,0,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,0,0,0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0,0,0,0,0}};
    //assume a rectangular image
    int[][] smooth = new int [image.length][image[0].length];
    //compute the smoothed value for
    //non-edge locations in the image
    for (int row=1; row<image.length-1; row++)
    for (int col=1; col<image[row].length-1; col++)
    smooth[row][col] = sum/9;
    //write out the input
    //write out the result
    "The edges of the image are a problem because only some of the nine values that go into the average exist. There are various ways to deal with this problem:
    1. Easy (shown above): Leave all the edge locations in the smoothed image to zero. Only inside locations get an averaged value from the image.
    2. Harder: Copy values at edge locations directly to the smoothed image without change.
    3. Hard: For each location in the image, average together only those of the nine values that exist. This calls for some fairy tricky if statements, or a tricky set of for statements inside the outer two.
    Here is a sample run of the hard solution:
    c:\>java ImageSmooth
    input:
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    output:
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 1 1 1 1 1 1 1 1 0 0
    0 1 2 3 3 3 3 3 3 2 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 2 3 3 3 3 3 3 2 1 0
    0 0 1 1 1 1 1 1 1 1 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    c:\>"
    OKAY that was very long, but I'm a beginner to java, especially to 2D arrays. If anyone could help me with this step-by-step, I would greatly appreciate it! Thank you very much in advance!

    larissa. wrote:
    I did try, but I have no clue where to start from. That's why I asked if someone could help me with this step by step...regardless, our track record for helping folks who state they are "completely lost" or "don't have a clue" is poor to dismal as there is only so much a forum can do in this situation. We can't put knowledge in your head; only you can do that. Often the best we can do is to point you to the most basic tutorials online and suggest that you start reading.
    That being said, perhaps we can help you if you have some basic knowledge here, enough to understand what we are suggesting, and perseverance. The first thing you need to do is to try to create this on your own as best you can, then come back with your code and with specific questions (not the "I'm completely lost" kind) that are answerable in the limited format of a Java forum. By posting your code, we can have a better idea of just where you're making bad assumptions or what Java subjects you need to read up on in the tutorials.

  • Supermarket Array program help!

    class Supermarket {
        double[] profit;
        String[] city;
        String[] aboveAverage;
        double average,deviation;
        double list[], lenght;
        Supermarket(String[] thisCity, double[] thisProfit)
       city = thisCity;
       profit = thisProfit;
        @Override
    public String toString(){
            return "City" + '\t' + "Profit" + '\n' + city + '\t' + profit + 'n';
        public double getSum()
            double sum = 0;
            for(int i = 0; i < profit.length; i++)
                sum = sum + profit;
    return sum;
    public double average()
    return getSum()/profit.length;
    public String aboveAverage()
    String s = "";
    double avg = average();
    for(int i = 0; i < profit.length; i++)
    if(profit[i] > avg)
    s = city[i] + "" + profit[i] + '\n';
    return s;
    public double getDeviation()
    double sumdifference = 0;
    double mean = average();
    for(int i = 0; i < profit.length; i++)
    sumdifference = sumdifference + Math.pow((profit[i]- 1), mean);
    return Math.sqrt(sumdifference/profit.length);
    public double findhighValue()
    double highestValue = profit[0];
    for(int i = 1; i < profit.length; i++)
    if(profit[i] > highestValue )
    highestValue = profit[i];
    return highestValue;
    public double findlowestValue()
    double lowestValue = profit[0];
    for(int i = 1; i > profit.length; i++)
    if(profit[i] > lowestValue)
    lowestValue = profit[i];
    return lowestValue;
    public String barGraph()
    String s = "";
    for(int i = 0; i < profit.length; i++)
    s = s + city[i] + "";
    int x = (int)Math.floor(profit[i]);
    for(int j = 1; j <= i; j++)
    s = s + "*";
    s = s + '\n';
    return s;
    public int findPosition(int startfrom)
    int position = startfrom;
    for(int i = startfrom + 1; 1 < profit.length; i++)
    if(profit[i] < profit[position])
    position = i;
    return position;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Locale;
    class TestSupermarket
    public static void main(String arg[])
    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern("0.00");
    Locale local = Locale.US;
    NumberFormat cf = NumberFormat.getCurrencyInstance(local);
    double profit[] = {10200000, 14600000, 17000000, 6700000, 3600000, 9100000};
    String city[] = {"Miami", "Sunrise", "Hollywood", "Tallahassee", "Jacksonville", "Orlando"};
    System.out.println("Millions in revenue " + profit + city);
    Supermarket n = new Supermarket(city, profit);
    System.out.println("Average of profits " + cf.format(n.getSum()));
    System.out.println("\nThe average " + cf.format(n.average()));
    System.out.println("\nthe highest value " + cf.format(n.findhighValue()));
    System.out.println("\nthe lowest value " + cf.format(n.findlowestValue()));
    System.out.println("\nbargraph\t " + n.barGraph());
    System.out.println("\ndeviation " + n.getDeviation());
    System.out.println("\nposition " + n.aboveAverage());
    I'm still having some issues. 
    1st - Deviation calculation seems wrong, as it produces infinite.
    2nd -?     A horizontal bar graph showing the performance for each city, to the nearest million dollars.  Not sure how to produce that.
    3rd - ?     List in descending order of profit, the cities and their respective profit.
    I'm still working on this situation, but help is appreciated if you can set me to the right path.  Producing the array bar is the problem I'm mainly having.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I offered to help him stated at my last post in his topic. Different people, not sure how to prove we're different people other than IP check. He didn't need to produce "origin"city. Just the two arrays of Profit and city. I went ahead and develop a test class to test out the input.

  • Simple switch program help

    I'm trying to prompt the user for a pattern they would like to see, then display the pattern.
    Here is the code I have:
    import java.util.Scanner;
    public class AsteriskPatterns
         public static void main (String[] args)
              char choice;
              Scanner scan = new Scanner (System.in);
              System.out.println ("Enter the pattern would you like to see a, b, c, or d: ");
              choice = scan.nextChar();
              switch (choice)
                   case a:
                        System.out.println ("**********");
                        System.out.println ("*********");
                        System.out.println ("********");
                        System.out.println ("*******");
                        System.out.println ("******");
                        System.out.println ("*****");
                        System.out.println ("****");
                        System.out.println ("***");
                        System.out.println ("**");
                        System.out.println ("*");
                        break;
                   case b:
                        System.out.println ("         *");
                        System.out.println ("        **");
                        System.out.println ("       ***");
                        System.out.println ("      ****");
                        System.out.println ("     *****");
                        System.out.println ("    ******");
                        System.out.println ("   *******");
                        System.out.println ("  ********");
                        System.out.println (" *********");
                        System.out.println ("**********");
                        break;
                   case c:
                        System.out.println ("**********");
                        System.out.println (" *********");
                        System.out.println ("  ********");
                        System.out.println ("   *******");
                        System.out.println ("    ******");
                        System.out.println ("     *****");
                        System.out.println ("      ****");
                        System.out.println ("       ***");
                        System.out.println ("        **");
                        System.out.println ("         *");
                        break;
                   case d:
                        System.out.println ("     *    ");
                        System.out.println ("    ***   ");
                        System.out.println ("   *****  ");
                        System.out.println ("  ******* ");
                        System.out.println (" *********");
                        System.out.println (" *********");
                        System.out.println ("  ******* ");
                        System.out.println ("   *****  ");
                        System.out.println ("    ***   ");
                        System.out.println ("     *    ");
                        break;
                   default:
                        System.out.println ("You didn't enter a valid choice!");
    }I'm getting 5 errors when I try to compile?
    AsteriskPatterns.java:15: cannot find symbol
    symbol : method nextChar()
    location : class java.util.Scanner
    choice = scan.nextChar();
    ^
    Then 4 errors under my switch command saying:
    cannot find symbol
    symbol : variable a, b, c, and d
    location: case a, case b, case c, and case d
    Any help would be greatly appreciated

    AsteriskPatterns.java:15: cannot find symbol
    symbol : method nextChar()
    location : class java.util.Scanner
    choice = scan.nextChar();
    cannot find symbol means there is no such method. Check for yourself: Scanner does not have a nextChar method:
    [http://java.sun.com/javase/6/docs/api/java/util/Scanner.html]
    As for you other errors, you need to write
    case 'a':not
    case a:

  • Simple Array Question - Help Needed!

    Hey people,
    I need a line of code that gets the maximum value out of an array.
    the array is called LEVELS and contains values [1, 3, 4, 17, 3, 2, 4]. I need a line of code that creates a new variable called MAXLEVEL and finds the largest value within the array.
    Thanks,
    sean :)

    Create a variable. Initialize it to the lowest possible value, like say Integer.MIN_VALUE.
    Loop through your array.
    For each element, see if it's greater than the current value in the variable. If it is, use it.
    When you reach the end of the array, the variable now holds the max value.
    How did you think you were going to do it?

  • Help with a simple Java program

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

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

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Need help on with simple email program

    i have been set a task to create a simple email program that has the variables of the sender the recipient the subject the content and a date object representing when the email was sent (this is just to be set to the current system date)
    It also needs to include a constructor with four String arguments, i.e the sender, receiver, subject and content. The constructor has to initialise the date of the email then transfer the values of the input parameters to the relevant attributes. If any values of the strings aren'nt given, the string �Unknown� should be set as the value.
    I was given a java file to test the one i am to create, but some of the values are not given, if anyone could be of anyhelp or just point me in the right direction then i would be very greatfull, ive posted the code for the test file i have been given below, thanks.
    public class SimpleEmailTest {
         public static void main( String[] args ) {
              SimpleEmail email;     // email object to test.
              String whoFrom;          // sender
              String whoTo;          // recipient
              String subject;          // subject matter
              String content;          // text content of email
              static final String notKnown = "Unknown";
              email = new SimpleEmail
    (notKnown, notKnown, notKnown, notKnown);
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
              email.setSender( "Jimmy Testsender");
              email.setRecipient( "Sheena Receiver");
              email.setSubject( "How are you today?");
              email.setContent( "I just wrote an email class!");
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
         }

    Start by writing a class named SimpleEmail, implement a constructor with four arguments in it, and the methods that the test code calls, such as the get...() and set...() methods. The class probably needs four member variables too.
    public class SimpleEmail {
        // ... add member variables here
        // constructor
        public SimpleEmail(String whoFrom, String whoTo, String subject, String content) {
            // ... add code to the constructor here
        // ... add get...() and set...() methods here
    }

  • Simple arrays

    hi,
    I am having difficulties with this very simple array (following). I want to store data through a while loop which is why I tried with a very simple example. And it doesn't work. The data is erased every loop, and i must set the dimension of the array (100 for this example) to get something or my array stays at 0... but I won't know it in my VI.
    Thanks for the help!
    Solved!
    Go to Solution.

    Since you are using Replace array element the element needs to exist prior to rewriting the element.
    Here are two examples in on shot:
    The upper one uses autoindexing, this has the disadvantage that you don't have the data until the loop is finished.
    The lower one uses append array element and feedback notes.
    Ton
    Message Edited by TonP on 06-29-2009 11:24 AM
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!
    Attachments:
    AppendAutoIndex.png ‏3 KB

  • "Assertion failed" error when executing a simple UCI program

    I am using a simple UCI program (tt1.c) with Xmath version 7.0.1 on Sloaris 2.8 that performs the followings:
    - Start Xmath701
    - Sleep 10 Seconds
    - Load a sysbuild model
    - Stop Xmath
    I am calling the uci executable using the following command:
    > /usr/local/apps/matrixx-7.0.1/bin/xmath -call tt1 &
    In this way everything works fine and the following printouts from the program are produced.
    --------- uci printout ----------
    ## Starting Xmath 701
    ## sleep 10 seconds
    ## load "case_h_cs_ds.xmd";
    ## Stopping Xmath 701
    All the processes (tt1, XMATH, xmath_mon, and sysbld) terminate correctly.
    The problem occurs if the 10 second wait after starting xmath is omitted:
    - Start Xmath701
    - Load a sysbuild model
    - Stop Xmath
    This results to the following printouts:
    --------- uci printout ----------
    ## Starting Xmath 701
    ## load "case_h_cs_ds.xmd";
    Assertion failed: file "/vob1/xm/ipc/ipc.cxx", line 420 errno 0.
    Note that the last line is not produced by the uci program and the tt1 did not
    finish (the printout before stopping xmath "## Stopping Xmath 701" was
    not produced).
    A call to the unix "ps -ef" utility shows that none of the related process has been terminated:
    fs085312 27631 20243 0 10:45:29 pts/27 0:00 tt1
    fs085312 27643 1 0 10:45:30 ? 0:00 /usr/local/apps/matrixx-7.0.1/solaris_mx_70.1/xmath/bin/xmath_mon /usr/local/app
    fs085312 27641 27631 0 10:45:30 ? 0:01 /usr/local/apps/matrixx-7.0.1/solaris_mx_70.1/xmath/bin/XMATH 142606339, 0x8800
    fs085312 25473 25446 0 10:45:33 ? 0:01 sysbld ++ 19 4 7 6 5 8 9 0 25446 ++
    The questions are as follows:
    1- What is "Assertion failed: file "/vob1/xm/ipc/ipc.cxx", line 420 errno 0" and why is that produced?
    2- Should the UCI program waits for end of sysbld initialization before issuing commands?
    3- If the answer to the above question is yes, is there a way to check the termination of sysbld initialization?
    Thanks in advance for you help.
    Attachments:
    tt1.c ‏1 KB

    I tracked down the problem and it is a race condition between the many processes being started up. A smaller delay should also solve the problem. Or, maybe do something else before the first 'load'. The 'load' command tries to launch systembuild and causes the race condition.

  • Weblogic error while deplying a simple servlet program

    Hi This is a very simple servlet program.
    I am trying to deploy it on the weblogic server but i get this error as follow
    Unable to access the selected application.
    *javax.enterprise.deploy.spi.exceptions.InvalidModuleException: [J2EE Deployment SPI:260105]Failed to create*
    DDBeanRoot for application, 'E:\AqanTech\WebApp1\myApp.war'.
    I have checked everything, right from my code to my web.xml file. I have used a build.bat file to build my war file.
    PLEASE HELP ME TO SOLVE THIS HUGE PROBLEM OF MINE ?
    Thanks,
    Shoeb

    Hi,
    The J2EE Error code siply suggest that there is something wrong in your Deployment Descriptors...
    Can u please post the XML files available inside your "WEB-INF" directory?
    Thanks
    Jay SenSharma
    http://jaysensharma.wordpress.com (WebLogic Wonders Are Here)

  • Problem while executing simple java program

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

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

  • PARSE_APPLICATION_DATA Error during XML = ABAP conversion: Response Message; CX_ST_DESERIALIZATION_ERROR in /1SAI/SAS0446CC11CC6EC1AD4789 Line 24 An error occurred when deserializing in the simple transformation program /1SAI/SAS0446CC11CC6EC1AD4789

    Hi Experts ,
    i have a scenario proxy to soap  where i am getting error while getting the response .
    we are sending the request successfully and getting response .some times we are getting in proxy level error below
    PARSE_APPLICATION_DATA Error during XML => ABAP conversion: Response Message; CX_ST_DESERIALIZATION_ERROR in /1SAI/SAS0446CC11CC6EC1AD4789 Line 24 An error occurred when deserializing in the simple transformation program /1SAI/SAS0446CC11CC6EC1AD4789 (Cha
    Please help us to fix this bug in proxy response.
    Regards
    Ravi

    Hello Ravinder,
    Can you please post the complete stack trace, it seems to be some fields are getting truncated i,e data sent from the program to the proxy object might be violating some length restrictions.
    Please check your message interface field lengths and what is being passed to the proxy.
    Regards,
    Ravi.

Maybe you are looking for

  • Issues with iTunes 11.1.5 and Windows 8.1

            I recently upgraded my iTunes to 11.1.5 on my Windows 8.1 computer, since the upgrade iTunes has become unusable. Before the upgrade I had an occasional error, device not recognized or a download error, sometimes i had to unplug and then plug

  • Details of contract employee

    Hi Experts, I would like to know  contract employee  information for this i have checked in P0001-PERSK EE subgroup.but for  that employee he does not have contract number.may be i have to check based on the company .Please correct me if i am going w

  • OLE Excel NumberFormat

    Hi All, In OLE for example consider the follwing statement, SET PROPERTY OF wf_cell1 'NumberFormat' = '@'. How can I get to know the list of possible values for 'NumberFormat' with their meaning? (Actually I want to use Currency format in my EXCEL ap

  • ITunes 10.4 suddenly not working on G5/10.58

    A couple of days ago I could use iTuens without a problem on my G5 running OSX 10.5.8 Yesterday when I tried to synch my ipad1, it wouldn't see it. I tried with my iphone 4 and iTunes didn't see that either. Then I tried the store link and it won't a

  • "itunes has stopped working".what do i do. i need help. happens after i click on a different program

    every time i open itunes and plug in my phone a update  box comes to upgrade to 5.5.1 but then seconds after i get a box  stating "itunes has stopped working" .... this also happens when i click out of itunes to go to a different program and i looked