java - 我在 Java 中遇到错误:无法解析为变量
问题描述
我正在运行此代码并收到错误
System.out.print(name[i]+" ");
System.out.print(age[i]+" ");
System.out.print(country[i]+" ");
那
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
name cannot be resolved to a variable
age cannot be resolved to a variable
country cannot be resolved to a variable
我该如何解决这个问题?
public class AnyInteger
{
public static void main(String arg[]) throws FileNotFoundException
{
int n = 0;
try {
BufferedReader in = new BufferedReader(new FileReader("D:\\Java\\eclipse-workspace\\AnyInteger\\src\\file.txt"));
String str;
while ((str = in.readLine())!= null) {
String[] arr =str.split("#");
n = arr.length;
String name[] = new String[n];
int age[] = new int[n];
String country[] = new String[n];
int i=0;
while(i<n)
{
for(int j=0;j<3;j++)
{
name[j] = arr[i];
i = i+1;
age[j] = Integer.parseInt(arr[i]);
i = i+1;
country[j] = arr[i];
i = i+1;
}
}
}
in.close();
}
catch (IOException e) {
System.out.println("File Read Error");
}
System.out.println("Names: ");
for(int i=0;i<n;i++)
{
System.out.print(name[i]+" ");
}
System.out.println("Ages: ");
for(int i=0;i<n;i++)
{
System.out.print(age[i]+" ");
}
System.out.println("Countries: ");
for(int i=0;i<n;i++)
{
System.out.print(country[i]+" ");
}
}
}
解决方案
您应该声明数组name[]
,age[]
并country[]
在 try/catch 语句之外声明,while
如果需要,只需在循环中实例化它。
像这样的东西:
public class AnyInteger
{
public static void main(String arg[]) throws FileNotFoundException
{
int n = 0;
String name[];
int age[];
String country[];
try {
BufferedReader in = new BufferedReader(new FileReader("D:\\Java\\eclipse-workspace\\AnyInteger\\src\\file.txt"));
String str;
while ((str = in.readLine())!= null) {
String[] arr =str.split("#");
n = arr.length;
name = new String[n];
age = new int[n];
country = new String[n];
int i=0;
while(i<n)
{
for(int j=0;j<3;j++)
{
name[j] = arr[i];
i = i+1;
age[j] = Integer.parseInt(arr[i]);
i = i+1;
country[j] = arr[i];
i = i+1;
}
}
}
in.close();
}
catch (IOException e) {
System.out.println("File Read Error");
}
System.out.println("Names: ");
for(int i=0;i<n;i++)
{
System.out.print(name[i]+" ");
}
System.out.println("Ages: ");
for(int i=0;i<n;i++)
{
System.out.print(age[i]+" ");
}
System.out.println("Countries: ");
for(int i=0;i<n;i++)
{
System.out.print(country[i]+" ");
}
}
}
推荐阅读
- vue.js - 如何将组件的逻辑放在文件 .vue 本身之外
- javascript - 用户输入正确的用户名和密码后,如何使提交按钮重定向到另一个页面?
- node.js - 错误:运行 firebase init 时找不到模块“fast-safe-stringify”
- c - 将二叉树转换为简单链表
- node.js - 自托管 APIM 开发人员门户:无法使用“npm run publish”在本地发布
- c# - Nopcommerce 4.2 - 如何获取 _ProductBox 部分视图的类别
- deep-learning - 目标尺寸 (torch.Size([12])) 必须与输入尺寸 (torch.Size([12, 1000])) 相同
- excel - 比较行和限制重复
- reactjs - 在 HOC 中使用带有传递参数的反应钩子
- javascript - 材料 UI 搜索框混合 w 自动完成和反应