Results 1 to 2 of 2
- 08-05-2007, 03:56 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
How would I declare the variable numbers as global?
Hi, 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.
Thanks.Java Code: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; } } } }
- 08-06-2007, 02:17 AM #2
Senior Member
- Join Date
- Jul 2007
- Posts
- 130
- Rep Power
- 0
U could put the variable inside the class definiton, meaning, under the code and outside of any method declaration, example
If u want the value remains the same for every instance u created, u could use the keyword static in front of the variable definitionJava Code:public class SortAndDestroy{ int global; public void static main(String[] args) { ....and so on....}
Similar Threads
-
Global constants
By Java Tip in forum Java TipReplies: 0Last Post: 02-17-2008, 09:06 AM -
Where is it best to declare swing components?
By MacNstuff in forum AWT / SwingReplies: 1Last Post: 02-06-2008, 12:59 AM -
Declaring global variables
By eva in forum New To JavaReplies: 3Last Post: 12-23-2007, 12:11 AM -
Defining global session scope in spring framework
By JavaBean in forum Java TipReplies: 0Last Post: 09-28-2007, 12:47 PM -
save global data in servlets
By Marty in forum Java ServletReplies: 1Last Post: 05-31-2007, 06:38 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks