Erste Klasse:
public class Pets
{
// Instance variables
private String name;
private int age; //in years
private double weight; //in pounds
// Default values for instance variables
private static final String DEFAULT_NAME = "No name yet." ;
private static final int DEFAULT_AGE = -1 ;
private static final double DEFAULT_WEIGHT = -1.0 ;
/***************************************************
* Constructors to create objects of type Pet
***************************************************/
// no-argument constructor
public Pets()
{
this(DEFAULT_NAME, DEFAULT_AGE, DEFAULT_WEIGHT) ;
}
// only name provided
public Pets(String initialName)
{
this(initialName, DEFAULT_AGE, DEFAULT_WEIGHT) ;
}
// only age provided
public Pets(int initialAge)
{
this(DEFAULT_NAME, initialAge, DEFAULT_WEIGHT) ;
}
// only weight provided
public Pets(double initialWeight)
{
this(DEFAULT_NAME, DEFAULT_AGE, initialWeight) ;
}
// full constructor (all three instance variables provided)
public Pets(String initialName, int initialAge, double initialWeight)
{
setName(initialName) ;
setAge(initialAge) ;
setWeight(initialWeight) ;
}
/****************************************************************
* Mutators and setters to update the Pet. Setters for age and
* weight validate reasonable weights are specified
****************************************************************/
// Mutator that sets all instance variables
public void set(String newName, int newAge, double newWeight)
{
setName(newName) ;
setAge(newAge) ;
setWeight(newWeight) ;
}
// Setters for each instance variable (validate age and weight)
public void setName(String newName)
{
name = newName;
}
public void setAge(int newAge)
{
if ((newAge < 0) && (newAge != DEFAULT_AGE))
{
System.out.println("Error: Invalid age.");
System.exit(99);
}
age = newAge;
}
public void setWeight(double newWeight)
{
if ((newWeight < 0.0) && (newWeight != DEFAULT_WEIGHT))
{
System.out.println("Error: Invalid weight.");
System.exit(98);
}
weight = newWeight;
}
/************************************
* getters for name, age, and weight
************************************/
public String getName( )
{
return name ;
}
public int getAge( )
{
return age ;
}
public double getWeight( )
{
return weight ;
}
/****************************************************
* toString() shows the pet's name, age, and weight
* equals() compares all three instance variables
****************************************************/
public String toString( )
{
return ("Name: " + name + " Age: " + age + " years"
+ " Weight: " + weight + " pounds");
}
public boolean equals(Pets anotherPet)
{
if (anotherPet == null)
{
return false ;
}
return ((this.getName().equals(anotherPet.getName())) &&
(this.getAge() == anotherPet.getAge()) &&
(this.getWeight() == anotherPet.getWeight())) ;
}
}
Hauptklasse:
import java.util.Scanner ;
import java.io.FileInputStream ;
import java.io.FileNotFoundException ;
import java.io.IOException ;
public class PetsMain
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in) ;
System.out.println("Please enter the number of pets") ;
int numberOfPets = keyboard.nextInt() ;
String fileName = "pets.txt" ;
FileInputStream fileStream = null ;
String workingDirectory = System.getProperty("user.dir") ;
System.out.println("Working Directory for this program: " + workingDirectory) ;
try
{
String absolutePath = workingDirectory + "\\" + fileName ;
System.out.println("Trying to open: " + absolutePath) ;
fileStream = new FileInputStream(absolutePath) ;
System.out.println("Opened the file ok.\n") ;
}
catch (FileNotFoundException e)
{
System.out.println("File \'" + fileName + "\' is missing") ;
System.out.println("Exiting program. ") ;
System.exit(0) ;
}
Scanner fileScanner = new Scanner(fileStream) ;
int sumAge = 0 ;
double sumWeight = 0 ;
String petName = "Pet Name" ;
String dogAge = "Age" ;
String dogWeight = "Weight" ;
String line = "--------------" ;
System.out.printf("%11s %15s %19s %n", petName, dogAge, dogWeight) ;
System.out.printf("%s %17s %17s %n", line, line, line) ;
for (int counter = 0; counter < numberOfPets; counter++)
{
fileScanner.useDelimiter(",") ;
String name = fileScanner.next() ;
fileScanner.useDelimiter(",") ;
int age = fileScanner.nextInt() ;
fileScanner.useDelimiter("[,\\s]") ;
double weight = fileScanner.nextDouble() ;
Pets pets = new Pets(name, age, weight) ;
sumAge += age ;
sumWeight += weight ;
System.out.printf("%-15s %15d %18s %n", name, age, weight) ;
System.out.println(pets.toString()) ; // Print until above is done
}
/*How do I make this?
Smallest pet: Name: Tweety Age: 2 years Weight: 0.1 pounds
Largest pet: Name: Dumbo Age: 6 years Weight: 2000.0 pounds
Youngest pet: Name: Fido Age: 1 years Weight: 15.0 pounds
Oldest pet: Name: Sylvester Age: 10 years Weight: 8.3 pounds
*/
System.out.println("\nThe total weight is " + sumWeight) ;
System.out.println("\nThe total age is " + sumAge) ;
try
{
fileStream.close() ;
}
catch (IOException e)
{
// don't do anything
}
}
}
Denken Sie daran, dass nur die Hauptklasse geändert werden kann. In der Hauptklasse der Teil, in dem ich notiert habe
// Drucken, bis oben fertig ist, wird Folgendes gedruckt:
Pet Name Age Weight
-------------- -------------- --------------
Fido 1 15.0
Name: Fido Age: 1 years Weight: 15.0 pounds
Tweety 2 0.1
Name:
Tweety Age: 2 years Weight: 0.1 pounds
Sylvester 10 8.3
Name:
Sylvester Age: 10 years Weight: 8.3 pounds
Fido 1 15.0
Name:
Fido Age: 1 years Weight: 15.0 pounds
Dumbo 6 2000.0
Name:
Dumbo Age: 6 years Weight: 2000.0 pounds
Ist es möglich, es auf einem anderen "Absatz" drucken zu lassen? Zum Beispiel so:
Pet Name Age Weight
-------------- -------------- --------------
Fido 1 15.0
Tweety 2 0.1
Sylvester 10 8.3
Fido 1 15.0
Dumbo 6 2000.0
Name: Fido Age: 1 years Weight: 15.0 pounds
Name: Tweety Age: 2 years Weight: 0.1 pounds
Name: Sylvester Age: 10 years Weight: 8.3 pounds
Name: Fido Age: 1 years Weight: 15.0 pounds
Name: Dumbo Age: 6 years Weight: 2000.0 pounds
Ich habe versucht, eine andere Schleife für den zweiten Teil zu erstellen, aber ich bin auf das Problem gestoßen, auf die Haustiere zuzugreifen. Der einzige, auf den zugegriffen werden konnte, war der zuletzt verwendete. Irgendwelche Gedanken?
UPDATE: Das Hauptproblem ist gelöst, aber ich habe noch ein kleines Problem. Wenn ich das Programm starte, bekomme ich Folgendes:
Name: Fido Age: 1 years Weight: 15.0 pounds
Name:
Tweety Age: 2 years Weight: 0.1 pounds
Name:
Sylvester Age: 10 years Weight: 8.3 pounds
Name:
Fido Age: 1 years Weight: 15.0 pounds
Name:
Dumbo Age: 6 years Weight: 2000.0 pounds
Warum sind die restlichen Haustiere nicht auf den Namen ausgerichtet?
Die einfache Möglichkeit, jedes Haustier einzeln zu speichern, besteht darin, ArrayList
eine Sammlung zu erstellen, in der Sie jedes Haustier speichern und jederzeit auf dessen Informationen zugreifen können, um den Index zu kennen.
Wie im Code deklarieren wir die Variablen aus der Schleife, damit wir auf diese Variablen in der Hole-Klasse zugreifen können. Dann initialisieren wir das Objekt und erstellen die ArrayList (denken Sie daran, einen leeren Konstruktor in der Pets-Klasse zu erstellen.
Wenn Sie die Schleife zum Lesen der Datei haben, fügen Sie jedes Haustier der ArrayList hinzu mit:
pets.add(new Pets(name,age,weight));
Aus der Leseschleife erstellen wir eine andere Schleife, um auf jeden Index der ArrayList zuzugreifen. Wenn Sie nur 1 Haustier möchten, können Sie eine Schleife erstellen, um einen genauen Namen zu finden, oder solche Dinge sind nützlicher als nur zu drucken und niemals zu speichern Haustiere. Grundsätzlich können Sie also auf das Haustier zugreifen, pets.get(x)
wobei x der Index des Haustieres ist.
public class PetsMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// We declare variables here
String name;
int age;
double weight;
Pets pet = new Pets(); // Initialize Object
ArrayList<Pets> pets = new ArrayList<Pets>(); // We create the ArrayList
Scanner keyboard = new Scanner(System.in) ;
System.out.println("Please enter the number of pets") ;
int numberOfPets = keyboard.nextInt() ;
String fileName = "pets.txt" ;
FileInputStream fileStream = null ;
String workingDirectory = System.getProperty("user.dir") ;
System.out.println("Working Directory for this program: " + workingDirectory) ;
try
{
String absolutePath = workingDirectory + "\\" + fileName ;
System.out.println("Trying to open: " + absolutePath) ;
fileStream = new FileInputStream(absolutePath) ;
System.out.println("Opened the file ok.\n") ;
}
catch (FileNotFoundException e)
{
System.out.println("File \'" + fileName + "\' is missing") ;
System.out.println("Exiting program. ") ;
System.exit(0) ;
}
Scanner fileScanner = new Scanner(fileStream) ;
int sumAge = 0 ;
double sumWeight = 0 ;
String petName = "Pet Name" ;
String dogAge = "Age" ;
String dogWeight = "Weight" ;
String line = "--------------" ;
System.out.printf("%11s %15s %19s %n", petName, dogAge, dogWeight) ;
System.out.printf("%s %17s %17s %n", line, line, line) ;
for (int counter = 0; counter < numberOfPets; counter++)
{
fileScanner.useDelimiter(",") ;
name = fileScanner.next() ;
fileScanner.useDelimiter(",") ;
age = fileScanner.nextInt() ;
fileScanner.useDelimiter("[,\\s]") ;
weight = fileScanner.nextDouble() ;
sumAge += age ;
sumWeight += weight ;
System.out.printf("%-15s %15d %18s %n", name, age, weight) ;
// **We add the pet to the collection
pets.add(new Pets(name,age,weight)); // Adding it to the ArrayList
}
// Then we acces to the ArrayList and we print what we want.
for(int x=0; x < pets.size(); x++){
System.out.print(pets.get(x).toString());
}
System.out.println("\nThe total weight is " + sumWeight) ;
System.out.println("\nThe total age is " + sumAge) ;
try
{
fileStream.close() ;
}
catch (IOException e)
{
// don't do anything
}
}
}
Hoffe es hat dir geholfen und wenn du Fragen hast füge einen Kommentar hinzu :)
Hier finden Sie einfach Informationen zum Speichern von Objekten auf Arraylist und können diese ausdrucken:
So fügen Sie einer ArrayList in Java ein Objekt hinzu
Wie kann ich mit einer Schleife Daten aus einer bestimmten ArrayList-Zeile abrufen?
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen