java parse to array

hi I have a problem ibeen trying to do this assignment in so many ways but still cannot figure how to do it, Iwas asked to do a program wheresomeone enters the number of students in a class then theyn would enter a number for each student, for examble you are asked how many students in you class so you enter 5 (5 could be any number) then you will be aske number for student 1, number for student 2, number for student n so then you have the number 5 that I can easily work with and also have 5 other numbers lets assume they are 5,5,5,5,5 this is asked through an object joptionpane then i have int[] x how can i do it so x=5,5,5,5,5 this is what i have so far but I am willing to change anything that is needed



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package promedio;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
*
* @author ***********
*/
public class promedio {
public static void main(String[] args) {

JFrame f = new JFrame("Promedio de calificaciones");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Ingresar la siguiente calificacion");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Component source = (Component) actionEvent.getSource();
Object response = JOptionPane.showInputDialog(source,
"¿Cual es la calificacion?", "Promedio de calificaciones",
JOptionPane.QUESTION_MESSAGE, null, new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" },
"10");

String x = (String) response;
    /*int y = Integer.parseInt(x);

    int[] nums = getIntBytesFromInt(int y);*/

String[] sNums = x.split(",");
x = new int[ sNums.length ];
for( int i = 0; i< sNums.length; i++) {
x[ i ] = Integer.parseInt( sNums[i] );

}
};
button.addActionListener(actionListener);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);


 
}}
tlak83Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

a_bCommented:
Try looking at a  StringToeknizer example.
0
a_bCommented:
See this - public class Test
{
    public static void main(String args[])
    {
      
        String test = "1,2,3,4,5";
        StringTokenizer st = new StringTokenizer(test, ",");
        while (st.hasMoreTokens())
        {
        String token = st.nextToken();
        System.out.println("token = " + token);
        }
    }
}
0
tlak83Author Commented:
Chek this, I tried the tokenizer as you mentioned but is not compatible with my code, the bold part is where the problem is, my only limitation with this is that is an assignment and have to use the for loop basically what I need is to be able to input the numbers and then parse them into an array so I can use them with the for loop to get an average of the numbers inserted, do you know what is wrong with the code.
 
Thank you for your help i hope you know how to do this


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package promedio;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import javax.swing.*;

/**
*
* @author ***********
*/
public class promedio {
public static void main(String[] args) {

JFrame f = new JFrame("Promedio de calificaciones");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Ingresar la siguiente calificacion");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Component source = (Component) actionEvent.getSource();
Object response = JOptionPane.showInputDialog(source,
"¿Cual es la calificacion?", "Promedio de calificaciones",
JOptionPane.QUESTION_MESSAGE, null, new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" },
"10");





String t = (String) response;
StringTokenizer st = new StringTokenizer(t, ",");
while (st.hasMoreTokens())
{
String token = st.nextToken();



String[] sNums = token.split(",");
token = new int[ sNums.length ];
for( int i = 0; i< sNums.length; i++) {
token[ i ] = Integer.parseInt( sNums[i] );

}

}}};

button.addActionListener(actionListener);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);



}}
0
Webinar: Miercom Evaluates Wi-Fi Security

It's not just about Wi-Fi connectivity anymore. A wireless security breach can cost your business large amounts of time, trouble, and expense. Plus, hear first-hand from Miercom how WatchGuard's Wi-Fi security stacks up against the competition in our upcoming webinar!

a_bCommented:
if you just need the average you donot need to store it the array.

What you can do is -

float avg =0;
int sum = 0;
int numTokens = st.countTokens();
while (st.hasMoreTokens())
{
String token = st.nextToken();
sum  =sum + Integer.parseInt(token);
}

avg = ((float)sum/(float)numTokens);


PS: the points allocated for the question are really low for the effort put in by me.
0
tlak83Author Commented:
the problem is that I am asked to do it with the for loop so the code you just posted will not wok
0
tlak83Author Commented:
how manypoints do you think are right for your effort, I think we can get into an agreement if you have the right solution
0
a_bCommented:
int[] token = new int[ st.countTokens()];
        int i=0;
        while (st.hasMoreTokens())
        {
        String str = st.nextToken();
        token[ i++ ] = Integer.parseInt(str );
        }

PS: Please increase points allocated, too much effort for just 50pts
0
a_bCommented:
increase to 500
0
tlak83Author Commented:
I will definitely raise the points this is the first question I ask for a long time so I dont really know how many points Ishould allocate so it would be a good idea for you to give me an idea.

Now about my question letme refrase it, I have an assignment, basically i need a program where someone will be able to enter the number of students in a group and then a number for each student, then those numbers to be parsed and using the for loop and Ican only use the for loop to get an average of them

as soon as you letme know about the points i will raise them
0
tlak83Author Commented:
here you go
0
a_bCommented:
So a while loop will not do, only a for loop would do?
0
tlak83Author Commented:
that is correct, and there is where i been having problems i tried in so many ways to do it but always i get some incompatible error I was able to get the for loop to work but entering the values into the code, however when I attempt to get the values through a joptiopane i cant
0
a_bCommented:

import java.util.StringTokenizer;
 
 
public class Test
{
    public static void main(String args[])
    {
	
        String test = "1,2,3,4,19";
        StringTokenizer st = new StringTokenizer(test, ",");
        float avg =0;
        int sum = 0;
        
        int[] token = new int[ st.countTokens()];
        int i=0;
        int numTokens = st.countTokens();
        for(i=0;i<numTokens;i++)
        {
            String str = st.nextToken();
            token[ i++ ] = Integer.parseInt(str );
        }
        
        for(i=0;i<numTokens;i++)
        {
            avg = avg + token[i];
        }
        avg = ((float)avg/(float)numTokens);
        
        System.out.println(avg);
    }
}

Open in new window

0
a_bCommented:
You can try this as well, this computes the avg within the for loop.
import java.util.StringTokenizer;
 
 
public class Test
{
    public static void main(String args[])
    {
	
        String test = "1,2,3,4,5";
        StringTokenizer st = new StringTokenizer(test, ",");
        float avg =0;
        int sum = 0;
        
        int[] token = new int[ st.countTokens()];
        int i=0;
        int numTokens = st.countTokens();
        for(i=0;i<numTokens;i++)
        {
            String str = st.nextToken();
            token[ i] = Integer.parseInt(str);
        }
        
        for(i=0;i<numTokens;i++)
        {
            avg = (float)(avg*(i) + token[i])/(float)(i+1);
//            System.out.println(avg);
        }
        System.out.println(avg);
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tlak83Author Commented:
String test = "1,2,3,4,19";
 that has the numbers already assigned, that is not my problem, I can do that my problem is that i need to enter any set of numbers it could be 1 2 3 4 or 7 3 5 or any other set, that set of numbers has to be entered by the person that runs the program it should not be enbeded in the code that is my exact problem to transfer those numbers into the code that is why i asked for the array basically what i need is

a joptionpane or similar to ask for the set of numbers one by one or all at the same time i dont care

then those numbers to be somehow parsed so i can use them into the for loop yu dont even have to write the code as long as you can tell me what to use so is compatible

I have a code similar to your but instead of using tokens i use an array and then i get the acerage this way

int sum = 0;
for (int i = 0; i<Nums.length; i++)
{ sum+=Nums[i]; }
int average = sum / Nums.length;

my problem comes to get those numbers into the code through a joptionpane or similar
0
a_bCommented:
Then just say that test = joptionpane input
0
tlak83Author Commented:
okay, let me test it that way, will get back to you in about 5 minutes
0
tlak83Author Commented:
thank you very much I have been trying to do this for a long time I even tried this same thing but i supose the parsing to array was my problem this tokenizing is great.

Thank you again for all your time an effort
0
a_bCommented:
make sure you cast the input to match the string
0
a_bCommented:
Please grade the question. Thanks

--AB
0
tlak83Author Commented:
this worked great he took time to understand what i needed but definitely did not give up and gave me the right solution
0
tlak83Author Commented:
I did not have to cast it
0
tlak83Author Commented:
I jus want to add the final code in case someone else needs it



import java.util.StringTokenizer;
import javax.swing.JOptionPane;


public class promedio
{
    public static void main(String args[])
    {

        String test = JOptionPane.showInputDialog(null, "numbers");
        StringTokenizer st = new StringTokenizer(test, ",");
        float avg =0;
       

        int[] token = new int[ st.countTokens()];
        int i=0;
        int numTokens = st.countTokens();
        for(i=0;i<numTokens;i++)
        {
            String str = st.nextToken();
            token[ i] = Integer.parseInt(str);
        }

        for(i=0;i<numTokens;i++)
        {
            avg = (float)(avg*(i) + token[i])/(float)(i+1);
//            System.out.println(avg);
        }
        JOptionPane.showMessageDialog(null, avg);
    }
}



the numbers have to be entered in the joptionpane using comma after each value
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.