如何在main中调用void方法?

时间:2017-12-01 11:45:25

标签: java methods void

public void AmPm(int time) {
 if (time >= 12 && time < 12)
   System.out.println("AM");
 else if (time >= 12 && time < 24)
   System.out.println("PM");
 else
   System.out.println("invalid input");}

如何在main方法中调用此方法

3 个答案:

答案 0 :(得分:1)

主要方法是静态的,静态方法只能调用静态方法。 你能做的是:

class A {
    public void amPm(int time) {
       if (time >= 0 && time < 12) //you have a typo there
           System.out.println("AM");
       else if (time >= 12 && time <24)
           System.out.println("PM");
       else
           System.out.println("invalid input");
    }
    //or as static method:
    public static void amPmInStaticWay(int time) { //... }

    public static void main(String[] args) {
        //...
        A a = new A();
        a.amPm(time);
        //or
        amPmInStaticWay(time);
        //or if you want to use static method from different class
        A.amPmInStaticWay(time);
    }
}

答案 1 :(得分:1)

您需要创建类public static void main(String[] args) { A a = new A(); a.amPm(time); /* instead of typing "time" you need to pass int value that you want to be passed to the method as an argument */ } 的对象实例,因为此方法不是静态的。然后你可以在那个引用上调用该方法:

using System.Linq;
...

//cast ListViewItemCollection as List<ListViewItem> for easier manipulation
var items = listView1.Items.Cast<ListViewItem>();
//first, get all items that don't have text matching with textBox text
List<int> itemIndexes = 
    items
        .Where(item => !item.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
        .Select(item => item.Index).ToList();
int val;
//now, with all those indexes do your stuff
itemIndexes.ForEach(index =>
    {
        int.TryParse(listView1.Items[index].SubItems[4].Text, out val);
        store[pos] = val;
        pos++;
        count++;
    });

//lastly, sort indexes descending (for example: 10, 5,4,1) and remove them from listview
itemIndexes
    .OrderByDescending(i=>i)
    .ToList()
    .ForEach(index => listView1.Items.RemoveAt(index));

答案 2 :(得分:0)

你的方法不是静态的,所以你应该从这个方法所属的类创建对象。 这个想法是: 静态方法属于类级别,因此您无法从静态方法调用非静态方法。