Adicionar "static" a metodos

8 respostas
tpiardi

Eu preciso adicionar o atributo static nesses metodos, para poder usa-los com minha main class.
Mas quando adiciono apenas static ai aparecem erros.
Podem me ajudar a converter isso?

Obrigado

public class Quicksort  {
	private int[] numbers;
	private int number;

	public void sort(int[] values) {
		// Check for empty or null array
		if (values ==null || values.length==0){
			return;
		}
		this.numbers = values;
		number = values.length;
		quicksort(0, number - 1);
	}

	private void quicksort(int low, int high) {
		int i = low, j = high;
		// Get the pivot element from the middle of the list
		int pivot = numbers[low + (high-low)/2];

		// Divide into two lists
		while (i <= j) {
			// If the current value from the left list is smaller then the pivot
			// element then get the next element from the left list
			while (numbers[i] < pivot) {
				i++;
			}
			// If the current value from the right list is larger then the pivot
			// element then get the next element from the right list
			while (numbers[j] > pivot) {
				j--;
			}

			// If we have found a values in the left list which is larger then
			// the pivot element and if we have found a value in the right list
			// which is smaller then the pivot element then we exchange the
			// values.
			// As we are done we can increase i and j
			if (i <= j) {
				exchange(i, j);
				i++;
				j--;
			}
		}
		// Recursion
		if (low < j)
			quicksort(low, j);
		if (i < high)
			quicksort(i, high);
	}

	private void exchange(int i, int j) {
		int temp = numbers[i];
		numbers[i] = numbers[j];
		numbers[j] = temp;
	}
}

8 Respostas

elton.souza

Quais erros aparecem?

tpiardi
public void sort(int[] values) {  
        this.numbers = values;  
        number = values.length;  
        quicksort(0, number - 1);  
    }

Non-static variable this canot be referenced from static context
Non-static variable number canot be referenced from static context

elton.souza

Um exemplo da main que está funcionando

public class Main { public static void main(String [] args){ int[] v = new int[]{0, 10, 22, 30}; Quicksort qs = new QuickSort(); qs.sort(v); System.out.println(v[0]+" "+v[1]+" "+v[2]+" "+v[3]); } }

Poste sua main pra vermos o que está errado.

natanSPR

tpiardi, voce quer usar o static nos metodos da sua classe Quicksort ?? ou no main ?
se possivel posta o codigo que deu erro…

BLV_DOOM_JAVA

Se vc quer utilizar static em métodos utilizados por instancia de classes sempre vai ocorrer erros, pois métodos static são métodos de classe, não dos objetos…
explicando melhor:

Vc tem uma classe chamada Contador…nessa classe vc tem o método contar…
veja bem:
Se vc quiser deixar esse método static vc sempre chamara ele dessa forma:

Contador.contar();

Um objeto instanciado a partir dessa classe nunca vai por utilizar esse método, ou seja:

Contador contador = new Contador(); contador.contar() // Não funciona da erro

Espero ter ajudado.

Rodrigo_Sasaki

se não me engano… se o seu método é estático… todas as variáveis da classe que forem usadas dentro dele, tem que ser estáticas também…

se a variável for criada dentro do método não tem problema… exemplo:

public static void sort(int[] values) {     
        this.numbers = values;  // a variável numbers é um atributo da classe, e se for usada em um método estático, tem que ser estática também   
        int number = values.length; // a variável number foi instanciada aqui dentro do método, então pode ficar do jeito que está    
        quicksort(0, number - 1);     
    }

acho que é mais ou menos isso… se falei besteira por favor alguém me corrija

tpiardi

valeu pessoal, declarei as variaveis como static e removi o this e funcionou!

V

tpiardi? Também conhecido como Strider? É você?

Criado 23 de maio de 2011
Ultima resposta 24 de mai. de 2011
Respostas 8
Participantes 6