Missing main() error [duplicate] - java

This question already has answers here:
Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) [duplicate]
(5 answers)
Closed 6 years ago.
I'm getting this error
Main method not found in class Bank, please define the main method as:
public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
Here is my Bank class
public class Bank { //Bank Class to calculate the value for infrastructure of each Bank
final int N = 9; // Equal to highest number in my CQU Student ID 12029103
int cost;
public int costPerBank(int numberOfComputers) {
// Calculate the total cost for numberOfComputers entered by the user
if (numberOfComputers == 0) { // When user enters '0' or negative values
cost=0;
}
if (numberOfComputers <= 2 && numberOfComputers >= 1) { // When user enters '1' or '2'
cost=1000;
}
if (numberOfComputers > 2 && numberOfComputers<=20) { // When user enters '3' to '20'
cost=1000+((numberOfComputers-2)*400);
}
if (numberOfComputers > 20 && numberOfComputers<=100) { // When user enters '21' to '100'
cost=1000+((numberOfComputers-2)*300);
}
if (numberOfComputers > 100) { // When user enters more than '100'
cost=numberOfComputers*200;
}
return cost;
}
}

A Java program needs to have a main method, essentially the starting point of the program. I suggest looking through some Java tutorials to get started, as they'll teach you stuff like this. Tutorialpoints is a good site.
Change the first few lines to:
public class Bank { //Bank Class to calculate the value for infrastructure of each Bank
final int N = 9; // Equal to highest number in my CQU Student ID 12029103
int cost;
public static void main(String[] args) {
(new Bank()).costPerBank(5);
}
(It creates a new Bank object, then calls the method on that.)
Simply defining a class won't do anything. It's like handing the computer tools (Methods), but not telling it to use (call) the tools.

public static void main(String[] args){
Bank bank = new Bank();
bank.costPerBank(1);
}
Put something like this in your class. This is the first method that is called when you run the program

Related

Problems with non-static variable inputs and trying to run methods

I've done a bunch research into trying to solve this issue (for about 2.5 hours), but I'm still not able to compile my program. I have tried making the method not static, but when attempting to run it, it gives me this error:
"Error: Main method is not static in class prog6, please define the
main method as: public static void main(String[] args)"
When the main method is static, I get following error in a compiler
Error: "non-static variable input cannot be referenced from a static
context
usd = input.nextDouble();"
I'm sorry if this question comes off redundant, I don't mean to ask without looking for an answer on my own, but I've been working at this for hours now and I don't understand what I'm doing wrong.
Some extra info on this program: it's meant to take inputs from the user to find out what currency they want to convert to, and how much USD they would like to convert. Then, I would invoke a method in order to do the calculations and return them. (Any amount trying to be converted over $200, will need 5% fee.)
import java.util.Scanner;
public class prog6
{
Scanner input = new Scanner(System.in);
public static void main (String[] args)
{
char curr = 0;
double usd;
double result;
while (curr!='Q' || curr!='q') { //loop
System.out.println("What type of currency would you like to buy?");
curr = input.next().charAt(0);
System.out.println("How many dollars would you like to convert?");
usd = input.nextDouble(); //asking user for info needed to convert
if (usd>200) {
usd = (usd)*(0.95);
}
result = calc (curr,usd); //invoke the method
}
}
public double calc (char mCurr,double mUsd) //method
{
if (mCurr=='E' || mCurr=='e') {
return (mUsd)*(0.88);
}
else if (mCurr=='P' || mCurr=='p') {
return (mUsd)*(0.77);
}
else if (mCurr=='Y' || mCurr=='y') {
return (mUsd)*(113.17);
}
return 0;
}
}
The main method will need to be static. From there, create an instance of your class and call a non-static method from the static main method. eg..
public class Prog6 {
private Scanner input = new Scanner(System.in);
public static void main (String[] args) {
Prog6 prog6 = new Prog6();
prog6.start();
}
public void start() {
char curr = 0;
double usd;
double result;
// etc...
}
}
You could make the member variable static but it's better form to use regular non-static members and methods and call this from the static main method.
There are two ways to solve your prolem
Change the input variable to static;
or
In main method, prog6 myprog= new prog6(); and refer input as myprog.input ....

Program not working?

The question is to find the number of days between two dates.example-input-26/3/2000 and 12/8/2014.the output will be the no of days in between these two dates.
There is an error saying "identifier expected" and i=1 is highlighted.Also I am not sure whether the program is completely correct.
import java.util.*;
class yearst
{
int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
int i,s,s1,s2,s3,k,diy,m,m1,m2,d1,d2,y1,y2,y;
i=1;s1=0;s2=0;s3=0;diy=365;
void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
ob.leap(i+1)
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
ob.leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
ob.leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s)
}
}
Please help.
Your program is a bunch of errors. First, you are calling class variables in main method without declaring them static or initializing them in constructor. Second, you are calling leap() which is method of a class from object of Scanner. It is not possible. The program will never compile nor run this way. I have modified your code to make it compilable and runnable. But one thing is for sure. Its logic is incorrect. It is giving wrong output as you want to calculate number of days between two dates. That is your job. I removed its errors. Now it is running. Here you are :-
import java.util.*;
class yearst
{
static int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
static int i=1,s,s1=0,s2=0,s3=0,k,diy=365,m,m1,m2,d1,d2,y1,y2,y;
static void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
//i=1;s1=0;s2=0;s3=0;diy=365;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
leap(i+1);
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s);
}
}
All the Best :)
Only declarations and static blocks allowed out of the methods. The below executable statement must be either in static block or in constructor
int i=1,s1=0,s2=0,s3=0,diy=365;
So, I recommend you move above code to constructor.
yearst(){
i=1;s1=0;s2=0;s3=0;diy=365;
}
A few things:
You'll need to initialize your variables inside a constructor, as initializing inside a class isn't allowed
Have you checked out the Date class in Java? It might be more useful for this case.
According to convention, class names should start with a capital letter

Creating an Array class from a UML diagram with a working driver class in java

I am having the most difficult time trying to convert a UML diagram into runnable java code. I am given:
Array
- array:double[]
+setArray(arr:double[]):void
+isInIncreasingOrder():boolean
+isInDecreasingOrder():boolean
+getTotal():double
+getAverage():double
I am not given what the length of the array should be, so I am assuming that the user must input them. It then asks for a driver class TestArray to test all of the methods.
So far, this is all I have, and I can't seem to find how else to go about finishing it:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I know basically how to get user input, but without a proper Driver Class I can't run anything and make sure it works?

Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1 [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
Pre Edit: The problem is when I mark it as static, so
public static int printMenuGetSelection()
it gives me the message
This Static method cannot hide the instance method from AMenu
I'm writing a Java program that reads files and gives the user multiple options for displaying things about the file. I'm currently writing a menu interface that implements an actual Interface and makes the program easier to use. However, I'm getting an exception when I try to call the menu method in my main method. The error is on the one active line in the main method where I call printMenuGetSelection(), and it says
Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1
How do I fix this bug? here is my program:
import java.util.*;
import java.io.*;
import java.text.*;
public class SpecialAssignment1 implements AMenu {
public static void main(String[] args) throws FileNotFoundException{
printMenuGetSelection();
/*System.out.println(RewardCustomer("transactions1.dat")); //CURRENTLY DISPLAYING TOP 6, DOESN'T WORK WITH TIES OR TOPN < lines
ProcessTransactionsFile("transactions2.dat", 52);*/
}
public int printMenuGetSelection() throws FileNotFoundException{
boolean runProgram = true;
Scanner s = new Scanner(System.in);
printStartMenu();
String startMenuSelection = s.next();
while(runProgram){
if(startMenuSelection.equals("1")){
startMenu1();
} else if(startMenuSelection.equals("2")){
startMenu2();
} else if(startMenuSelection.equals("3")){
startMenu3();
} else if(startMenuSelection.equals("4")){
startMenu4();
} else if(startMenuSelection.equals("5")){
runProgram = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
return 1;
}
public static void printStartMenu(){
System.out.println("**********************************************************");
System.out.println("Main Menu...");
System.out.println(" (1) RewardCustomers");
System.out.println(" (2) ProcessTransactionFiles");
System.out.println(" (3) TopCustomers");
System.out.println(" (4) QueryStatsFile");
System.out.println(" (5) Quit");
System.out.println(" Enter a valid selection: ");
}
public static void startMenu1() throws FileNotFoundException{
boolean runMenu1 = true;
while(runMenu1){
Scanner s = new Scanner(System.in);
System.out.println("Reward Customers Menu...");
System.out.println(" (1) Use transactions1.dat");
System.out.println(" (2) Use transactions2.dat");
System.out.println(" (3) Quit");
System.out.println(" Enter a valid selection: ");
String menu1Selection = s.next();
if(menu1Selection.equals("1")){
System.out.println(RewardCustomer("transactions1.dat"));
} else if(menu1Selection.equals("2")){
System.out.println(RewardCustomer("transactions2.dat"));
} else if(menu1Selection.equals("3")){
runMenu1 = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
}
public static void startMenu2(){
boolean runMenu2 = true;
while(runMenu2){
Scanner s = new Scanner(System.in);
System.out.println("Process Transaction Files Menu...");
System.out.println(" (1) Create transactions2.dat file");
System.out.println(" (2) Display transactions1.dat");
System.out.println(" (3) Display transactions2.dat");
System.out.println(" (4) Query transactions1.dat");
System.out.println(" (5) Query transactions2.dat");
System.out.println(" (6) Quit");
System.out.println(" Enter a valid selection: 4");
String menu2Selection = s.next();
if(menu2Selection.equals("1")){
}
}
}
public static void startMenu3(){
}
public static void startMenu4(){
}
I removed the code not pertaining to the question to make it easier to read, if it's needed I'll put it in. Also, here is the AMenu Interface. Please do not suggest any other changes to my program. If you think it's dumb to have the menu as an Implemented Interface, I 100% agree with you but that's the requirement. For reference, here is the AMenu Interface:
import java.io.FileNotFoundException;
public interface AMenu {
/**
* Prints a menu with selections and logic to return a valid selection.
* #return the selected item
*/
abstract int printMenuGetSelection() throws FileNotFoundException;
/**
* #return the numberOfMenuItems
*/
abstract int getNumberOfMenuItems();
}
Since printMenuGetSelection() is non static, you cannot call it from within the static method main() unless you create an instance of SpecialAssignment1 and call the method on that object.
you need to create an instance of your SpecialAssignment1 then call the method from that, as abstract requires an object.
As other people have said, you need to create an instance of SpecialAssignment1, then call printMenuSelection() on it. Part of what's making this confusing though is that you've stuck the main method inside the menu interface class. This whole thing would make more sense if you had a class SpecialAssignment1 with just the main method and a separate MenuGenerator class with all the menu generation stuff.

Java: index in array exists, ArrayIndexOutOfBoundsException: 0

Sorry if this is answered somewhere due to me missing something obvious, but I've been googling this for days now and it just doesn't seem to make any sense. I've got 3 years of experience in Javascript and am getting into Java now, so I'm not behind on the basic concepts of anything and such.
I'm using IntelliJ for this, but it fails to point out the problem. The communication (access rights and instantiations) between my classes is fine, the code syntax and variable types are as well, etc, so I really can't tell what it is.
I have a Data class, which just holds "read-only" data for the other classes to use.
public class Data {
// snip
public static int[][] specs = {
{6,1,6,40},
{5,2,5,30},
{5,3,4,40},
{4,4,3,60}
};
}
There's another class that has to read this data when it's initialized.
public class Soldier {
// snip
public int range;
public Soldier() {
int x = ...; // user input
range = Data.specs[x][1];
}
}
The specs array itself contains its data as defined (ie the array is not empty), x is valid as an index of the specs array (ie 0 <= x <= 3), its type is int and Test has read access to the specs array (all confirmed with debug output statements). And yet, when it tries to set the value of range (then and only then, at that exact point), I get the "Index out of bounds" error.
Can someone please tell me what's going wrong when trying to read the array? Or am I right in saying that this is really weird and I need to post the entire code?
Note: a small new test also shows that, if I change the code to first output a manually chosen value from the array and then set the value of range, the console prints the error statement (and exits the program) and follows it up by printing the manually picked value, but assigning the value and then asking to output range only throws the error... That makes absolutely no sense at all!
Edit: I've edited the code above. The class called Test is called Soldier in my code (I'm making a text-based game...). Below's the stack trace, if it's any good without the full code (which is way long). The basic structure of my program is this:
1) Boot contains the main method and instantiates a new Game
2) Game instantiates x Teams
3) each Team instantiates an Army
4) each Army instantiates x Soldiers
Each instance of the classes is set as an attribute of the instantiating class (public Army army; and an Army instantiation in the Team constructor, for example). It's essentially a cascade of constructors instantiating subsequent classes and assigning them as their attributes.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Army.<init>(Army.java:13)
at Team.<init>(Team.java:19)
at Game.<init>(Game.java:22)
at Boot.main(Boot.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)5
Edit edit: here's the semi-full code (I'm leaving out the stuff that has absolutely nothing to do with it, including the imports). It's in no particular order and the classes are in separate .java files within the IntelliJ project. The game continues up to the point where a new Soldier asks for its type to be designated (the function performing the user input is working fine and validating the input as proven by a technically identical other part of the game).
public class Boot {
public static void main(String[] args) {
Object[] games = new Object[] {};
if (Lib.userConfirmPrompt("Start the game?") == true) {
do {
games[games.length] = new Game();
}
while (Lib.userConfirmPrompt("Do you want to play again?") == true);
}
System.exit(0);
}
}
public class Game {
public Object[] teams = new Object[] {};
public Game() {
for (int i = 0;i < settings.xbots + 1;i++) {
teams[teams.length] = new Team(this);
}
}
}
public class Team {
public Game game;
public Army army;
public Team(Game p) {
game = p;
army = new Army(this);
}
}
public class Army {
public Team team;
public static Object[] soldiers = new Object[] {};
public Army(Team p) {
team = p;
for (int i = 0;i < team.game.settings.xsoldiers;i++) {
soldiers[soldiers.length] = new Soldier(this);
}
}
}
public class Soldier {
private Army army;
public int sight;
public int range;
public int distance;
public int damage;
public Soldier(Army p) {
army = p;
int type = Lib.userTxtIntOptionsPrompt(Data.isoldiertypes);
// HERE is where it crashes, type is assigned and valid but the array access fails
sight = Data.isoldierspecs[type][0];
range = Data.isoldierspecs[type][1];
distance = Data.isoldierspecs[type][2];
damage = Data.isoldierspecs[type][3];
}
}
public class Data {
public static List isoldiertypes = Arrays.asList("Scout","Private","Machinegunner","Grenadier");
public static int[][] isoldierspecs = {
{6,1,6,40},
{5,2,5,30},
{5,3,4,40},
{4,4,3,60}
};
}
public class Lib {
private static Scanner input = new Scanner(System.in);
// output
// default: 1 query string to print
public static void outBase(String query) {
System.out.print(query);
}
public static void outStd(String query) {
outBase(query + "\n");
}
// end of output
// input
// default: 1 query string to print,
// query and input are in-line (exception: userConfirmPrompt prints query block-wise and default instruction in-line before input),
// keeps user hostage until valid input is given (exception: userPrompt returns blindly)
public static String userPrompt(String query) {
outBase(query);
return input.nextLine();
}
public static String userTxtPrompt(String query) {
String menuinput = null;
do {
if (menuinput != null) {
userHostage();
}
menuinput = userPrompt(query);
} while (menuinput.length() == 0);
return menuinput;
}
public static int userIntPrompt(String query) {
String menuinput = null;
do {
if (menuinput != null) {
userHostage();
}
menuinput = userTxtPrompt(query);
} while(menuinput.matches("^-?\\d+$") == false);
return new Integer(menuinput);
}
// end of input
// options input
// default: takes a List of options as argument,
// prints an enumerated list of these options string-wise,
// prompts for a numeral selection of the desired option and returns the number if valid
public static int userTxtIntOptionsPrompt(List options) {
int choice = 0;
Boolean chosen = false;
do {
if (chosen == true) {
userHostage();
} else {
chosen = true;
}
chosen = true;
for (int i = 0;i < options.size() - 2;i++) {
outStd((i + 1) + ") " + options.get(i) + ",");
}
outStd((options.size() - 1) + ") " + options.get(options.size() - 2) + "\nand " + options.size() + ") " + options.get(options.size() - 1) + ".");
choice = userIntPrompt("Enter the number of the option you'd like to select: ") - 1;
} while(choice < 0 || choice >= options.size());
return choice;
}
// end of options input
// miscellaneous
public static void userHostage() {
outStd("Invalid operation. Please try again.");
}
}
The problem is in your Army class:
public static Object[] soldiers = new Object[] {};
You initialize an empty (length == 0) array named soldiers, but later you access:
soldiers[soldiers.length] = new Soldier(this);
This causes the failure.
By definition, soldiers.length is out of the bound of the array (since the bound is from 0 to soldiers.length-1)
To overcome it - make sure you allocate enough space in the array soldiers or use a dynamic array (ArrayList) instead. You can append elements to an ArrayList using ArrayList.add(), and you don't need to know the expected size before filling it up.
The x should be greater than -1 and less than 4.
The stacktrace does not mention the Solder class, its in the conctructor of the Army class.
Any how, only knowing that the index should be within a range is not enough. As a programmer its your duty to validate the index before trying to access an element at that index.
if(index > 0 && index < array.length) {
//then only acess the element at index
Problem is the array soldiers is of size 0.
This line int x = ...; // user input implies that you are taking input in some fashion from the user and accessing the array with it. Are you checking this value to see that is in range (i.e., between 0 and 3)? If not, this may be why your testing works.
Edit: something like this might solve it for you:
public class Army {
public Team team;
public Vector<Soldier> soldiers;
public Army(Team p) {
soldiers = new Vector<Soldier>()
team = p;
for (int i = 0;i < team.game.settings.xsoldiers;i++) {
soldiers.add(new Soldier(this));
}
}
}
Judging by your other code, this sort of pattern will be useful in your Game object as well.

Categories

Resources