Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am trying to find away to get the user to input the number of cannonballs/ammo

ID: 639955 • Letter: I

Question

I am trying to find away to get the user to input the number of cannonballs/ammo they would like to use. The assignment requires the "ammo" to be a static variable. Please Help!

import java.util.Scanner;

public class Cannon{

private static int ammo;

public static void setAmmo(int myAmmo)
    {
       
        System.out.println("Enter the number of Cannon Balls:");

        Scanner in = new Scanner(System.in);

        myAmmo=in.nextInt();
        ammo=myAmmo;
        System.out.println("The amount of ammo is now : " + ammo);
    }

}

This is the error I get when i try to call the method from another class.

error: non-static method setAmmo(int) cannot be referenced from a static context
    Cannon.setAmmo(0);
          ^

Explanation / Answer

import java.util.Scanner;

public class Cannon{

private static int ammo;

public static void setAmmo(int myAmmo)
    {
       
        System.out.println("Enter the number of Cannon Balls:");

Scanner in = new Scanner(System.in);
        myAmmo=in.nextInt();
        ammo=myAmmo;
        System.out.println("The amount of ammo is now : " + ammo);
    }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote