help with methods [closed]
I think my program should run, I'm just blanking on how to call these methods so it will work. Here's the code:
import java.util.*;
public class median {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// need to call methods
}
int[] arr;
int m;
public void selectio开发者_开发知识库nSort() {
Scanner input = new Scanner( System.in );
System.out.println("how many numbers in array: ");
m = input.nextInt();
System.out.println("enter"+m+" numbers: ");
int count=0;
while(count <m){
int num = input.nextInt();
arr[count]=num;
}
int i, j, minIndex, tmp;
int n = arr.length;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}
public void median(){
if (m%2==0){
double median = (arr[m/2]+arr[(m/2)+1])/2;
System.out.println("the median is "+median);
}
else {
System.out.println("the median is "+arr[(m/2)+1] );
}
}
}
You need to add the static
modifier to your methods and fields. If you don't understand why, I recommend you read the Learning the Java Language tutorial.
First: create an object from that class. Second: call the methods.
Like this:
public static void main(String[] args) {
// TODO Auto-generated method stub
// need to call methods
//creating object
Median m = new Median();
//calling methods from the object
m.selectionSort();
m.median();
}
UPDATE: You don't need to create the constructor unless you want to put some customized code in it.
PS: Class names: first letter in always in capitals = best practices.
public static void main(String[] args){
median m1 = new median();
m1.selectionSort();
m1.median();
}
Create an instance of yourself, and invoke the methods:
public static void main(String[] args) {
median me = new median();
me.selectionSort();
}
Incidentally, you should consider renaming median
to be Median
to conform with Java class naming conventions.
精彩评论