boa noite pessoal,tenho 2 vetores um do tipo int e outro do tipo teste,eu queria copiar os valor do vetor de int para o vetor teste,mais como eu faço a conversão dos valores?
public class teste {
teste t[];
int[] vetor;
//int[] vetor2;
public teste(){
vetor = new int[10];
vetor[0] = 1;
vetor[1] = 2;
vetor[2] = 3;
}
public void copiarVetor(){
t = new teste[vetor.length];
int i;
for(i = 0; i < vetor.length; i++){
if(vetor[i] != 0){
t[i] = vetor[i];
System.out.println("vetor = " + t[i]);
}
}
}
public static void main(String[] args){
teste t = new teste();
t.copiarVetor();
}
}
Com t = new teste[vetor.length]; vc cria um vector de objetos do tipo teste e com vetor = new int[10]; vc cria um vecto de inteiros não teria como vc passar um tipo INT para um tipo Object, teria que criar um método para setar um atributo da classe teste como inteiro. De uma olhada mais sobre métodos GET e SET e sobre tipos primitivos e objetos.
crie o metodo get e o set valor,mais agora como faço para copicar os valores para o vetor de objeto?
public class teste {
teste t[];
int Valor;
int[] vetor;
//int[] vetor2;
public teste(){
vetor = new int[10];
vetor[0] = 1;
vetor[1] = 2;
vetor[2] = 3;
}
public void copiarVetor(){
t = new teste[vetor.length];
int i;
for(i = 0; i < vetor.length; i++){
if(vetor[i] != 0){
t[i] = vetor[i];
System.out.println("vetor = " + t[i]);
}
}
}
public static void main(String[] args){
teste t = new teste();
t.copiarVetor();
}
public int getValor() {
return Valor;
}
public void setValor(int valor) {
Valor = valor;
}
}
Cara ta confuso esse teu codigo, vc esta instanciando teste dentro de sua propria classe, como vector … para alterar seria t[i].setValor(vetor[i]);. Mas esta muito mal codificada.
public class Main {
Teste t[];
int[] vetor;
public Main(){
vetor = new int[3];
vetor[0] = 1;
vetor[1] = 2;
vetor[2] = 3;
}
public void copiarVetor(){
t = new Teste[vetor.length];
int i;
for(i = 0; i < vetor.length; i++){
if(vetor[i] != 0){
t[i].setValor(vetor[i]);
System.out.println("vetor = " + t[i].getValor);
}
}
}
public static void main(String[] args){
Main m = new Main();
m.copiarVetor();
}
}
class Teste{
int valor;
public Teste() { }
public int getValor(){
return valor;
}
public void setValor(int valor){
this.valor = valor;
}
}
falta arrumar alguns detalhes para funcionar perfeitamente…
Que viagem.
Tá dando erro porque t = new Teste[vetor.length]; cria um array de Teste nulos.
Agora, afinal qual o seu objetivo? Não, não é fazer esse pseudo-parse de int pra sua classe. Acho que você se perdeu na sua lógica.
Ah, mais uma coisa: estude as convenções de código.