gpt4 book ai didi

java - 尝试并发现问题

转载 作者:行者123 更新时间:2023-11-30 03:32:38 24 4
gpt4 key购买 nike

我试图在这个例子中编写一个“try and catch”方法,但由于某种原因,我在所有变量上都出错了: “找不到标志”。在以下所有情况下都会发生这种情况:小计&客户类型。有谁知道这是什么原因造成的?

import java.text.NumberFormat;
import java.util.Scanner;
import java.util.*;

public class InvoiceApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";

while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
try
{
//System.out.print("Enter customer type (r/c): ");
String customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}

// get the discount percent
double discountPercent = 0;
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}

// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;

// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");

// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}

最佳答案

代码的问题在于变量的范围:如果您在 try block 中声明某些内容,则它仅在该 try block 中可见;它在 try block 之外是不可见的,甚至包括它后面的 catch block 。

为了解决此问题,请在 try block 之外声明变量:

String customerType;
double subtotal;
try {
//System.out.print("Enter customer type (r/c): ");
customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
} catch (InputMismatchException e) {
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}

关于java - 尝试并发现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com