Java 在循环中同时打印两个字符串,但在单独的;段落;
头等舱:Java 在循环中同时打印两个字符串,但在单独的;段落;,java,fileinputstream,jcreator,Java,Fileinputstream,Jcreator,头等舱: 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
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())) ;
}
}
是否可以将其打印在不同的“段落”上?例如,像这样:
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
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()) ;
}
// 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);
}
我试图为第二部分创建一个不同的循环,但我遇到了试图访问宠物的问题。唯一可以访问的是最后使用的一个。有什么想法吗
更新:主要问题已经解决,但我还有一个次要问题。当我运行程序时,我得到以下信息:
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
为什么其余的宠物不与名字对齐?您在同一个循环中打印两行,因此它们总是在同一段落中
System.out.printf("%-15s %15d %18s %n", name, age, weight) ;
System.out.println(pets.toString()) ; // Print until above is done
最简单的方法是将宠物存储在一个数组中,然后在完成另一个循环时对其进行迭代
大概是这样的:
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
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()) ;
}
// 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);
}
List-petList=new-ArrayList();
对于(int counter=0;counter
只需更改System.out.printf(“%-15s%15d%18s%n”、姓名、年龄、体重);
进入
List pets=new ArrayList();
宠物。添加(新宠物(姓名、年龄、体重));
然后,您可以使用for each循环打印集合。您可以执行以下操作:
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
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()) ;
}
// 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);
}
或者养最小的宠物
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);
有更优雅的方法可以做到这一点(使用流),但我认为最好是这样开始。单独存储每只宠物的简单方法是创建一个
ArrayList
就像一个集合,在其中存储每只宠物,并且您可以随时访问它们的信息,知道其中的索引
正如在代码中一样,我们在循环外声明变量,以便在hole类中访问这些变量,然后初始化对象并创建ArrayList(记住在Pets类中创建一个空构造函数)
当您具有读取文件的循环时,您可以使用以下命令将每个宠物添加到ArrayList中:
宠物。添加(新宠物(姓名、年龄、体重));
因此,在读取循环之外,我们创建了另一个循环来访问ArrayList的每个索引,如果你只想要一只宠物,你可以创建一个循环来找到一个确切的名字或类似的东西,这比只打印和从不存储宠物更有用。因此,基本上你可以使用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
}
}
}
公共类PetsMain{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
//我们在这里声明变量
字符串名;
智力年龄;
双倍重量;
宠物宠物=新宠物();//初始化对象
ArrayList pets=new ArrayList();//我们创建ArrayList
扫描仪键盘=新扫描仪(System.in);
System.out.println(“请输入宠物数量”);
int numberOfPets=keyboard.nextInt();
字符串fileName=“pets.txt”;
FileInputStream fileStream=null;
字符串workingDirectory=System.getProperty(“user.dir”);
System.out.println(“此程序的工作目录:“+workingDirectory”);
尝试
{
字符串absolutePath=workingDirectory+“\\”+文件名;
System.out.println(“试图打开:“+absolutePath”);
fileStream=新文件输入流(绝对路径);
System.out.println(“打开文件确定。\n”);
}
catch(filenotfounde异常)
{
System.out.println(“缺少文件\'”+文件名+“\”);
System.out.println(“退出程序”);
系统出口(0);
}
Scanner fileScanner=新扫描仪(fileStream);
int sumAge=0;
双倍重量=0;
字符串petName=“Pet Name”;
字符串dogAge=“Age”;
字符串dogWeight=“Weight”;
字符串行=“--------------”;
System.out.printf(“%11s%15s%19s%n”,宠物名,狗龄,狗重);
System.out.printf(“%s%17s%17s%n”,行,行,行);
对于(int counter=0;counter
希望它对您有所帮助,如果您有任何问题,请添加评论:)
在这里,您可以轻松找到有关在Arraylist上存储对象的信息并进行打印:
你的等号是错误的,你应该覆盖等号(对象o)。什么意思:打印不同的段落?这是命令提示打印,不是文字文档。你应该首先收集输入的宠物(进入
集合
),然后循环打印出来。@Stultuske这就是为什么