I am having with my studies, I have problem where I am supposed to get an IP address from an user and then iterate it from right most number and if that number will be equal or more than 256 then I should iterate the number -1 place before this and this one set to 0.
I tried to solve it by simply making primitive code at first which would do it one time and only by user input and after that I would add more complexity like original more than one iteration, error checks and put code into propper .java files and classes. I understand that this would be better with ArrayList but I intended to add ArrayList instead of simple Array later.
Could anyone please tell me why the loop with condition put outofarraybound exception when I am not trying to iterate "i"?
for (i = 3; i >= 0; i--) {
pomoc = zasobnikIPadresa[i];
if (pomoc > 255) {
zasobnikIPadresa[i] = 0;
zasobnikIPadresa[i-1] = pomoc + 1;
}
}
So far I was able to analyze that I dont have proper knowledge of Arrays and I think that solution to my issue would help me to finish my problem and to better understand them.
here is full code so far:
package com.ipadresa.classes;
import java.util.Scanner;
public class Hlavni {
public static void main(String[] args) {
int i = 0;
int[] zasobnikIPadresa = new int[4];
Scanner ctecka = new Scanner(System.in);
for (i = 0; i < zasobnikIPadresa.length; i++) {
zasobnikIPadresa[i] = ctecka.nextInt();
}
System.out.print("Original IP adress: ");
for (i = 0; i < zasobnikIPadresa.length; i++) {
if (i < zasobnikIPadresa.length - 1) {
System.out.print(zasobnikIPadresa[i] + ".");
} else {
System.out.print(zasobnikIPadresa[i]);
}
} System.out.println();
int pomoc = 0;
for (i = 3; i >= 0; i--) {
pomoc = zasobnikIPadresa[i];
if (pomoc > 255) {
zasobnikIPadresa[i] = 0;
zasobnikIPadresa[i-1] = pomoc + 1;
}
}
System.out.print("Final IP adress: ");
for (i = 0; i < zasobnikIPadresa.length; i++) {
if (i < zasobnikIPadresa.length - 1) {
System.out.print(zasobnikIPadresa[i] + ".");
} else {
System.out.print(zasobnikIPadresa[i]);
}
}
ctecka.close();
}
}