Help with array

i have this assignment and i need to get number of As, Bs, Cs, Ds, and Fs and display those numbers based on the % of the class in a graph. (duno if that made sense, lets say theres 2 As and 2 Fs, 50% had As and 50 had Fs...)
the grapg needs to look like this
o     10     20     30     40     50     60     70     80     90     100%
|     |     |     |     |     |     |     |     |     |     |
****A
**************B
*******************C
*******D
****Fi need to have 50 total asterisks, so 1 ast. equals 2 percent. now so far i have this
public GradeGraph (){
     Scanner scan = new Scanner(System.in);
     public int inputNumOfGrades() {
          System.out.println("Enter number of A's:");
          System.out.println("Enter number of B's:");
          System.out.println("Enter number of C's:");
          System.out.println("Enter number of D's:");
          System.out.println("Enter number of F's:");
           int A = scan.nextInt();
           int B = scan.nextInt();
           int C = scan.nextInt();
           int D = scan.nextInt();
           int F = scan.nextInt();
           int total = (A+B+C+D+F);
           return A + B + C + D + F + total;}
     public String drawGraph (String grade) {
          }my question is how do i make all those asterisks by using arrays?

how do i get it to print something like this
o     10     20     30     40     50     60     70     80     90     100%
|     |     |     |     |     |     |     |     |     |     |
****A
**************B
*******************C
*******D
****Fi have this so far
//GradeGraph.java
import java.util.Scanner;
     public class GradeGraph
     private int A, B, C, D, F;
     private double total;
     public static void inputNumOfGrades() {
          Scanner scan = new Scanner(System.in);
          System.out.println("Enter number of A's:");
                int A = scan.nextInt();
          System.out.println("Enter number of B's:");
                int B = scan.nextInt();
          System.out.println("Enter number of C's:");
                int C = scan.nextInt();
          System.out.println("Enter number of D's:");
                int D = scan.nextInt();
          System.out.println("Enter number of F's:");
                int F = scan.nextInt();
     public int total(){
          int total = A + B + C + D + F;
          return total;
     public double getPercentA(){
          double pA = A / total;
          return pA;}
     public double getPercentB(){
          double pB = B / total;
          return pB;}
     public double getPercentC(){
          double pC = C / total;
          return pC;}
     public double getPercentD(){
          double pD = D / total;
          return pD;}          
     public double getPercentF(){
          double pF = F / total;
          return pF;}
     public void drawGraph () {
          for (int i=1;i<=50;i++){
          System.out.println("*");}
          }

Similar Messages

  • Need help with Arrays

    Hey guys, I'm a beginner programmer and I'm having a bit of a tough time with arrays. I could really use some help!
    What I'm trying to do is roll one die and then record the rolls.
    Here is my sample I/O:
    How many times should I roll a die?
    -> 8
    rolling 8 times
    2, 1, 5, 6, 2, 3, 6, 5
    number of 1's: 1
    number of 2's: 2
    and so on....
    Here is my incomplete code at this moment:
    //CountDieFaces.java
    import java.util.Scanner;
    import java.io.*;
    import library.Gamble;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        Scanner scan = new Scanner(System.in);
        int[] faceCount= {0,0,0,0,0,0,0};
        int dice;
        System.out.println("How many times would you like to roll the die?");
        int dieCount = scan.nextInt();
        int dieRoll = Gamble.rollDie(); // Main calling class method
        int count = 1;
        while(count < dieCount)
            System.out.println(faceCount[count]);
            count++;
    }Here is the gamble library:
    //Gamble.java
    package library;
    public class Gamble
         // returns 1, 2, 3, 4, 5, or 6
         public static int rollDie()
              int dieRoll = (int)(Math.random()*6)+1;
              return dieRoll;
    }and here are the errors I have so far:
    ----jGRASP exec: javac -g CountDieFaces.java
    CountDieFaces.java:19: <identifier> expected
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:19: illegal start of type
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:25: illegal start of type
         while(count < dieCount)
         ^
    CountDieFaces.java:25: > expected
         while(count < dieCount)
         ^
    CountDieFaces.java:25: ')' expected
         while(count < dieCount)
         ^
    CountDieFaces.java:26: ';' expected
         ^
    CountDieFaces.java:27: illegal start of type
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ';' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: invalid method declaration; return type required
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ']' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ')' expected
              System.out.println(faceCount[count]);
    I'm really confused with how a the gamble library gets put into the array, so any help is appreciated! Also if anyone could explain the errors to me, I would really appreciate it.
    thanks in advance,
    wootens
    Edited by: Wootens on Oct 18, 2010 8:55 PM

    D'oh!
    Thanks you guys, fixed that. Although I'm having trouble with storing the die roll in the array. Any suggestions?
    java.io.*;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        public static void main(String[] args)
            Scanner scan = new Scanner(System.in);
            int[] faceCount= {0,0,0,0,0,0};
            int dice;
            System.out.println("How many times would you like to roll the die?");
            int dieCount = scan.nextInt();
            int dieRoll = rollDie(); // Main calling class method
            int count = 0;
            while(count < dieCount)
                System.out.println(faceCount[dieRoll]);
                count++;
        public static int rollDie()
            int dieRoll = (int)(Math.random()*6)+1;
            return dieRoll;
    }Wootens

  • Help with array question

    hi,
    i need some help with this piece of code. wat would it output to the screen?
    int [] theArray = { 1,2,3,4,5};
    for (int i = 1; i < 5; i++)
    System.out.print(theArray * i + "; ");
    would it output 1 * 1;
    2 * 2;...
    thanx
    devin

    Ok...
    1] Your index into the array is off by 1 - remember that array indexing starts from 0.
    2] You cannot multiply an array object. The contents? fine , go ahead but NOT the array
    so your output should be something like:
    operator * cannot be applied to int[] :d
    try
    int[] theArray = {0,1,2,3,4,5};
    for(int i = 1;i<6;i++)
         System.out.print(theArray*i+";");
    giving you an output of 1;4;9;16;n...
    if you were looking for the output stated change
    System.out.print(theArray*i+";");
    to
    System.out.print(theArray[i]+"*"+i+";");done...

  • Need Help with Array.sort and compare

    Hi
    I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
    Ok everthing works fine, but i get a problem with lower and upper cases.
    So i need a comparator, i tried everything but i just dont understand it.
    How do i use this with Array.sort??
    I hope someone can help me

    Okay, you want to ignore case when sorting.
    There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
    English english German german
    english English german German
    English english german German
    english English German german
    The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
    Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
    The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
        String s1 = ((String)o1).toUpper();
        String s2 = ((String)o1).toUpper();
        return s1.compareTo(s2);
    } You'll need to add your own null check if you need one.
    For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
    Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked.

  • Please Help With Arrays

    I really need some help with the following two methods:
    - A method fillArray() that accepts an integer array as a parameter and fills the array with random integers. I am encouraged to use Math.random()
    - A method printArray() that accepts an integer array as a parameter and outputs every element of the array to the standard output device. I am encouraged to use print instead of println in order to save paper.
    Thanks so much for your help.

    public class Test {
       public static void main (String[] args){
           int[] intArray = new int[20];
           fillArray(intArray);
           printArray(intArray);
       public static void fillArray (int[] intArray){
           for (int i = 0; i < intArray.length; i++) {
               intArray[i] = (int) (Math.random()*1000);
       public static void printArray (int[] intArray){
           for (int i = 0; i < intArray.length; i++) {
               int i1 = intArray;
    System.out.print(i1+",");
    System.out.println("");

  • Need Help with Arrays/Text

    I'm trying to create a flash program that uses it's own code to send and create images. Each square has a colour and that colour gets added into the array. A black, then grey, then white is:
    filecode = ["Bl", "Gr", "Wh"];
    That works fine, but when I try to paste it into an Input text box it will only fill in the first part of the array.
    filecode = ["Bl,Gr,Wh"];
    So the program has NO idea what I want.
    The only ways I can think of fixing this is by putting in 402 text boxes to suit every box...But every one of them needs a Variable Name.
    Or by sending the information straight into the array. But this way you are just looking at what you just drew, and that is not at ALL practical.
    Helping me with this headache will be greatly apprectiated.
    FlashDrive100.

    If you can explain the first part of your posting it might become a little clearer what you are trying to do and what isn't working... particularly this...
    " when I try to paste it into an Input text box it will only fill in the first part of the array."
    I can't speak for anyone else, but at this point, I share your file's problem... not knowing what you want.

  • Help with arrays and Exception in thread "main" java.lang.NullPointerExcept

    Hi, I have been having trouble all day getting this array sorted and put into a new array. I think it is something simple with my nested loops in sortCityArray() that is causing the problem. Any help would be greatly appreciated. The error is thrown on line 99 at Highway.sortCityArray(Highway.java:99)
    import java.util.Scanner;
    import java.io.*;
    import java.util.Arrays;
    public class Highway
    private String[] listOfCities=new String[200];
    private City[] cityArray=new City[200];
    private City[] sortedCityArray=new City[200];
    private String city="";
    private String city2="";
    private String fileName;
    private City x;
    private int milesToNextCity;
    private int milesAroundNextCity;
    private int speedToNextCity;
    public Highway(String filename)
    String fileName=filename;//"I-40cities.txt";
           File myFile = new File(fileName);
           try {
           Scanner scan=new Scanner(myFile);
           for(int i=0; scan.hasNextLine(); i++){
           String city=scan.nextLine();
           String city2=scan.nextLine();
           int milesToNextCity=scan.nextInt();
           int milesAroundNextCity=scan.nextInt();
           int speedToNextCity=scan.nextInt();
                   if(scan.hasNextLine()){
              scan.nextLine();
           cityArray=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    //return cityArray;
    /*public City[] doCityArray(){
    File myFile = new File(fileName);
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
    String city=scan.nextLine();
    String city2=scan.nextLine();
    int milesToNextCity=scan.nextInt();
    int milesAroundNextCity=scan.nextInt();
    int speedToNextCity=scan.nextInt();
         if(scan.hasNextLine()){
              scan.nextLine();
    cityArray[i]=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    return cityArray;
    public City[] sortCityArray(){
    sortedCityArray[0]=new City(cityArray[0].getCity(),cityArray[0].getNextCity(),cityArray[0].getLengthAB(),cityArray[0].getLengthAroundB(),cityArray[0].getSpeedAB());
    for(int j=0; j<cityArray.length; j++ )
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
    /*     for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    //     j++;
    System.out.println(sortedCityArray[0].getCity());
    System.out.println(sortedCityArray[0].getNextCity());
    System.out.println(sortedCityArray[0].getLengthAB());
    System.out.println(sortedCityArray[0].getLengthAroundB());
    System.out.println(sortedCityArray[0].getSpeedAB());
    System.out.println(sortedCityArray[1].getCity());
    System.out.println(sortedCityArray[1].getNextCity());
    System.out.println(sortedCityArray[1].getLengthAB());
    System.out.println(sortedCityArray[1].getLengthAroundB());
    System.out.println(sortedCityArray[1].getSpeedAB());
    System.out.println(sortedCityArray[2].getCity());
    System.out.println(sortedCityArray[2].getNextCity());
    System.out.println(sortedCityArray[2].getLengthAB());
    System.out.println(sortedCityArray[2].getLengthAroundB());
    System.out.println(sortedCityArray[2].getSpeedAB());
    System.out.println(sortedCityArray[3].getCity());
    System.out.println(sortedCityArray[3].getNextCity());
    System.out.println(sortedCityArray[3].getLengthAB());
    System.out.println(sortedCityArray[3].getLengthAroundB());
    System.out.println(sortedCityArray[3].getSpeedAB());
    System.out.println(sortedCityArray[4].getCity());
    System.out.println(sortedCityArray[4].getNextCity());
    System.out.println(sortedCityArray[4].getLengthAB());
    System.out.println(sortedCityArray[4].getLengthAroundB());
    System.out.println(sortedCityArray[4].getSpeedAB());
    return cityArray;
    /*public String[] listOfCities(){
    File myFile = new File("I-40cities.txt");
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
         String city=scan.nextLine();
         city=city.trim();
    scan.nextLine();
    scan.nextLine();
         listOfCities[i]=city;
         System.out.println(listOfCities[i]);
    catch (Exception e) {
    System.out.println(e);
    return listOfCities;
    public static void main(String args[]) {
    Highway h = new Highway("out-of-order.txt");
    h.sortCityArray();

    the ouput is perfect according to the print lines if I use (increase the int where j is in the loop manually by one) :
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[0].getNextCity().equals(cityArray.getCity())){
              sortedCityArray[0+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[1].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[1+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[2].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[2+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[3].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[3+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    But I cant do this for 200 elements. Are the loops nested right?
    Edited by: modplan on Sep 22, 2008 6:49 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

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

  • Need Small Help with Arrays.

    I have this question i wanna ask...Could anyone help me with this code.
    Assume that the array arr has been declared. how do i write a statement that assigns the next to last � element of the array to the variable x , which has already been declared.

    Of course, if you don't know the size until run time, you'll want to check that the array size is greater than 1, else there won't BE a next to last element.

  • Help with arrays...Please Help

    Hello,
    Iam trying to make a library system. I have three classes, one for the GUI, User class, and Users class. User class instantiates an object with all the relevant data like, Name, Age, Address, etc. The Users class contains a array of User Objects.
    With this program I have to be able to create users, display users and delete users. The problem Iam having is displaying them. (I think I correctly store the User Objectsin the array, and Iam having problems retreiving them). The thing is when I run the program I don't get any exception errors, just nothing gets displayed!
    Here is part of my code:
    public class Users {
    //declaring variables
    public Users (){
    initialiseArray();
    public void initialiseArray(){
    userArray = new User [50];
    // This method first checks to see if there is enough room for a new
    // user object. If there is the object is added to the array, if there is'nt
    // Then method expandUserArray is called to make room for the user
    public void addUser( User user)
    if (userArraySize == userArray.length) {
    expandUserArray();
    userArray[userArraySize] = user;
    userArraySize++;
    // In this method first the user is searched for in the array, if found
    // Then method decreaseUserArray is called to delete the user
    public void deleteUser ( User user )
    location = 0;
    while (location < userArraySize && userArray[location] != user) {
    location++;
    if (userArray[location] == user) {
    decreaseUserArray(location);
    public void displayUsers( ){
    for (int i = 0; i < userArraySize; i++) {
    usersInformation += "\n" + (userArray.getUserName());
    usersInformation += "\t" + (userArray[i].getUserID());
    usersInformation += "\t" + (userArray[i].getUserAddress());
    public String getUserInformation(){
    //usersInformation = userInformation.toString();
    return usersInformation;
    // The User is deleted by shifting all the above users one place down
    private void decreaseUserArray(int loc)
    userArray[loc] = userArray[userArraySize - 1];
    userArray[userArraySize - 1] = null;
    userArraySize--;
    // This method increase the size of the array by 50%
    private void expandUserArray( )
    int newSize = (int) (userArray.length * increasePercentage);
    User newUserArray[] = new User[newSize];
    for (int i = 0; i < userArray.length; i++) {
    newUserArray[i] = userArray[i];
    userArray = newUserArray;
    Is there anything wrong with my arrays??? Here is part of my code for action performed:
    void addUserButton_actionPerformed(ActionEvent e) {
    newUserName = userNameTextField.getText();
    newUserAddress = userAdressTextField.getText();
    newUserID = Integer.parseInt ( userIDTextField.getText());
    User newUser = new User (newUserName, newUserAddress, newUserID);
    Users users = new Users();
    users.addUser(newUser);
    clearButton();
    void displayUsersButton_actionPerformed(ActionEvent e) {
    Users users = new Users();
    users.displayUsers();
    displayUsersTextArea.append (users.getUserInformation());
    void deleteUserButton_actionPerformed(ActionEvent e) {
    //Still incomplete
    Thanks for your help!

    First, PLEASE USE THE SPECIAL TOKENS FOUND AT
    http://forum.java.sun.com/faq.jsp#messageformat WHEN
    POSTING CODE!!!! Sorry about that, Iam new and I did'nt know about Special Tokens.
    As far as the problem, let me start out by asking if
    you've considered using a class that implements the
    List interface. Perhaps Vector or ArrayList would
    make a better choice since they already handle
    "growing" and "shrinking" for you.I tried using vector arrays but it got too complicated. It was very easy to add and remove objects from the vector but I never figured out how to display all the objects with all the data.
    public void displayUsers( ){
    for (int i = 0; i < userArraySize; i++) {
    usersInformation += "\n" +
    " + (userArray.getUserName());   //what is
    usersInformation?  Also, how does getUserName(),
    getUserID(), getUserAddress() know which user object
    to operate on if these are methods of userArray?
    usersInformation += "\t" +
    " + (userArray.getUserID());     //I'm guess you've
    only posted "some" of your code. 
    usersInformation += "\t" +
    " + (userArray.getUserAddress());//Try posting all
    that you have so far, and please use the special
    tokens to format your code.
    }I made a mistake while I was cutting & pasting my code. It should be for example:
    usersInformation += "\n" (userArray.getUserName());
    The comment about instanciating a new Users for each
    actionPerformed is on point. You are replacing your
    Usres with a new object each time.Yep this was the problem. I just changed the constructor, declared and
    created object of Users elsewhere.
    Thanks for your help!

  • Help with Array of Arrays

    import java.util.Arrays;
    import java.util.Date;
    import java.util.List;
    public class StockDay
        private String[] stockDayData;
        List stockDays = new ArrayList();
        public StockDay(String stockData)
            stockDayData = new String[6];
            String[] stockDayData= stockData.split(",");
            stockDays.add(stockDayData[]);
    }I have an outside class calling this class with a string of data separated by commas. I am trying to separate the data so that each time the method is called, each piece of the data (6 total) is put into an array list. Then that array list is put into an array list of arrays. I am sorry if I have not made this clear, I will try again. I want an array of arrays, and the interior arrays will contain 6 pieces of information each from the string that is given to the method, and each separated by commas.
    Any help is much appreciated. I am also curious how I can accesses one piece of the data at a time, this is what I am thinking for this:
    data = arraylist1[#].arraylist2[#]this would set data equal to whatever is in arraylist2[#]
    Thank you very much.

    ActingRude wrote:
    I meant just a simple Array I guess.Note the difference between Array and array. Class names start with uppercase in java. There is a class called Array, but it's just a utility class, and isn't part of arrays.
    .. like I am using above? I was under the impression that the biggest syntax difference between an array(fixed number of items) and an ArrayList(unfixed number of items) was the use of the [] and () That's one of many syntactical differences, yes, but the main difference is not in the syntax. arrays are part of the Java language, have special handling because of that, and are faster and smaller than ArrayLists. ArrayList is part of the API, and didn't exist until Java 1.2 (about 5-6 years into Java's life, I think), and is built on top of an array.
    UnsupportedOperationException:
    null (in java.util.AbstractList)I have no idea what is causing this, I can only assume that I am doing something wrong...It looks like you're tyring to add null to an ArrayList and it doesn't like it. I thought ArrayList accepted null elements, but I could be wrong. Paste in the exact line that's causing it, and any declarations necessary to clarify any variables used on that line.

  • A little bit of help with arrays

    Hi guyz
    I have a problem regarding reading and processing element of an array. I have a "Reference Base Generator" and for example I generate a sine wave. Then I use "Get waveform components" to get the data from the graphic, after this i have a 1-D array of data  (right?) at the output of the "Get waveform component' bloc. I need to read every element, process it and then send it as a value further to a function input. So, how can i get every element of that array and send it further ?
    I hope I was clear with my problem.
    It would be great if you could provide me with some help. 
    Thanks alot,
    Andrei_L. 
    Solved!
    Go to Solution.

    And just for completeness sake:
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Example_VI_BD.png ‏24 KB

  • Help with Arrays

    hi, ive just started a java course about a month ago and am having trouble with an assignment (big trouble), basicly I was wondering if someone could help me in this program I am reading from a text file and trying to store the info in a 2d array the text file has 60 lines like this :
    1     Y1     -9.30     5.65     -5.02
    and my code is:
    public static String [][] readfile (String fileName)
              /*declare local variables*/
              String [][]data;
              String [] line;
              String [] temp;
              String token;
              int count = 0;
              String inputLine;
              data = new String[60][count];     
         try
                           /*try loop to catch exceptions*/               
              FileReader reader = new FileReader("Data_Set_1.txt");
              /*file name to be filled in above*/
              BufferedReader in = new BufferedReader(reader);
              boolean done = false;
              while(!done)
                   inputLine = in.readLine();
    /*readline() will return null and exit this loop at the end of a line*/
              if (inputLine == null)
                   done = true;
                   break;
    /*break the string up declare tokeniser and pass it the inputLine string*/
    StringTokenizer tokeniser = new StringTokenizer(inputLine);
    token = tokeniser.nextToken();/*this will need to be moved but where*/
                   temp = new String [count];
                   count++;
                   while (tokeniser.hasMoreTokens())
    /*tokeniser will return true if there is more file to be read */
                    for (int i = 0;i < count;i++)
                    temp[i] = token;     
                    }/*end for*/               
                   }/*while*/
                   for (int j=0;j <temp.length;j++)
                        line[j] = temp[j];
              }/*end outer while*/
              for (int genes = 0;genes < 59;genes++)
              {for (int col = 0;col < 5;col++)
              data[genes][col] = line[genes], line[col];
              }/*end inner for*/
         }/*end outer for*/
    }/*end try*/I left out the catch loop as it not relevant. I know that the line:
    data[genes][col] = line[genes], line[col];
    is wrong but I dont know how to fix it and cant find the answer anywhere, if anyone can spot any other mistakes it would be great to let me know and im sorry if Ive posted wrong or anything like that ill fix it next time, any help or comments would be much appreciated.
    Thanks

    No need to apologise for being new to Java. After all, that is what the forum is for! If you wanted to apologise about your nickname well.... it'll do. :-)
    Your thinking is right. However do give gimbal2's idea a little thought. I do not know what each row is storing but if the data for each row were in an object, then the object could use meaningful names and provide sensible formatting and so on. However I have not seen the details of the assignment that your teacher gave you so it may have to be arrays. But what you would have would be an array of object called LineData or Genes. You might cycle through the array asking each object to call out its name and a feature for example.
    In general you gain very little advantage by passing a "temp" array to another array "line" using an equals sign. The reason is that there is only one array it just has two names! A bit like pinning an extra registration plate on a car! If you really wanted two arrays you would have to investigate "cloning" of arrays. However if you add the temp array (or whatever you call it) to another array such as your two dimensional array, then you can re-use the temp name by applying "=new" to create a new array. This will not affect the existing "array within an array" because it no longer needs a name - it is located by a number now!!!
    Array[] is fast in Java but you have to give it a size before you can use it. Arraylist is less fast but has the ability to grow. Not that the speed difference will be at all noticeable. Actually the internal working of the Arraylist uses arrays and cloning and such like.
    thesonofdad has given some good code. Again I might consider putting it in gimbal2's object though.
    I have covered quite a lot of ground so feel free to ask questions.

  • Help with array's again

    Hello again
    I know im probably getting on peoples nerves now, but im still working on my lottery simulation. Ive tried different techniques, all of which have worked so far but now im trying a different way and have encountered a problem i cannot de-bug.
    Please can you have a look at my code, its probably obvious to most of you experts.
    int[] winners = new int[5];
    winners[0] = Lotto.drawBall();
    int num = Lotto.drawBall();
    for(int counter = 1; counter<5;){
        while(counter <= winners.length){
            if(num==winners[0] || num==winners[1] || num==winners[2] || num==winners[3] || num==winners[4]){
                num = Lotto.drawBall();
            else{
                winners[counter] = num;  //here is where my exception occurs
                counter++;
    System.out.print(winners[0]);
    System.out.println();
    System.out.print(winners[1]);
    System.out.println();
    System.out.print(winners[2]);
    System.out.println();
    System.out.print(winners[3]);
    System.out.println();
    System.out.print(winners[4]);I get an Array index out of bounds exception but i cannot see how.
    Please can you help me again??
    D_H

    int[] winners = new int[5];
    winners[0] = Lotto.drawBall();
    int num = Lotto.drawBall();
    for(int counter = 1; counter<5;){
    while(counter <= winners.length){ /*Here you should use counter < winners.length*/
    if(num==winners[0] || num==winners[1] ||
    s[1] || num==winners[2] || num==winners[3] ||
    num==winners[4]){
    num = Lotto.drawBall();
    else{
    winners[counter] = num;  //here is where
    re is where my exception occurs
    counter++;
    System.out.print(winners[0]);
    System.out.println();
    System.out.print(winners[1]);
    System.out.println();
    System.out.print(winners[2]);
    System.out.println();
    System.out.print(winners[3]);
    System.out.println();
    System.out.print(winners[4]);I get an Array index out of bounds exception but i
    cannot see how.
    Please can you help me again??
    D_Hcheck the while condition you are using count until it is equal to 5

  • Noob needs help with array manipulation

    First off, I'd like to say hello to eveybody!
    I'm trying to figure out how to search for a value in an array, delete the first occurence of it, and shift the rest of the array down one. Can anyone point me in the right direction of an algorithm, mabey?
    Any help is most appreciated!

    first of all, let me comment that for this purpouse, you're better using the ArrayList class.
    anyway, you would need to make a temporary array inside a method, and traverse the array in question using a loop. most people use a for loop.
    Then, put all the values of the old array into the temporary one, except for the one you dont want.
    after the loop, set the old array to equal the temporary array.

  • Need help with arrays in a survey

    I am making a survey using arrays to store the answers to 2 questions and output the frequencies of each answer, as well as the average rating for each question. When I do it in a structured manner, it works properly:
    import java.text.DecimalFormat;  //in order to format numbers
    import javax.swing.*;
    public class Music1
      public static void main (String[] args)
        int iCount = 0, iResponsesSum1 = 0, iResponsesSum2 = 0, iParticipants;
        double dResponsesAve1 = 0, dResponsesAve2 = 0;
        String sInput = "", sOutput = "", sOutput1 = "";
        int frequency1[] = new int[6];
        int frequency2[] = new int[6];
        iParticipants = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of participants\nin music taste survey:"));
        int responses1[] = new int[iParticipants];
        int responses2[] = new int[iParticipants];
        for (iCount = 0; iCount < responses1.length; iCount++)//for loop
          responses1[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rave music (1: awful - 5: great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display first input box
          responses2[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rock & Roll music (1: awful - 5 great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display second input box
          ++frequency1[responses1[iCount]];
          ++frequency2[responses2[iCount]];
          iResponsesSum1+= responses1[iCount];//sum answers for first question
          iResponsesSum2+= responses2[iCount];//sum answers for second question
        }//end for loop
        for (int rating = 1; rating < frequency1.length; rating++)
          sOutput1+=  " Participants who left rating " + rating + " \t" + frequency1[rating] + "\t" + frequency2[rating] + "\n";
        }//end for loop
        dResponsesAve1 = iResponsesSum1/(double)(responses1.length);
        dResponsesAve2 = iResponsesSum2/(double)(responses2.length);
        DecimalFormat myFormat = new DecimalFormat("0.00");
        sOutput = "\tMusic Survey Results\n\n\n\n" +
           " Number of participants: " + iParticipants + "\n\n" +
           " Rave average rating:  " + myFormat.format(dResponsesAve1) + "\n" +             " Rock average rating:  " + myFormat.format(dResponsesAve2) + "\n\n\n" +
           "\tRatings by music:\n\n" +
           "\t\t" +
           "Rave\tRock" + "\n" +
           sOutput1 + "\n";
        JTextArea outputArea = new JTextArea(20, 15);
        outputArea.setText(sOutput);
        JOptionPane.showMessageDialog(null, outputArea, "Music Survey", JOptionPane.PLAIN_MESSAGE);//output the message
      System.exit(0);//exit the program
      }//end main
    }//end classNow, the problems start when I try to transform that into classess that create survey object and methods to be performed on that object.
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    public class Music
         public int iCount;
         public int iRating;
         private int iResponsesSum1;
         private int iResponsesSum2;
         private int iParticipants;
         private double dResponsesAve1;
         private double dResponsesAve2;
         private String sInput;
         private String sOutput1;
         private String sOutput;
         private int responses1[];
         private int responses2[];
         private int frequency1[];
         private int frequency2[];
         public Music()
              setParticipants();
              iCount = 0;
              iRating = 0;
              iResponsesSum1 = 0;
              iResponsesSum2 = 0;
              iParticipants = 0;;
              dResponsesAve1 = 0;
              dResponsesAve1 = 0;
              iParticipants = 0;
              sInput = "";
              sOutput = "";
              sOutput1 = "";
              responses1 = new int[iParticipants];
              responses2 = new int[iParticipants];
              frequency1 = new int[6];
              frequency2 = new int[6];
         public void setParticipants()
              iParticipants = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of participants\nin music taste survey:"));
         public int getParticipants()
              return iParticipants;
         public void setResponses1()
              for (iCount = 0; iCount < responses1.length; iCount++)//for loop
                   responses1[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rave music (1: awful - 5: great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display first input box
         public void setResponses2()
              for (iCount = 0; iCount < responses1.length; iCount++)//for loop
                   responses2[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rock & Roll(1: awful - 5: great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display second input box
         public void setFrequency1()
              ++frequency1[responses1[iCount]];     
         public void  setFrequency2()
              ++frequency1[responses1[iCount]];     
         public void  setSum1()
              iResponsesSum1+= responses1[iCount];//sum answers for first question
         public int getSum1()
              return iResponsesSum1;
         public void  setSum2()
              iResponsesSum2+= responses2[iCount];//sum answers for first question     
         public int getSum2()
              return iResponsesSum2;
         public void setFrequenciesByRating()
              sOutput1+=  "Participants who left rating " + iRating + "               " + frequency1[iRating] + "                        " + frequency2[iRating] + "\n";
         public String getFrequenciesByRating()
              return sOutput1;
         public double getAverage1()
              dResponsesAve1 = getSum1()/(double)(responses1.length);
              return dResponsesAve1;
         public double getAverage2()
              dResponsesAve2 = getSum2()/(double)(responses2.length);
              return dResponsesAve2;
         public String toString()
              DecimalFormat myFormat = new DecimalFormat("0.00");
              sOutput = "                        Music Survey Results\n\n\n\n" +
                   "Number of participants: " + getParticipants() + "\n\n" +
                   "Rave average rating:  " + myFormat.format(getAverage1()) + "\n" +
                   "Rock average rating:  " + myFormat.format(getAverage2()) + "\n\n\n" +
                   "                        Ratings by music:\n\n" +
                   "                                                          " +
                   "Rave       Rock" + "\n" +
                   getFrequenciesByRating() + "\n";
              return sOutput;
    }Here is what I have for the main program:
    mport java.text.DecimalFormat;  //in order to format numbers
    import javax.swing.JOptionPane;
    public class MusicApp
         public static void main (String[] args)
              int iCount = 0, iRating = 0;
              int responses1[] = new int[6];
              Music survey = new Music();
              for (int iCount1 = 0; iCount1 < responses1.length; iCount1++)
                   survey.setResponses1();
              for (int iCount2 = 0; iCount2 < responses1.length; iCount2++)
                   survey.setResponses2();
              for (int iCount3 = 0; iCount3 < responses1.length; iCount3++)
                   survey.setFrequency1();
              for (int iCount4 = 0; iCount4 < responses1.length; iCount4++)
                   survey.setFrequency2();
              for (iRating = 1; iRating < responses1.length; iRating++)
                   survey.setFrequenciesByRating();
              JOptionPane.showMessageDialog(null,survey.toString(), "Music Survey", JOptionPane.PLAIN_MESSAGE);//output the message
              System.exit(0);//exit the program
    }This obviously doesn't work, it gives me an ArrayIndexOutOfBoundsException.
    I tried to twist it in every way I could think of, but I still couldn't get it to work. I would like the program to run as it does in the structured form.
    I think I have a problem with the scope of the variables, but I am really not sure, that's why I hope that someone can give me some insight into what I am doing wrong.
    So, please, any constructive comment or advice is greatly appreciated.

    By the way, have a good look at your Music constructor:
    setParticipants(); //this will only be called once!
    iCount = 0;
    iRating = 0;
    iResponsesSum1 = 0;
    iResponsesSum2 = 0;
    iParticipants = 0;; //double semicolon :)
    dResponsesAve1 = 0;
    dResponsesAve1 = 0;
    iParticipants = 0; //!!
    sInput = "";
    sOutput = "";
    sOutput1 = "";
    responses1 = new int[iParticipants]; //this creates an array of int with size 0 (see iParticipants)
    responses2 = new int[iParticipants]; //idem
    frequency1 = new int[6]; //this creates an array of size 6 [0,0,0,0,0,0]
    frequency2 = new int[6]; //idem

Maybe you are looking for