所以我有我的if语句在.txt文件中搜索与用户键入的国家/地区对应的货币代码。我将这些国家/地区代码存储在名为'from'和'to'的字符串中。我需要访问存储在'from'和'to'变量中的if语句的结果,以便稍后插入。当我尝试在最后一行中使用这些时,它说无法找到符号'from'并且找不到符号'to'。我怎样才能解决这个问题?
//all my imports here
public class ExchangeApp {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("Exchange App");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 2, 5, 3));
//GUI Elements
JLabel toLabel = new JLabel("To");
JTextField CurrencyTo = new JTextField(20);
JLabel fromLabel = new JLabel("From");
JTextField CurrencyFrom = new JTextField(20);
JLabel amountLabel = new JLabel("Amount");
JTextField AmountText = new JTextField(20);
JLabel displayLabel = new JLabel();
JLabel updateLabel = new JLabel();
JButton Calculate = new JButton("Calculate");
JButton Clear = new JButton("Clear");
//Add elements to panel
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(fromLabel);
panel.add(CurrencyFrom);
panel.add(toLabel);
panel.add(CurrencyTo);
panel.add(amountLabel);
panel.add(AmountText);
panel.add(Calculate);
panel.add(Clear);
panel.add(displayLabel);
panel.add(updateLabel);
//make visible
frame.add(panel);
frame.setVisible(true);
class calculateListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==Calculate){
String line, from, to;
String fromString = CurrencyFrom.getText();
String toString = CurrencyTo.getText();
double amount = Double.parseDouble(AmountText.getText());
try{
//import text file
File inputFile = new File("currency.txt");
//create file scanner
Scanner input = new Scanner(inputFile);
try{
//skip first line
input.nextLine();
//while has next line
while(input.hasNextLine()){
//set line equal to entire line
line = input.nextLine();
String[] countryArray = line.split("\t");
//search for from
if(fromString.equals(countryArray[0])){
//set 'from' equal to that country code
from = countryArray[2];
//testing
System.out.println(from);
}
//search for to
if(toString.equals(countryArray[0])){
//set 'to' equal to that country code
to = countryArray[2];
System.out.println(to);
}
else{
displayLabel.setText("To country not found");
}
}//while loop
}//2nd try
finally{input.close();}
}//1st try
catch(IOException exception){
System.out.println(exception);
}//catch bracket
}//if bracket ****these 2 variables****
String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to;
}//action bracket
}//class implements action listener bracket
ActionListener listener = new calculateListener();
Calculate.addActionListener(listener);
}//main bracket
}//class bracket