Ask coding questions

← Back to all posts
Old Phone (Solved)
LordSpice (1)

Code is acting funny and I don't know the issue. My program is supposed to read a number of lines of text from a file, and then convert them into numbers that resemble the input a user would make on a Nokia 3310 model. I think I have written a competent code, but my issue is that my program skips the first line of text and converts the second line of text.
The very first line of the file is meant to indicate the number of lines that follow
Here is the link to my repl for anyone that wants to try their hands at it: https://repl.it/@LordSpice/Old-Phone?live=AEaR-7GUOXPuwg
I found a solution to my issue through some help from Archie, but I am leaving this up along with the code for anyone who would ever find it interesting to look at or use

Answered by ArchieMaclean (667) [earned 5 cycles]
View Answer
Commentshotnewtop
ArchieMaclean (667)

You are calling file.nextLine() twice in the same iteration of the for loop, once on line 21 (when declaring toConvert) and once on line 114 (when declaring waste).
This means that the file only converts every second line of text because only every second line will be declared toConvert and the encoding will follow.
To solve, get rid of lines 112-116.
Please upvote if you found this helpful :)

LordSpice (1)

@ArchieMaclean Right, what I am doing is I am making my program read a line first, convert that line and print the numbers, then get rid of excess white-space. I don't need to print either the waste or the converted text. I am just printing waste to see what was read as waste, I guess I should have clarified that with a comment.
To elaborate even further, the intended order of commands is this:
read int and define it as loop -> read nextLine() -> read all characters in that line using a loop -> printing numbers -> reading whitespace as a nextLine() to avoid issues -> repeating the loops as many times as necessary

LordSpice (1)

@ArchieMaclean I have tried the solution you have suggested, but that provided me with a different issue. Now, my program only prints the line that is before last and then stops. This is some very interesting behaviour to say the least

ArchieMaclean (667)

@LordSpice ok.
Every time you call nextLine() you are taking the entire next line, reading it, then moving past it. This means every second line will become "waste".
To remove whitespace, use toConvert = toConvert.replaceAll("\\s+","");

LordSpice (1)

@ArchieMaclean I am not supposed to remove spaces (my idea of white-space is vague, I know lol), but I have taken the luxury of checking out what you have written and realised my mistake I guess. I managed to make the program work, thanks for the help friend!

ArchieMaclean (667)

@LordSpice cool, I'm glad it works now. If you have any other problems, then don't hesitate to ask!

LordSpice (1)

Basically, it jumps a line of text and takes the second one for some reason