当我输入itemtype时,如何使它打印出一个实际的类型而不仅仅是int

swvgeqrz  于 2021-07-09  发布在  Java
关注(0)|答案(5)|浏览(324)
package Homework;

import java.util.Scanner;

public class Homework2LibraryFines {

public static void main(String[] args) {
    // Variables
    int cardNumber;
    int age;
    int overdue;
    int itemType;
    double overdueFine;
    int fineAdjustment;
    int books = 1;
    int magazines = 2;
    int dvd = 3;

    Scanner input = new Scanner(System.in);

    System.out.println("Enter patron's library card number");
    cardNumber = input.nextInt();

    System.out.println("Enter patron's age");
    age = input.nextInt();

    System.out.println("Enter item type 1.Book, 2.Magazine, 3.DVD");
    itemType = input.nextInt();

    System.out.println("Enter number of days overdue");
    overdue = input.nextInt();

    System.out.println("Enter overdue fine");
    overdueFine = input.nextDouble();

    System.out.println("Enter fine adjustment");
    fineAdjustment = input.nextInt();
    if (overdueFine == books) {
        overdueFine += 0.50;
    } else if (overdueFine == magazines) {
        overdueFine += 0.25;
    } else if (overdueFine == dvd) {
        overdueFine += 1.50;
    } else if (age > 70) {
        overdueFine += 0;
    } else if (age >= 6 && age <= 17) {
        overdueFine += 1.00;
    }

    System.out.println(cardNumber + " is " + age + " years old " + "and has an overdue " + itemType + "." + "The "
            + itemType + " is " + overdue + " days overdue");

}

}

输出

输入用户的图书卡号
222222
输入用户年龄
30
输入项目类型1.书本、2.杂志、3.dvd

输入逾期天数
10
输入滞纳金
2
输入微调

22222已满30岁,逾期3天,逾期10天

3zwjbxry

3zwjbxry1#

除了 if 以及 switch 已建议的解决方案,您可以创建 enum . 这是一类特殊的有限值类。您可以覆盖 toString() 方法打印出你想要的任何东西。

hgb9j2n6

hgb9j2n62#

一种选择是 switch 声明。
这个 itemType 变量存储选项,第二个变量存储 string ```
String itemT = "";
switch(itemType)
{
case 1:
itemT = "book"
break;
case2:
...
}

4c8rllxm

4c8rllxm3#

可以声明itemtypes的和数组,并且在打印时,将用户输入用作数组中的偏移量。
用于存储,

String itemTypesArr[] = {"", "Book", "Magazine", "DVD"};

现在, itemTypesArr[1]"Book" 其他人也是如此。
用于打印,

System.out.println(cardNumber + " is " + age + " years old " + "and has an overdue " + itemTypesArr[itemType] + "." + "The " + itemTypesArr[itemType] + " is " + overdue + " days overdue");
o7jaxewo

o7jaxewo4#

不是很漂亮但是很管用:

string itemName = "";

if (itemType == 1) itemName = "Book";
else if (itemType == 2) itemName = "Magazine";
else if (itemType == 3) itemName = "DVD";

当打印出来时,用itemname替换itemtype。

hwazgwia

hwazgwia5#

你可以加一个 switch 声明以获取实际 String 值取决于输入的数字

String item="Book";//making Book the default option
        switch (itemType) {
            case 1:
                item = "Book";
                break;
            case 2:
                item = "Magazine";
                break;
            case 3:
                item = "DVD";
                break;
        }

和打印 itemprint 声明。
甚至有点难看 ternary 条件

String item = itemType == 1 ? "Book" : itemType == 2 ? "Magazine" : itemType == 3 ? "DVD" : "Book";

相关问题