...

View Full Version : Global Variables In Java



Antoniohawk
05-27-2004, 03:51 AM
How would I declare the variable numbers as global? I want to be able to access the same variable from any method so that the value of the variable is the same.


import TerminalIO.KeyboardReader;

public class SortAndDestroy{

public static void main (String[] args){
int[] numbers = {42,37,5,33,6};
KeyboardReader reader = new KeyboardReader();
int choice;

for(int i = 0; i < Names.numbers.length; i++){
System.out.print(numbers[i] + " ");
}

choice = reader.readInt("\nSelection[1] or Bubble[2] Sort? ");

if (choice == 1)
selectionSort(numbers);
else if (choice == 2)
bubbleSort(numbers);
else
System.out.println("That is not a choice.");
}

public static void selectionSort(int[] numbers){
for(int i = 0; i < numbers.length; i++){
int minIndex = findMinimum(numbers, i);
if(minIndex != 1)
swap(numbers, i, minIndex);

System.out.print(numbers[i] + " ");
}
}

public static int findMinimum(int[] numbers, int first){
int minIndex = first;

for(int i = first + 1; i < numbers.length; i++)
if(numbers[i] < numbers[minIndex])
minIndex = i;

return minIndex;
}

public static void swap(int[] numbers, int x, int y){
int temp = numbers[x];
numbers[x] = numbers[y];
numbers[y] = temp;
}

public static void bubbleSort(int[] numbers){
int k = 0;
boolean exchangeMade = true;

while((k < numbers.length - 1) && exchangeMade){
exchangeMade = false;
k++;
for(int j = 0; j < numbers.length - k; j++)
if(numbers[j] > numbers[j + 1]){
swap(numbers,j,j + 1);
exchangeMade = true;
}
}
}
}

hkucsis
05-27-2004, 05:47 AM
public class SortAndDestroy{
int[] numbers = {42,37,5,33,6};
public static void main (String[] args){
...

Spookster
05-27-2004, 07:00 AM
That's usually a bad idea. You don't want to give everyone access to a local variable. Instead make the variable private but create a public method within that class that returns the value.

Edit: Never mind. I misread your question. I thought you wanted to give other classes access to the variables in that class. As was posted already just declare the variable outside of your methods. That will put it into the scope of all your methods.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum