mrprogrammer231 mrprogrammer231 - 2 months ago 7
Java Question

ParseInt keeps getting a zero

I am reading a text file in from another program that is this(I really just am trying to save the first number of each line. I am simulating a memory and CPU interaction so these are codes in another class:

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


I am trying to just save it into the memory array, but while debugging it I see that the value stored is zero. I cant figure it out! I added the "[0]" because the compiler would throw this error without it

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


So, any help is much appreciated here is the block of code!

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));
}
}

Answer

You're incrementing init before you actually print the value. So your code is printing 0 because you haven't assigned anything to memory[init] yet.

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));
    }
}