字符串输出错误

时间:2017-08-25 12:50:03

标签: java

这是我的程序,我想要实现的是在位置1的字符串amount1中取char值,例如amount1 = $ 3.00 amount2 = 2。但它没有打印出我的预期,2。

System.out.print("$"+cost[0]+".00 remains to be paid. Enter coin or note: ");
String amount1 = keyboard.nextLine();
char amount2 = amount1.charAt(1);
String amountcheck = "$"+cost[0]+".00";
int [] remainder = new int[1];
    if (amount1.equals(amountcheck)) {
        System.out.println("Perfect! No change given."); }
    if (amount2 < cost[0]) {
        remainder[0] = cost[0] - amount2; }

System.out.println("Remainder = "+remainder[0]);
System.out.println(+amount2);

例如,

$3.00 remains to be paid. Enter coin or note: $2.00
Remainder = 0
50

问题出现在第2行和第3行。首先是3,它不明白为什么它在amount1 index 1处输出50作为char。如果我没有错,那么char位置的工作类似于数组索引系统。其次是第3行,我的原始代码的第8行和第9行中的if语句似乎没有捕获该数量2&lt; cost [0]并且不执行以下操作。

因此,当我在“$ 2.00”的第1位获取char时,我期望发生的是newamount将等于2而不是程序输出的50。

我已经尝试过更改字符位置,但所有这些似乎都会减少值。

2 个答案:

答案 0 :(得分:0)

您将amount2设置为char,当您将其打印时,它会转换为字符'2'50的字符的ASCII编号。 如果要输出2,则应将amount2更改为int,并将字符解析为整数,如第3行中的Integer.parseInt(""+amount1.charAt(1));

答案 1 :(得分:0)

您使用char存储数值,但该值是字符,而不是数字。这意味着您正在'2'中存储50 48。您应该删除'0'的值以获取正确的值(Integer.parseInt(String))或直接使用"$#.00"将字符串解析为数字。

但正如我在评论中所说,这很容易纠正,因此我不会为此提供更多代码。

但是,让我们诚实,你的逻辑从一开始就有风险。

您要求用户输入特定格式的金额:$##.00。如果该数字是两位数$则失败,如果他添加空格或未放置Scanner或用户专业的任何错误,则会失败。

首先,你应该简化这个,你需要$?如果要指定美元货币,请询问美元货币。 那么,你需要小数?我们首先假设您没有(请参阅注意获取小数提示)。

您只需要通过Integer输入一个整数值,它提供获取Scanner.nextInt()的方法 - &gt; int ammountReceived = keyboard.nextInt();

int remainder = amountToPay - amountReceived;
if(remainder == 0){
    //equals
} else if(remainder > 0){
    //not enough
} else {
    //too much
}

然后你需要看看是否

  1. 等于
  2. 太多
  3. 不够
  4. 像这样:

    Scanner sc = new Scanner(System.in);
    System.out.print("Amount to pay : $");
    int amountToPay = sc.nextInt();
    
    System.out.print("Amount received : $");
    int amountReceived = sc.nextInt();
    int remainder = amountToPay - amountReceived;
    if (remainder == 0) {
        System.out.println("That perfect, thanks.");
    } else if (remainder > 0) {
        System.out.println("Remaining : $" + remainder);
    } else {
        System.out.println("Need to give back : $" + -remainder);
    }
    sc.close();
    

    这将提供更简单的解决方案:

    char

    你和我很接近,但是你会发现这个问题更具可读性并且专注于问题,我不会使用String来获取特定的Scanner.nextInt模式,我专注于问题 - &gt;得到报酬;)

    现在,你必须在这里添加一个循环再次询问,直到收到正确的金额。但请不要按字符读取数字字符串字符...

    注意:

      如果格式不正确(不是整数),
    1. double会抛出异常
    2. 您可以轻松对其进行调整以获得floatBigDecimal或更好{{1}}