Me ajudem, nao to conseguindo incrementar qdo insiro os valores

8 respostas
N
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Vendas extends JFrame{
	
	private JTextArea outputArea;
	private String[] valores = {"200 - 299",
								"300 - 399",
								"400 - 499",
								"500 - 599",
								"600 - 699",
								"700 - 799",
								"800 - 899",
								"900 - 999",
								"1000 - 1k+"};
	private JTextField enterField;
	private int quantidadePessoas[];
	
	public Vendas() {
	
		Container container = getContentPane();
		container.setLayout(new BorderLayout());
		
		outputArea = new JTextArea(20, 30);
		quantidadePessoas = new int[valores.length];
		String output ="";
		output = "Valores" + "\tQuantidades de pessoas\n";
	
		
		enterField = new JTextField(10);
		
		enterField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					int aux = Integer.parseInt(e.getActionCommand());
					if ((aux >= 200) && (aux <300))
						++quantidadePessoas[0];
					else if ((aux >= 300) && (aux <400))
						++quantidadePessoas[1];
					else if ((aux >= 400) && (aux <500))
						++quantidadePessoas[2];
					else if ((aux >= 500) && (aux <600))
						++quantidadePessoas[3];
					else if ((aux >= 600) && (aux <700))
						++quantidadePessoas[4];
					else if ((aux >= 700) && (aux <800))
						++quantidadePessoas[5];
					else if ((aux >= 800) && (aux <900))
						++quantidadePessoas[6];
					else if ((aux >= 900) && (aux <1000))
						++quantidadePessoas[7];
					else if (aux >= 1000)
						++quantidadePessoas[8];
					
					enterField.setText("");
				}catch (NumberFormatException e1) {
					// TODO: handle exception
					JOptionPane.showMessageDialog(null, "digitar somente numeros");
					enterField.setText("");
					enterField.requestFocus();
				}
				
			}
			
		});
		
		for (int i=0; i<valores.length; i++) {
			 output += valores[i] + "\t" + quantidadePessoas[i] + "\n";
		}
		container.add(enterField, BorderLayout.NORTH);
		outputArea.setText(output);
		container.add(outputArea, BorderLayout.CENTER);
		
		
		setSize(300, 250);
		setVisible(true);
	}
	public static void main(String[] args) {
		Vendas app = new Vendas();
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

}

Eu tenho esse codigo, e qdo digito um valor de 200 pra cima é para incrementar o indice do vetor de quantidade de pessoas q ganham esse valor.
Alguem pode me dizer no que estou errando?

8 Respostas

bebad

onde ta a parte que incrementa ?
isso ja funciona com menos de 200 ?

N

a parte q incrementa ta no listerner do textfield

nao incrementa com nenhum valor

Mantu

No listener do seu campo de texto, vc esqueceu de atualizar o texto do seu JTextArea… O texto do JTextArea não vai se alterar sempre que o vetor quantidadePessoas se alterar… É você quem tem que atualizar o JTextArea

fabioaab

tente fazer:

quantidadePessoas[n]++;

ao invés de:
++quantidadePessoas[n];

Mantu

Fiz algumas modificações no seu código para chegar ao resultado que espera.
Note uma coisa: EVITE AO MÁXIMO concatenar uma variavel String usando o "+=". Isso é muito prejudicial para a performance. Veja lá no método preencherOutputArea como estamos usando o StringBuilder. Utilize esta classe sempre que quiser fazer concatenações desse tipo.

public class Vendas extends JFrame {

	private JTextArea outputArea;
	private String[] valores = {
		"200 - 299", "300 - 399", "400 - 499", "500 - 599", "600 - 699",
		"700 - 799", "800 - 899", "900 - 999", "1000 - 1k+"
	};
	private JTextField enterField;
	private int quantidadePessoas[];

	public Vendas() {

		Container container = getContentPane();
		container.setLayout(new BorderLayout());

		outputArea = new JTextArea(20, 30);
		quantidadePessoas = new int[valores.length];

		enterField = new JTextField(10);

		enterField.addActionListener(
			new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
						int aux = Integer.parseInt(e.getActionCommand());
						if((aux >= 200) && (aux < 300))
							++quantidadePessoas[0];
						else if((aux >= 300) && (aux < 400))
							++quantidadePessoas[1];
						else if((aux >= 400) && (aux < 500))
							++quantidadePessoas[2];
						else if((aux >= 500) && (aux < 600))
							++quantidadePessoas[3];
						else if((aux >= 600) && (aux < 700))
							++quantidadePessoas[4];
						else if((aux >= 700) && (aux < 800))
							++quantidadePessoas[5];
						else if((aux >= 800) && (aux < 900))
							++quantidadePessoas[6];
						else if((aux >= 900) && (aux < 1000))
							++quantidadePessoas[7];
						else if(aux >= 1000)
							++quantidadePessoas[8];
	
						enterField.setText("");
						preencheOutputArea();
					} catch (NumberFormatException e1) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(
							null,
							"digitar somente numeros");
						enterField.setText("");
						enterField.requestFocus();
					}
	
				}
			}
		);

		preencheOutputArea();
		
		container.add(enterField, BorderLayout.NORTH);
		container.add(outputArea, BorderLayout.CENTER);

		setSize(300, 250);
		setVisible(true);
	}
	
	private void preencheOutputArea() {
		StringBuilder sb = new StringBuilder("");
		sb.append("Valores\tQuantidades de pessoas\n");
		for (int i = 0; i < valores.length; i++) {
			sb.append(valores[i] + "\t" + quantidadePessoas[i] + "\n");
		}
		outputArea.setText(sb.toString());
	}

	public static void main(String[] args) {
		Vendas app = new Vendas();
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

}
Mantu

fabioaab:
tente fazer:

quantidadePessoas[n]++;

ao invés de:
++quantidadePessoas[n];


Neste caso, isto não influencia em nada.
A diferênça entre usar o operado ++ antes ou depois da variável indica apenas o momento em que a variável será incrementada.
O exemplo a seguir imprimirá “10” no console:

int i = 10;
System.out.println(i++);

Este exemplo, por sua vez, imprimirá 11:

int i = 10;
System.out.println(++i);

No primiero caso, o operador é de pós-incremento, ou seja, só fará o incremento após o término da instrução.
No segundo caso, o operador é de pré-incremento, ou seja, fará o incremento antes de executar a instrução.

N

putz, obrigado mesmo Mantu, ta perfeito

o fato de eu usar em String o " += " é pq ta livro da 4ª edição do deitel

ele concatena ate o capitulo 7 pelo menos usando +=, mas vo ler sobre StringBuilder no site da sun e procurar tirar essa mania q peguei do livro, obrigado

Mantu

nania:
o " += " é pq ta livro da 4ª edição do deitel

ele concatena ate o capitulo 7 pelo menos usando +=,


Deitel, Deitel… Que decepção! Espero que ele depois do tal capítulo 7 diga que não é legal usar += pra Strings… tsc, tsc, tsc…

Criado 16 de janeiro de 2007
Ultima resposta 16 de jan. de 2007
Respostas 8
Participantes 4