- 123
- 234
- 345
- 451
- 512
First, let us make the pseudo-code before trying to code instead.
- Declare `n` = "12345"
- Declare `length` = length of `n`
- Declare `i` as integer
- Loop start from `i` = 0 to `length`- 1
- Display sub-string of `n` from `i` to `i` + 3
And convert it to code.
- public class SequenceNumber {
- public static void main(String[] args) {
- String n = "12345";
- int length = n.length();
- int i;
- for(i = 0; i < length; i++) {
- System.out.println(n.substring(i, i + 3));
- }
- }
- }
And let us check the output.
- 123
- 234
- 345
- Exception in thread "main" java.lang.StringIndexOutOfBoundException: String index out of range: 6
- at java.lang.String.substring(String.java:1955)
- at SequenceNumber.main(SequenceNumber.java:8)
Wow, for the first time to code and we already make an exception, nice. Let's try figure out, in the line 8 of class Sequence Number the compiler said that "String index out of range: 6" that means when `i` = 3 it will get the sub-string of `n` from 3 to 6. If you try to display the `length` it will print 5, so the problem that make this exception is `i` + 3. Let's change the pseudo-code to make it avoid the exception.
- Declare `n` = "12345"
- Declare `length` = length of `n`
- Declare `i` as integer
- Declare `x` as integer
- Loop start from `i` = 0 to `length` - 1
- Check if `i` + 3 > `length`
- Set `x` = length of sub-string of `n` from `i`
- Display sub-string of `n` from `i` concat with sub-string of `n` from 0 to 3 - `x`
- Else
- Display sub-string of `n` from `i` to `i` + 3
And make some update in the current code.
- public class SequenceNumber {
- public static void main(String[] args) {
- String n = "12345";
- int length = n.length();
- int i;
- int x;
- for (i = 0; i < length; i++) {
- if (i + 3 > length) {
- x = n.substring(i).length();
- System.out.println(n.substring(i) + n.substring(0, 3 - x));
- } else {
- System.out.println(n.substring(i, i + 3));
- }
- }
- }
- }
If you want to make it shorter in the code, try this one.
- public class SequenceNumber {
- public static void main(String[] args) {
- char[] digits = Integer.toString(12345).toCharArray();
- for (int i = 0; i < digits.length; i++) {
- System.out.println("" + digits[i] + digits[(i + 1) % digits.length] + digits[(i + 2) % digits.length]);
- }
- }
- }
References:
How can get the possible 3 digit combination from a number having more than 3 digits in java.
No comments:
Post a Comment