我希望构造函数一次又一次地输入

时间:2015-12-28 05:25:55

标签: java

这里是代码想要一次又一次地在构造函数中输入。

//gas class

package gas.mileage;

public class Gas {
     int miles; // miles for one tankful
      int gallons; // gallons for one tankful
      int totalMiles = 0; // total mailes for trip
      int totalGallons = 0; // total gallons for trip

      double milesPerGallon; // miles per gallon for tankful
      double totalMilesPerGallon; // miles per gallon for trip

    public Gas(int miles,int gallons) {

      // prompt user for miles and obtain the input from user
      //System.out.print( "Entered miles (-1 to quit): " );
     // miles = input.nextInt();

      // exit if the input is -1 otherwise, proceed with the program
      while ( miles != -1 )
      {
         // prompt user for gallons and obtain the input from user
         //System.out.print( "Entered gallons: " );
         //gallons = input.nextInt();

         // add gallons and miles for this tank to total
         totalMiles += miles;
         totalGallons += gallons;
            if(gallons!=0)
            {
                milesPerGallon=miles/gallons;
              //System.out.println("miles pr gallon :"+milesPerGallon); 
            }
            if(gallons!=0)
            {
                totalMilesPerGallon=totalMiles/totalGallons;
            //  System.out.println("total miles coverd using gallons :"+totalMilesPerGallon); 
            }
         //use if statement to check if gallons is 0.
         // caluclate miles per gallon for the current tank
         // Print out the milesPerGallon
  // Missing Part A

// end of Missing Part A

         //use if statement to check if totalGallons is 0.
         // calculate miles per gallon for the total trip.
        // Print out the totalMilesPerGallon 

// Missing Part B

// End of Missing Part B

         // prompt user for new value for miles
        // System.out.print( "Entered miles (-1 to quit): " );
         break;
         //miles = input.nextInt();
      } // end while loop     

}
    public void setmpg(double milesPerGallon)
    {
        this.milesPerGallon=milesPerGallon;
    }
    public double getmpg(){
        return this.milesPerGallon;
    }
}
// Main start
package gas.mileage;

import java.util.Scanner;

public class GasMileage {

    public static void main(String[] args) {

    // perform miles per gallon calculations

      Scanner input = new Scanner( System.in );

     int a=input.nextInt();
     int b=input.nextInt();
     Gas g=new Gas(a, b);
      Gas k=new Gas(60, 3);
      Gas l=new Gas(20, 5);


   System.out.println("vlaues are :"+g.getmpg());
   System.out.println("vlaues are :"+k.getmpg());
   System.out.println("vlaues are :"+l.getmpg());
   } // end main method 

}

我希望气体类构造函数输入不要一次又一次地使用enter code here也没有找到并且平均值是totalmilesprgallon = totalmiles / totalgallons (汽油里程)驾驶员关注汽车的行驶里程。一个司机有 通过记录每个容器使用的里程数和加仑数来跟踪几次旅行。开发 一个Java应用程序,它将为每次旅行输入里程驱动和使用的加仑(均为整数)。 程序应计算并显示每次行程所获得的里程数加仑并打印出来 到目前为止所有行程所获得的每加仑英里数。所有平均计算都应该 产生浮点结果。使用classScannerand sentinel控制的重复来获取 来自用户的数据。

2 个答案:

答案 0 :(得分:0)

答案1:(紧凑型逻辑结构:无计算器。输入里程和加仑数,并按行程打印概述)。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(moreTrip(sc, "Would you like another calculation? (Y or N) ")) {
        int miles, gallons;
        while ((miles = getInt(sc, "Miles: ")) < 0) {
            System.out.println("Please enter a non-negative number");
        }
        while ((gallons = getInt(sc, "Gallons: ")) <= 0) {
            System.out.println("Please enter a positive number");
        }
        System.out.println((new Trip(miles, gallons)).getMPG());
    }
}

private static boolean moreTrip(Scanner sc, String message) {
    System.out.print(message);
    String response;
    if ((response = sc.nextLine()).isEmpty()) {
        response = sc.nextLine();
    }
    return ("y".compareToIgnoreCase(response) == 0)
            ? true
            : (("n".compareToIgnoreCase(response) == 0)
                ? false
                : moreTrip(sc, message));
}

private static int getInt(Scanner sc, String message) {
    System.out.print(message);
    return (sc.hasNextInt()) ? sc.nextInt() : getInt(sc, "Please enter a number");
}
public class Trip {
    private final int miles;
    private final int gallons;

    public Trip(int miles, int gallons) {
       this.miles = miles;
       this.gallons = gallons;
    }

    public double getMPG() {
        return (double)miles / gallons;
    }
}

P.S。情景尚不清楚。因此,如果您要向班级添加多个旅行统计信息并根据这些统计信息进行计算,最好制作Trip课程,而不是Gas,并在其中设置属性private final List<Trip> trips = new ArrayList<>();具有适当功能的TripCalculator类(参见答案2)。

答案 1 :(得分:0)

答案2:完整结构(使用TripCalculator收集多个旅程详细信息,以打印旅行收集的所有详细信息)

代表一次旅行所用英里和加仑的Trip课程:

public class Trip {
    private final int miles;
    private final int gallons;

    public Trip(int miles, int gallons) {
       this.miles = miles;
       this.gallons = gallons;
    }

    public double getMPG() {
        return (double)miles / gallons;
    }

    public int getMiles() {
        return miles;
    }

    public int getGallons() {
        return gallons;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        return sb.append("\nMiles: ").append(miles)
                .append("\nGallons: ").append(gallons)
                .append("\nMiles per Gallon: ").append(getMPG())
                .toString();
    }
}

GasCalculator课程,包含(多个)旅行和功能的集合,以获得所有旅行的总里程数,所有旅行使用的总加仑数和每加仑平均总里程数:

import java.util.ArrayList;
import java.util.List;

public class TripCalculator {
    private final List<Trip> trips = new ArrayList<>();

    public void add(Trip trip) {
        trips.add(trip);
    }

    public int getTotalMiles() {
        return trips.stream().mapToInt(trip -> trip.getMiles()).sum();
    }

    public int getTotalGallons() {
        return trips.stream().mapToInt(trip -> trip.getGallons()).sum();
    }

    public double getAverageMPG() {
        return (double)getTotalMiles() / getTotalGallons();
    }

    public void printTrips() {
        trips.stream().forEach(System.out::println);
    }

    public void printAll() {
        System.out.println("\nSTATISTICS");
        printTrips();
        System.out.println(this);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        return sb.append("\nTotal Miles: ").append(getTotalMiles())
                .append("\nTotal Gallons: ").append(getTotalGallons())
                .append("\nAverage Miles per Gallon: ").append(getAverageMPG())
                .toString();
    }
}

只是试驾:

import java.util.Scanner;

public class TestDrive {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        TripCalculator calc = new TripCalculator();

        while(moreTrip(sc, "Would you like another calculation? (Y or N) ")) {
            int miles, gallons;
            while ((miles = getInt(sc, "Miles: ")) < 0) {
                System.out.println("Please enter a non-negative number");
            }
            while ((gallons = getInt(sc, "Gallons: ")) <= 0) {
                System.out.println("Please enter a positive number");
            }
            calc.add(new Trip(miles, gallons));
        }

        calc.printAll();
    }

    private static boolean moreTrip(Scanner sc, String message) {
        System.out.print(message);
        String response;
        if ((response = sc.nextLine()).isEmpty()) {
            response = sc.nextLine();
        }
        return ("y".compareToIgnoreCase(response) == 0)
                ? true
                : (("n".compareToIgnoreCase(response) == 0)
                    ? false
                    : moreTrip(sc, message));
    }

    private static int getInt(Scanner sc, String message) {
        System.out.print(message);
        return (sc.hasNextInt()) ? sc.nextInt() : getInt(sc, "Please enter a number");
    }
}

然后您还可以为TripCalculator添加一些电动工具,例如:

public Trip toTrip() {
    return new Trip(getTotalMiles(), getTotalGallons());
}

public void reset() {
    trips.clear();
}

public Trip resetAndGet() {
    Trip trip = toTrip();
    reset();
    return trip;
}

public void resetAndContinue() {
    trips.add(resetAndGet());
}