Array program

hey guys
well, i have a little problem with my prac. anyone who can help, please do!!!!!!!! well the prac is like this:
- use an initialiser list to create an array that holds all the prime numbers between 2 and 100;
- prime numbers are : 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
-request a number between 2 and 100
- inform the user if that number is prime
- repeat this indefinitely until the user supplies a negative number
- if the response is not a negative number and not between 2 and 100 then inform the user that the response is invalid!!!
nowwwwwwww, here's what i have done so far,
please reply with suggestion!!
public class prac7
{  public static void main (String[] args)
int[] primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
int response = 2;
     Screen.out.println ("");
     Screen.out.println (" ........Hello and Welcome!!.........");
     Screen.out.println ("");
     Screen.out.print (" Please enter a number between 2 and 100: ");
     response = Keybd.in.readInt();
     for (......................) // what goes here???
     // how is it possible to compare the response to all the prime numbers above//
     if (response == primes.length) {
     Screen.out.println ("");     
     Screen.out.println (" - The number you have requested is prime!!");
     int count = 4;
     while (count > 0) {
          Screen.out.println (" - Good one!!");
          count = count - 1;
     else if (response > 100) {
     Screen.out.println ("");     
     Screen.out.println (" - The response is invalid.");
     Screen.out.println ("");
     Screen.out.println (" - Good luck next time!! Can't be that hard!!!");
     else if (response < 0) { 
     Screen.out.println ("");     
     Screen.out.println (" - Out of my range!!");
     else
     Screen.out.println ("");
     Screen.out.println (" - Not a prime number!!");
}

Okay let's get serious ;)
replace all your if else stuff to this
if(response > 100) {
            Screen.out.println("");
            Screen.out.println(" - The response is invalid.");
            Screen.out.println("");
            Screen.out.println(" - Good luck next time!! Can't be that hard!!!");
        else if (response < 0) {
            Screen.out.println("");
            Screen.out.println(" - Out of my range!!");
        else {// okay enough of other checking time to check for primes
            boolean found = checkPrime(response);
            if(found)
                Screen.out.println(" - The number you have requested is prime!!");
            else
                Screen.out.println(" - Not a prime number!!");
        }add a new function
private boolean checkPrime(int response) {
        for(int w=0;w<primes.length;w++) {
            if(response==primes[w]) {
                return true; //if one of them matches we found it so quit checking
        return false; //didn't find a match sad :(
unformattted one
replacement code
if(response > 100) {
Screen.out.println("");
Screen.out.println(" - The response is invalid.");
Screen.out.println("");
Screen.out.println(" - Good luck next time!! Can't be that hard!!!");
else if (response < 0) {
Screen.out.println("");
Screen.out.println(" - Out of my range!!");
else {// okay enough of other checking time to check for primes
boolean found = checkPrime(response);
if(found)
Screen.out.println(" - The number you have requested is prime!!");
else
Screen.out.println(" - Not a prime number!!");
extra function
private boolean checkPrime(int response) {
for(int w=0;w<primes.length;w++) {
if(response==primes[w]) {
return true; //if one of them matches we found it so quit checking
return false; //didn't find a match sad :(
Thanks
Joey

Similar Messages

  • 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.

  • Help with array program!!

    hi friends
    i am a new comer to java and I have been studying Arrays recently. I came across this program on the internet ( thanks to Peter Williams)
    package DataStructures;
    import java.util.NoSuchElementException;
    * An array implementation of a stack
    * @author Peter Williams
    public class StackArray implements Stack {
    private int top; // for storing next item
    public StackArray() {
    stack = new Object[1];
    top = 0;
    public boolean isEmpty() {
    return top == 0;
    public void push(Object item) {
    if (top == stack.length) {
    // expand the stack
    Object[] newStack = new Object[2*stack.length];
    System.arraycopy(stack, 0, newStack, 0, stack.length);
    stack = newStack;
    stack[top++] = item;
    public Object pop() {
    if (top == 0) {
    throw new NoSuchElementException();
    } else {
    return stack[--top];
    interface Stack {
    * Indicates the status of the stack.
    * @return <code>true</code> if the stack is empty.
    public boolean isEmpty();
    * Pushes an item onto the stack.
    * @param <code>item</code> the Object to be pushed.
    public void push(Object item);
    * Pops an item off the stack.
    * @return the item most recently pushed onto the stack
    * @exception NoSuchElementException if the stack is empty.
    public Object pop();
    class StackDemo {
    public static void main(String[] args) {
         Stack s = new StackArray();
         // Stack s = new StackList();
         for (int i = 0; i < 8; i++) {
         s.push(new Integer(i));
         while (!s.isEmpty ()) {
         System.out.println(s.pop());
    what baffles me is as below:
    there is an 'if' construct in the push method, which talks about if(top == stack.length)
    I fail to understand how top can at any time be equal to stack.length.
    Could you help me understand this program?
    a thousand apologies and thanks in advance

    figurativelly speaking:
    if you take an array and put it standing on your tesk, so that start of array points to floor, and end of array points to roof, then you can start filling that array as stack.
    if you put books into stack, then you push (put) them on top of the stack, so the first book ever but into stack is adiacent to array element with index zero (0) and then second book in stack would be adiacent to array element that has index one (1) and so on.
    if you have array of size 5, then fift book in stack would be adiacent to array element with index four (4)
    after pushing that Object to stack, the top variable will get incremented (top++ in code) and be equal to size of array.
    however, if you would like to push another Object to stack, then it would fall over the end of the array, so longer array is needed...

  • Error in array program

    hi
    can anyone tell me why this program gives a syntax error. But it works for a byte code[] array.
    public class String2a {
         public static void main(String[] args) {
              int code[] = {35,36,37,38,39,30};
              String s1 = new String(code,1,5);
              String s2 = new String(code,2,3);
              String s3 = new String(code);
              System.out.println(s1);
              System.out.println(s2);
              System.out.println(s3);
              System.out.println(code);
    String2a.java:10: cannot find symbol
    symbol : constructor String(int[])
    location: class java.lang.String
              String s3 = new String(code);

    String2a.java:10: cannot find symbol
    symbol : constructor String(int[])This compiler message means pretty much what it says: there is no String constructor that takes a single int array as its argument.
    For a list of what constructors there are see the [String API documentation|http://java.sun.com/javase/6/docs/api/java/lang/String.html]

  • 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.

  • 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.

  • 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);
    }

  • Help with an array program

    I can't see how to calculate the lowest hours, highest hours, and average hours worked.
    These three values should be outputted each on a seperate line.
    I just can't figure this out.
    Any help please.
    This program will show the employees
    hours. It will have one
    class.It will use an array to keep
    track of the number of hours the employee
    has worked with the output to the monitor
    of the employees highest, lowest, and the
    average of all hours entered. */
    import java.util.*;
    import java.text.DecimalFormat;
    /*** Import Decimal Formating hours to format hours average. ***/
    public class cs219Arrays
         public static void main(String[] args)
              Scanner scannerObject = new Scanner(System.in);
              int[] employees ={20, 35, 40};
              int employeesHighest = 40;
              int employeesLowest = 20;
              double employeesAverage = 35;
              int[] firstEmployee = new int[1];
              int[] secondEmployee = new int[2];
              int[] thirdEmployee = new int[3];
              System.out.println("This program will accept hours worked for 3 employees.");
              System.out.println("Enter hours worked for employee #: ");
              System.out.println(".\n");
              employeesAverage = scannerObject.nextInt();
              for(int count =20; count <= 40; count++)
                             DecimalFormat df = new DecimalFormat("0.00");
                             System.out.println("pay: " employeesAverage " lowest " employeesHighest " Highest hours " employeesLowest " Lowest hours "+df.format(employeesAverage));
                             System.out.print("\n");
                             employeesAverage++;
    }/* end of body of first for loop */
              for(int count =20; count <= 40; count++)
                                       employeesAverage = employeesAverage + employeesHighest + employeesLowest;
                                       DecimalFormat df = new DecimalFormat("0.00");
                                       System.out.println("pay: $" employeesAverage " lowest " employeesHighest " Highest hours $" +df.format(employeesAverage));
                                       System.out.print("\n");
                                       employeesAverage++;
    }/* end of body of second for loop */
              for(int count =20; count <= 40; count++)
                                       employeesAverage = employeesAverage + employeesHighest + employeesLowest;
                                       DecimalFormat df = new DecimalFormat("0.00");
                                       System.out.println("pay: $" employeesAverage " lowest " employeesHighest " Highest hours $" +df.format(employeesAverage));
                                       System.out.print("\n");
                                       employeesAverage++;
    }/* end of body of third for loop */
              System.out.println("\n");
              DecimalFormat twoDigits = new DecimalFormat("0.00");
              /*** Create new DecimalFormat object named twoDigits ***/
              /*Displays number of hours, employees hours and average hours.*/
              System.out.println("You entered " + employeesAverage + " number of hours.");
              System.out.println("Your number of hours are " + twoDigits.format(employeesAverage));
              System.out.println("\n\n");
    }     /*End of method for data.*/
    {     /*Main method.*/
    }     /*End of main method.*/
    }     /*End of class cs219Arrays.*/

    Want help?
    Use the code formatting tags for starters. http://forum.java.sun.com/help.jspa?sec=formatting

  • 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.

  • Need help with an arrays program

    this is the task
    1.instantiate an array to hold integer test scores
    2.determine and print out the total number of scores
    3.determine whether there are any perfect scores (100) and if so print student numbers (who received these scores)
    4.print out only the scores that are greater or equal to 80
    5.calculate the percentage of students that got scores of 80 or above (and print out)
    6.calculate the average of all scores (and print out)
    heres the code that i came up with
    int [] scores = {79, 87, 94, 82, 67, 100, 98, 87, 81, 74, 91, 59, 97, 62, 78, 66, 83, 75, 88, 94, 63, 44, 100, 69, 87, 99, 76, 72};
    int total=scores.length;
    System.out.println("The total number of scores is: "+total);
    for (int i=0;i<=scores.length;i++)
    System.out.println(scores);
    step 2 is as far as i got
    i got stuck at step 3, i cant figure out how to do that
    reply plz, ty

    3.determine whether there are any perfect scores (100) and if so print student numbers (who received these scores)This question strongly suggests that the data contains information about students associated with each of the test scores. As you have illustrated it, part 3 is simply not doable. There must be more to the assignment than you have said.
    Do one thing at a time and make sure your code compiles and runs as you expect before moving on. The code you have posted looks OK for the first couple of steps, but its it's impossible to say unless you post something that's runnable.
    (A small thing - but very much appreciated - can you please post code using the "code" tags? Put {code} at the start of your code and again at the end. That way the code will be nicely formatted by the forum's astounding software.)

  • Confusion on how to make array program

    I have been taking a Java class at school for a couple months and am a bit unsure about how to go about completing a particular assignment. No text book that I found could really make me understand. I am trying to make a simple applet that tests for a username and password. My teacher tried it and also couldn't do it. Here is what we have so far. Any input on how to make the array portion work would be appreciated greatly:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PasswordApplet extends Applet implements ActionListener
    //Declaring variables
    String id, password;
    boolean success;
    String idArray[] = {"aaron","kevin"};
    String passwordArray[] = {"shs", "bears"};
    //Create components for applet
    Label headerLabel = new Label("Please type your ID and Password");
    Label idLabel = new Label("ID: ");
    TextField idField = new TextField(8);
    Label passwordLabel = new Label("Password: ");
    TextField passwordField = new TextField(8);
    Button loginButton = new Button("Login");
    public void init()
    //Set color, layout, and add components
    setBackground(Color.orange);
    setLayout(new FlowLayout(FlowLayout.LEFT,50,30));
    add(headerLabel);
    add(idLabel);
    add(idField);
    idField.requestFocus();
    add(passwordLabel);
    add(passwordField);
              passwordField.setEchoChar('*');
    add(loginButton);
    loginButton.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    success = false;
    id = idField.getText();
    password = passwordField.getText();
    //Sequential search
    int i = 0;
              while( i<idArray.length)
                        if(id.compareTo(idArray)==0)
                             if (password.compareTo(passwordArray[i])==0)
                                  success = true;
                        i = i+1;
                   if (success = false)
                        headerLabel.setText("Unsuccessful. Try Again");
                        idField.setText("");
                        passwordField.setText("");
                        idField.requestFocus();
                   else
                        headerLabel.setText("Login successful");
    repaint();

    I have been taking a Java class at school for a
    couple months and am a bit unsure about how to go
    about completing a particular assignment. No text
    book that I found could really make me understand.
    sigh
    am trying to make a simple applet that tests for a
    username and password. Okay.
    My teacher tried it and also
    couldn't do it. Why? What is the point in telling us this? Your teacher is an idiot? Good for you.
    Here is what we have so far. Any
    input on how to make the array portion work would beWhat specific problem are you having? Tell us that. It doesn't work is meaningless.
    Do you have an error? Does it compile? Which specific line of code does not do what you expect?

  • What wrong with this array program

    Hello,
    I am writing a program to calculate a sum of matrix A (power 100) and B(power 50). I do not have mathlab to check the result. However, it seem to me that the last row of result is not correct. Can any one help me, please. The below is my program. Thank you very much.
    public class MatrixT
    public static void main(String[] args) {   
         //This part is used to calculate Matrix A (power 100)
    int [][]MatrixA0 = {     {1,2,-9,5,3},{2,3,6,2,5},{1,2,3,-6,4},{5,5,2,1,0},{-6,2,3,1,0}};
         System.out.println("Matrix A (power 100) is ");
         int [][]MatrixA1 = new int [5][5];
         for (int i=0; i < 5;i++)
         for (int j=0; j<5; j++)
              MatrixA1 [j] = MatrixA0 [i][j];
         for (int n = 0 ; n < 100 ; n ++)
         int [][] MatrixA2 = new int [5][5];
         for (int i=0; i < 5;i ++)
         for (int j=0; j<5; j ++)
              //MatrixA2[i][j] = 0;
              for (int k = 0; k<5; k++)
              MatrixA2[i][j] += MatrixA1[i][k] * MatrixA0[k][j];
         for (int i=0; i < 5;i++)
         for (int j=0; j<5; j++)
              MatrixA1 [i][j] = MatrixA2[i][j];
         for (int i=0; i < 5;i++)
         for (int j=0; j<5; j++)
    System.out.print(MatrixA1[i][j] + "\t");
         System.out.println();
    // This part is used to calculate Matrix B (power 50)
    int [][]MatrixB0 = {{2,0,4,-2,-8},{1,1,2,2,7},{3,1,-5,6,3},{5,-5,-7,-1,3},{3,7,1,0,0}};
    System.out.println("Matrix B (power 50) is ");
    int [][]MatrixB1 = new int [5][5];
         for (int i=0; i < 5;i++)
         for (int j=0; j<5; j++)
              MatrixB1 [i][j] = MatrixB0 [i][j];
         for (int n = 0 ; n < 50 ; n ++)
         int [][] MatrixB2 = new int [5][5];
         for (int i=0; i < 5;i ++)
         for (int j=0; j < 5; j ++)
              //MatrixB2[i][j] = 0;
              for (int k = 0; k < 5; k++)
              MatrixB2[i][j] += MatrixB1[i][k] * MatrixB0[k][j];
         for (int i=0; i < 5;i++)
         for (int j=0; j < 5; j++)
              MatrixB1 [i][j] = MatrixB2[i][j];
    for (int i=0; i < 5;i++)
         for (int j=0; j < 5; j++)
         System.out.print(MatrixB1[i][j] + "\t");
         System.out.println();
    //This part is used to sum up the two productions of A and B
    int [][]MatrixC = new int [5][5];
         System.out.println("Matrix C (sum of A and B) ");
    for (int i=0; i < 5;i++)
         for (int j=0; j < 5; j++)
              MatrixC[i][j] = MatrixA1[i][j] + MatrixB1[i][j];
         for (int i=0; i < 5;i++) {
         for (int j=0; j < 5; j++)
         System.out.print(MatrixC[i][j] + "\t");
         System.out.println();

    hi couldnt compile ur program
    so i wrote it this wayy.hope this will help u
    import java.util.*;
    public class matrix {
    static int SIZE = 5;
    static int NO_OF_TIMES1=99;
         static int NO_OF_TIMES2=49;
    public static void main(String args[]) {
         int mA[][] = { {1,2,-9,5,3},{2,3,6,2,5},{1,2,3,-6,4},{5,5,2,1,0},{-6,2,3,1,0}};
         int mB[][] = {{2,0,4,-2,-8},{1,1,2,2,7},{3,1,-5,6,3},{5,-5,-7,-1,3},{3,7,1,0,0}};
         int mA100[][] = new int[SIZE][SIZE];
    int mB50[][] = new int[SIZE][SIZE];
         int mAPLUSB[][] = new int[SIZE][SIZE];
         for (int i=0; i<NO_OF_TIMES1; i++) {
         mA100= mmult(SIZE, SIZE, mA, mA, mA100);
         for (int i=0; i<NO_OF_TIMES2; i++) {
         mB50= mmult(SIZE, SIZE, mB, mB, mB50);
         mAPLUSB=madd(SIZE, SIZE, mA100, mB50, mAPLUSB);
         print(mAPLUSB);
    public static void print(int[][] mm){
    for(int j=0;j<SIZE;j++){
    for(int k=0;k<SIZE;k++){
                   System.out.print(mm[j][k]);
                   System.out.print("\t");
              System.out.println();
    public static int[][] mmult (int rows, int cols,
         int[][] m1, int[][] m2, int[][] m3) {
         for (int i=0; i<rows; i++) {
         for (int j=0; j<cols; j++) {
              int val = 0;
              for (int k=0; k<cols; k++) {
              val += m1[i][k] * m2[k][j];
              m3[i][j] = val;
         return m3;
         public static int[][] madd (int rows, int cols,
         int[][] m1, int[][] m2, int[][] m3) {
         for (int i=0; i<rows; i++) {
         for (int j=0; j<cols; j++) {
              int val = 0;
              val += m1[i][j] + m2[i][j];
                   m3[i][j] = val;
         return m3;

  • How Hard is it to program in Java.Swing

    Hi
    I wanted to program using java.swing component but i don't have any idea where i should start.
    I have been programming in java using java.Awt
    and i can do simple array programing.
    So how hard is it, and Where should i start learning java.swing. Ps I don't know anything about Swing, I don't even know what it is.
    Thanks you

    Hi
    As the previous guy said it is quite easy, and that link should teach you the basics. What I want to remind you of is that Swing uses up more memory when run. But it also have a few nicer extra goodies that make coding a little bit easier. Have fun with it.
    Here are a few more sites
    <http://manning.spindoczine.com/sbe/>
    <http://java.sun.com/docs/books/tutorial/uiswing/>
    Ciao

  • Javascript array / jsp Bean Collection

    How can you fill a javascript array with the values of the collection?
    <jsp:useBean id="programs" scope="request" class="java.util.Collection"/>
      How can I create this array?
    <script language="JavaScript" type="text/javascript">
    var programData =
    new Array ( new Array "${programs[1].programId}","${programs[1].programName}", "${programs[1].department}"),  
                 new Array "${programs[2].programId}","${programs[2].programName}", "${programs[2].department}"),
    </script>

    I answered myself. If anyone else would like to know how to fill a javascript array with the values of a jsp beans collection.
    function collectionToArray()
    Array[rows] = [4];  
    var cnt = 0;
    <c:forEach var="sp" items="${programs}">
      rows[cnt][0] = ${sp.programId};
      rows[cnt][1] = ${sp.programName};
      rows[cnt][2] = ${sp.department};
      rows[cnt][3] = ${sp.urlLink1};
      rows[cnt][4] = ${sp.urlLink2};
      cnt++;
    </c:forEach>  
    }

  • Display warning if 2 names are identical

    Can someone please help me with this. My array program is below. I need to edit it to make a message display 'This password has been chosen' if to names are identical. I have played around with it and I can get the warning to appear but all the time. The code below makes the warning cycle continuously down the page. If anyone could help I would be very gratefull.
    import java.io.*;
    public class Arraylist
    public static void main(String[] args)
    String members[] = {"Fred","Brenda","John"};
    System.out.println("full member: "+members[0]);
    while (members==members)
    System.out.println("this password has been chosen");

    I'm going to assume for a moment that this is a serious question and not a troll.
    It should be obvious that (members==members) is going to return true always.
    At what point are you checking to see if there is a duplicate? Is it only in the original array, or are you adding items later?
    In either case, some classes that should help you are:
    HashSet (or anything implementing the Set interface)
    HashMap (or anything implementing the Map interface)
    both are found in java.util.
    Hope this helps.

Maybe you are looking for

  • Guest network and multiple VLANs

    Hello all, I have installed a pair of 5508 controllers in our network. One controller sits inside the network and APs are configured to associate with that controller. The second controller sits on a DMZ interface off the ASA. I have a guest network

  • How to create new java objects in native methods?

    Hello, Is it possible to create java objects and return the same to the java code from a native method? Also is it possible to pass java objects other than String objects (for example, Vector objects) as parameters to native methods and is it possibl

  • Multi-Message Mapping based on value of field - (Without BPM)

    Hi. I am having a bit of difficulty with multi-message mapping without BPM. I want to map to message1 & message2 based on a field in the rows of the source structure. e.g. row1-Source-Field1=> (if equal 0)   => <b>Message1</b>-field1. row2-Source-Fie

  • Making the background white

    Can someone help me make the background of my application white ? All it does is display a simple curve in a window. Here's the structure: public class Curve public static void main(String[] args) JFrame window = new JFrame(); CurvePane pane = new Cu

  • GTS and FI intergration

    Hi, Currently we are implementing SAP GTS 7.2, we need to do SPL check on payment run. When the payment proposal is generated in ECC - get an error as u201CTechnical error when checking in GTSu201D the message class is u201CFIPAY_GTSu201D but in GTS