要求单价输出为整数,代码应该怎么改
时间: 2024-02-25 08:55:44 浏览: 93
Python中变量的输入输出实例代码详解
好的,如果要求单价输出为整数,可以将`Book`类中的价格属性`price`改为整型`int`类型,然后将读入价格的代码修改为读入整数。同时,在输出单价时,使用`System.out.printf()`方法,指定输出格式为整数即可。下面是修改后的代码:
```java
import java.util.*;
class Book {
private String type;
private String name;
private int price;
private String uniqueProperty;
public Book(String type, String name, int price, String uniqueProperty) {
this.type = type;
this.name = name;
this.price = price;
this.uniqueProperty = uniqueProperty;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public String getUniqueProperty() {
return uniqueProperty;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Book> books = new ArrayList<>();
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
String type = scanner.next();
String name = scanner.next();
int price = scanner.nextInt();
String uniqueProperty = scanner.next();
books.add(new Book(type, name, price, uniqueProperty));
}
String queryType = scanner.next();
boolean found = false;
for (Book book : books) {
if (book.getType().equals(queryType)) {
System.out.printf("书名: %s, 单价: %d, 独有属性: %s\n", book.getName(), book.getPrice(), book.getUniqueProperty());
found = true;
}
}
if (!found) {
System.out.println("Don't have this kind of book");
}
}
}
```
这里使用了`System.out.printf()`方法,格式化输出书名、单价和独有属性。`%s`表示输出字符串,`%d`表示输出整数。在输出单价时,使用`%d`格式化输出。
阅读全文