ParseInt持续为零

时间:2016-10-01 17:19:19

标签: java

我正在从另一个程序中读取文本文件(我真的只是想保存每行的第一个数字。我正在模拟内存和CPU交互,所以这些是另一个类中的代码:

1    // Load 0
0
14   // CopyToX
4    // LoadIdxX 32 (load from A-Z table) 
32
21   // JumpIfEqual 12 
12
9    // Put 2 (output as char)
2
25   // IncX
20   // Jump 3
3
1    // Load 0
0
16   // CopyToY
5    // LoadIdxY 59 (load from 1-10 table)
59
21   // JumpIfEqual 27
27
9    // Put 1 (output as int)
1
1    // Load 1  (because no IncY instruction)
1
11   // AddY
16   // CopyToY
20   // Jump 15
15
1    // Print newline
10
9
2
50   // End
65   // Data A-Z
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
0
1    // Data 1-10
2
3
4
5
6
7
8
9
10
0

.1000
30

我试图将它保存到内存数组中,但在调试时我发现存储的值为零。我弄清楚了!我添加了“[0]”,因为编译器会在没有它的情况下抛出此错误

The method parseInt(String) in the type Integer is not applicable for the arguments (String[])

所以,任何帮助都非常感谢这里的代码块!

String line;
int init=0;
while((line= Fileread.readLine())!=null)
    {
System.out.println(line.length());
    if(line.length()==0)
        break;
    try
    {
        memory[init++]=Integer.parseInt(line.trim().split(" ")[0]);
        System.out.println(memory[init]);
    }
    catch(NumberFormatException e)
    {
        init=Integer.parseInt(line.substring(1));
    }
}

2 个答案:

答案 0 :(得分:1)

在实际打印值之前,您需要递增init。 因此,您的代码正在打印0,因为您还没有为memory[init]分配任何内容。

String line;
int init=0;
while((line= Fileread.readLine())!=null)
    {
System.out.println(line.length());
    if(line.length()==0)
        break;
    try
    {
        memory[init]=Integer.parseInt(line.trim().split(" ")[0]);
        System.out.println(memory[init]);
        init++;
    }
    catch(NumberFormatException e)
    {
        init=Integer.parseInt(line.substring(1));
    }
}

答案 1 :(得分:0)

您的代码可能是这样的:

String line;
int init=0;
while((line= Fileread.readLine())!=null)
    {
System.out.println(line.length());
    if(line.length()==0)
        break;
    String num= str.replaceAll("\\D+","");

    try
    {
       if(num.length() == 0){
        memory[init++]=Integer.parseInt(num);
        System.out.println(memory[init]);
       }
    }
    catch(NumberFormatException e)
    {
        init=Integer.parseInt(line.substring(1));
    }
}