Не удается заставить программу печатать в командной строке или в файле отчета - PullRequest
0 голосов
/ 09 мая 2020

У меня есть программа, которая компилируется, но я не могу заставить ее печатать в командной строке или в файле отчета. Любая помощь приветствуется. Вот ошибка, которую я получаю:

Ошибка: основной метод не найден в классе Township, определите основной метод как: publi c stati c void main (String [] args) или JavaFX класс приложения должен расширять javafx.application.Application Нажмите любую клавишу, чтобы продолжить. .

    import java.util.*;
import java.io.*;


//Township class
class Township
{
   //instance variables
   String name;
   int households;
   int bicycles;
   double average;
   String tier;
   double funding;

   //constructor
   public Township(String name, int households, int bicycles)
   {
       this.name = name;
       this.households = households;
       this.bicycles = bicycles;
   }
   //calculate average bikes per household
   public void AverageBikes()
   {
       average = (double)bicycles/households;
   }
   //calculate the funding
   public void Funding()
   {
       if(average>=3.0) funding = 50000.00;
       else if(average>=2.0) funding = 40000.00;
       else if(average>=1.0) funding = 30000.00;
       else if(average>=0.5) funding = 20000.00;
       else funding = 0.00;
   }
   //calculate the tier
   public void Tier()
   {
       if(average>=3.0) tier = "One";
       else if(average>=2.0) tier = "Two";
       else if(average>=1.0) tier = "Three";
       else if(average>=0.5) tier = "Four";
       else tier = "Five";
   }
   //sort the townships in alphabetical order by township name
   public static void sort(Township t[], int n)
   {
       for(int i=0; i<n-1; i++){
           for(int j=i+1; j<n; j++){
               if(t[i].name.compareTo(t[j].name) > 0){
                   Township tmp = t[i];
                   t[i] = t[j];
                   t[j] = tmp;
               }
           }
       }
   }
}

//Driver class
class Driver
{
   //method to print the report
   public static void printReport(Township t[], int n)
   {
       //sort the list
       Township.sort(t, n);

       System.out.println ("Township           Number       Bicycles   Average Bikes   Proposed       Tier");
       System.out.println ("Name               Households   reported   Per household   Funding           Designation");

       //print the report
       for(int i=0; i<n; i++)
       {
           System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
               t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
       }
   }
   //method to get input from user
   public static Township getInput(Scanner sc)
   {
       System.out.print ("Enter the name of Township: ");
       String name = sc.nextLine();
       System.out.print ("Enter the number households: ");
       int household = sc.nextInt();
       System.out.print ("Enter the bicycles reported: ");
       int bicycles = sc.nextInt();

       Township town = new Township(name, household, bicycles);
       town.AverageBikes();
       town.Funding();
       town.Tier();

       return town;
   }
   //method to get input from file
   public static int readFile(Township town[]) throws IOException
   {
       //open the file
       Scanner sc = new Scanner(new File("town.txt"));

       int i=0;
       while(sc.hasNext())
       {
           String name = sc.nextLine();
           int household = sc.nextInt();
           sc.nextLine();
           int bicycles = sc.nextInt();
           sc.nextLine();

           town[i] = new Township(name, household, bicycles);
           town[i].AverageBikes();
           town[i].Funding();
           town[i].Tier();
           i++;     
       }
       return i;
   }

   //method to write the report to the file
   public static void writeFile(Township t[], int n) throws IOException
   {
       //sort the list
       Township.sort(t, n);

       FileWriter writer = new FileWriter("report.txt");
       PrintWriter pout = new PrintWriter(writer);


       pout.printf ("Township           Number       Bicycles   Average Bikes   Proposed       Tier\n");
       pout.printf ("Name               Households   reported   Per household   Funding           Designation\n");

       for(int i=0; i<n; i++)
       {
           pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
               t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
       }
       pout.close();
   }

   //main method
   public static void main (String[] args) throws IOException
   {
       //create an instance of Scanner class
       Scanner sc = new Scanner(System.in);
       //create an array of Townships
       Township town[] = new Township[10];

       int i= readFile(town);

       //processing
       while(true)
       {
           //menu
           System.out.println ("1. Input\n2. Report\n3. Exit");
           //prompt to enter a choice
           System.out.print("Enter choice: ");
           int n = sc.nextInt();

           switch(n)
           {
               case 1:
                   //get input from user
                   town[i] = getInput(sc);
                   i++;
                   break;
               case 2:
                   //print the report
                   printReport(town, i);
                   break;
               case 3:
                   //write to file
                   writeFile(town, i);
                   System.out.println ("Goodbye!");
                   return;
           }
       }      
   }
}


РЕДАКТИРОВАТЬ

Благодаря ответам я обновил ошибку и код.

Вот новая ошибка, которую я получаю:

Ошибка: исключение в потоке «main» java .util.InputMismatchException в java .base / java. util.Scanner.throwFor (Scanner. java: 939) в java .base / java .util.Scanner.next (Scanner. java: 1594) в java .base / java. util.Scanner.nextInt (Scanner. java: 2258) в java .base / java .util.Scanner.nextInt (Scanner. java: 2212) в Township.readFile (Township. java: 143) в Township.main (Township. java: 20)

Код:

import java.util.*;
import java.io.*;

//Township class
public class Township{
   //instance variables
   String name;
   int households;
   int bicycles;
   double average;
   String tier;
   double funding;
public static void main (String[] args) throws IOException{
       //create an instance of Scanner class
       Scanner sc = new Scanner(System.in);
       //create an array of Townships
       Township town[] = new Township[10];

       int i= readFile(town);

       //processing
       while(true)
       {
           //menu
           System.out.println ("1. Input\n2. Report\n3. Exit");
           //prompt to enter a choice
           System.out.print("Enter choice: ");
           int n = sc.nextInt();

           switch(n)
           {
               case 1:
                   //get input from user
                   town[i] = getInput(sc);
                   i++;
                   break;
               case 2:
                   //print the report
                   printReport(town, i);
                   break;
               case 3:
                   //write to file
                   writeFile(town, i);
                   System.out.println ("Goodbye!");
                   return;
           }
       }
   }
//==================================================================
   //constructor
   public Township(String name, int households, int bicycles)
   {
       this.name = name;
       this.households = households;
       this.bicycles = bicycles;
   }
   //calculate average bikes per household
   public void AverageBikes()
   {
       average = (double)bicycles/households;
   }
   //calculate the funding
   public void Funding()
   {
       if(average>=3.0) funding = 50000.00;
       else if(average>=2.0) funding = 40000.00;
       else if(average>=1.0) funding = 30000.00;
       else if(average>=0.5) funding = 20000.00;
       else funding = 0.00;
   }
   //calculate the tier
//==================================================================
   public void Tier()
   {
       if(average>=3.0) tier = "One";
       else if(average>=2.0) tier = "Two";
       else if(average>=1.0) tier = "Three";
       else if(average>=0.5) tier = "Four";
       else tier = "Five";
   }
   //sort the townships in alphabetical order by township name
   public static void sort(Township t[], int n)
   {
       for(int i=0; i<n-1; i++){
           for(int j=i+1; j<n; j++){
               if(t[i].name.compareTo(t[j].name) > 0){
                   Township tmp = t[i];
                   t[i] = t[j];
                   t[j] = tmp;
               }
           }
       }
   }
//==================================================================
   //method to print the report
   public static void printReport(Township t[], int n)
   {
       //sort the list
       Township.sort(t, n);

       System.out.println ("Township           Number       Bicycles   Average Bikes   Proposed       Tier");
       System.out.println ("Name               Households   reported   Per household   Funding           Designation");

       //print the report
       for(int i=0; i<n; i++)
       {
           System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
               t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
       }
   }
//==================================================================
   //method to get input from user
   public static Township getInput(Scanner sc)
   {
       System.out.print ("Enter the name of Township: ");
       String name = sc.nextLine();
       System.out.print ("Enter the number households: ");
       int household = sc.nextInt();
       System.out.print ("Enter the bicycles reported: ");
       int bicycles = sc.nextInt();

       Township town = new Township(name, household, bicycles);
       town.AverageBikes();
       town.Funding();
       town.Tier();

       return town;
   }
//==================================================================
   //method to get input from file
   public static int readFile(Township town[]) throws IOException
   {
       //open the file
       Scanner sc = new Scanner(new File("bicycledata.txt"));

       int i=0;
       while(sc.hasNext())
       {
           String name = sc.nextLine();
           int households = sc.nextInt();
           sc.nextLine();
           int bicycles = sc.nextInt();
           sc.nextLine();

           town[i] = new Township(name, households, bicycles);
           town[i].AverageBikes();
           town[i].Funding();
           town[i].Tier();
           i++;
       }
       return i;
   }
//==================================================================
   //method to write the report to the file
   public static void writeFile(Township t[], int n) throws IOException{
       //sort the list
       Township.sort(t, n);

       FileWriter writer = new FileWriter("report.txt");
       PrintWriter pout = new PrintWriter(writer);


       pout.printf ("Township           Number       Bicycles   Average Bikes   Proposed       Tier\n");
       pout.printf ("Name               Households   reported   Per household   Funding           Designation\n");

       for(int i=0; i<n; i++)
       {
           pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
               t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
       }
       pout.close();
   }//end method
}//end class

Ответы [ 2 ]

0 голосов
/ 09 мая 2020

Попробуйте следующее:

class Township {
    //instance variables
    String name;
    int households;
    int bicycles;
    double average;
    String tier;
    double funding;

    //constructor
    public Township(String name, int households, int bicycles) {
        this.name = name;
        this.households = households;
        this.bicycles = bicycles;
    }

    // Rest of Township class code...

    public static void main(String[] args) {
        // Do things...
    }
}

Взгляните на это: Essentials

Каждому приложению нужен один класс с основным методом. Этот класс является точкой входа для программы и является именем класса, переданным команде интерпретатора java для запуска приложения.


IOException передается вам по другой причине . Ответ на ваш вопрос дан.

0 голосов
/ 09 мая 2020

Я думаю, вы компилируете класс Township, у которого нет метода main (). Вы должны скомпилировать класс Driver, потому что класс Driver имеет метод main () и создает объект класса Township.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...