If Statements and Code Refactoring | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

If Statements and Code Refactoring

if (i >= ring.length()) i = i - ring.length(); if (i < 0) i = ring.length() + i; The above are from lines 94 - 97 of my code. Is it possible to refactor to eliminate these if statements or this the simplest way to make these decisions already? Thoughts? https://code.sololearn.com/c6fBC0Ak72t6/?ref=app

8th May 2017, 7:53 PM
Steven Schneider
Steven Schneider - avatar
8 Answers
+ 8
how about this? get rid of both ifs change the command before to i = (ring.indexOf(decodeMe.charAt(j)) - temp)%ring.length(); [edit] no good xD index out of range [edit2] leaving the 2nd if worked i = (ring.indexOf(decodeMe.charAt(j)) - temp)%ring.length(); if (i < 0) i = ring.length() + i;
8th May 2017, 8:33 PM
Burey
Burey - avatar
+ 6
i = (i >= ring.length())? i-ring.length():i+ring.length());
8th May 2017, 8:11 PM
Burey
Burey - avatar
+ 3
@Jeth I don't hate if statements, I'm just wondering if there were possibilities I could have explored that would minimize, if not eliminate, my use of if's. Yeah, I'm aware of the newline character. I just hadn't learned how to use it by the time I first got my code working. Knowing how to use the newline character in Java is one reason, of many, that I'm now considering refactoring my code.
8th May 2017, 8:45 PM
Steven Schneider
Steven Schneider - avatar
+ 3
@Burey Thanks, I'll have to try that. It does appear to reduce the complexity of my code a bit.
8th May 2017, 8:46 PM
Steven Schneider
Steven Schneider - avatar
+ 2
Lol. Thanks, but aren't terniary operators an obfuscated if-then? :)
8th May 2017, 8:19 PM
Steven Schneider
Steven Schneider - avatar
+ 2
By the way you can refactor this: System.out.println(); System.out.println(); System.out.println("To enter a new word hit enter or else type 'done': "); System.out.println(); with this: System.out.println("\n\nTo enter a new word hit enter or else type 'done': \n"); There is a special symbol to break line, no need to call println function for this many times in a row.
8th May 2017, 8:28 PM
Jeth
Jeth - avatar
+ 1
i = i >= ring.length() ? i - ring.length() : i < 0 ? ring.length() + i : i;
8th May 2017, 8:15 PM
Jeth
Jeth - avatar
+ 1
Only if they used with complex statements or nested many times. If you don't like them why you want to refactor simple "if" statements? It is better to leave code in state of better readability for you. Even if it will take more lines.
8th May 2017, 8:25 PM
Jeth
Jeth - avatar