【问题标题】:Printing two Strings simultaneously in loop but on separate "paragraphs"在循环中同时打印两个字符串,但在单独的“段落”上
【发布时间】:2019-01-08 15:26:30
【问题描述】:

头等舱:

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())) ;
    }
}

主类:

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
        }

    }

}

请记住,只有 Main 类是我们可以对其进行更改的类。 在 Main 类中,我注意到的部分

// 打印直到上面完成 它打印以下内容:

       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

是否可以让它打印在不同的“段落”上?例如,像这样:

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

我尝试为第二部分创建一个不同的循环,但我遇到了尝试访问宠物的问题。唯一可以访问的是最后一个使用的。有什么想法吗?

更新:主要问题已解决,但我还有一个小问题。当我运行程序时,我得到了这个:

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

为什么其余宠物不与名称对齐?

【问题讨论】:

  • 你的equals错误,你应该重写equals(Object o)。你是什​​么意思:在不同的段落上打印?这是命令提示符打印,而不是 word 文档
  • 这不是你的做法。你应该首先收集输入的宠物(到Collection),然后循环打印出来。
  • @Stultuske 这就是为什么我在印刷品上加上引号。我举了一个例子来说明我的意思。
  • @daniu 收藏?怎么样?
  • 当然可以,也很简单。大牛的回复应该能帮到你,大概是不给你写代码我们能得到的最准确的。只是一个提示:一个集合可以迭代不止一次

标签: java fileinputstream jcreator


【解决方案1】:

单独存储每只宠物的简单方法是创建一个ArrayList,就像一个集合,您可以在其中存储每只宠物,并且您可以随时访问它们的信息以了解其上的索引。

在代码中,我们在循环外声明变量,以便我们可以在孔类中访问这些变量,然后我们初始化对象并创建 ArrayList(记得在 Pets 类中创建一个空的构造函数。

当您有循环读取文件时,您将每个宠物添加到 ArrayList 中:

pets.add(new Pets(name,age,weight));

因此,在读取循环之外,我们创建了另一个循环来访问 ArrayList 的每个索引,如果您只想要 1 个宠物,您可以创建一个循环来找到一个确切的名称或类似的东西,这比仅打印和永远不要存放宠物。所以基本上你可以通过pets.get(x) 访问宠物,其中 x 是宠物的索引。

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
        }
    }

}

希望它对您有所帮助,如果您有任何问题,请添加评论:)

在这里您可以轻松找到有关在 Arraylist 上存储对象的信息并打印出来:

How to add an object to an ArrayList in Java

How to get data from a specific ArrayList row using with a loop?

【讨论】:

  • 当您创建 ArrayList 时,它说找不到符号。这是为什么呢?
  • 已解决。我忘了导入 ArrayList。谢谢!
  • 我已经更新了我最初的帖子,希望你能帮助我解决这个小问题。
  • 只能是两件事:你存储数据的方式,检查宠物文件的阅读器,或者可能是你打印的方式,但我没有看到任何奇怪的东西,所以可能是阅读器。 @TomásPalamás
【解决方案2】:

只需更改System.out.printf("%-15s %15d %18s %n", name, age, weight) ; 进入

List<Pet> pets = new ArrayList<>();
pets.add(new Pet(name, age, weight));

然后您可以使用每个循环打印集合。

【讨论】:

  • 它说找不到符号。
【解决方案3】:

你这样做:

// allows you to store the pets that were entered
Collection<Pets> petsCollection = new ArrayList<>();

// loop and have the user enter pets
for (int i = 0; i < petCount; i++) {
    // your code
    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); 
    // add to collection
    petsCollection.add(pets);
}

现在你的所有宠物都在集合中,你可以迭代它来做各种事情,比如打印:

petsCollection.forEach(pet -> {
    System.out.printf("Pet: %s age: %d weight: %d%n", pet.getName(), pet.getAge(), pet.getWeight());
});

或得到最小的宠物

int minAge = Integer.MAX_VALUE;
for (Pets pet : petsCollection) {
    minAge = Math.min(minAge, pet.getAge());
}
System.out.printf("The youngest pet is %d%n", minAge);

有更优雅的方法(使用 Streams),但我认为最好是这样开始。

【讨论】:

    【解决方案4】:

    你在同一个循环中打印两行,所以它们总是在同一个段落中。

    System.out.printf("%-15s %15d %18s %n", name, age, weight) ; 
    System.out.println(pets.toString()) ; // Print until above is done
    

    执行此操作的最简单方法是将宠物存储在一个数组中,然后在完成另一个循环时对其进行迭代。

    类似这样的:

    List<Pets> petList = new ArrayList<Pets>();
    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) ; 
        petList.add(pets);
    }
    
    for(Pets pet : petList{
        System.out.println(pets.toString()) ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 2020-09-14
      • 1970-01-01
      • 2016-10-17
      • 2020-03-30
      相关资源
      最近更新 更多