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();
}
}
Since by this for loop condition, for (i = 3; i >= 0; i--) {, the variable i is allowed to == 0, then let's see what the array index is here when i is 0:
zasobnikIPadresa[i-1] = pomoc + 1;
it's -1. Ouch.
What if the condition
pomoc > 255
is true when
i==0.
Then you'll be accessing zasobnikIPadresa[-1] i.e. out of bound.
Related
I am struggling with this code here. I want print out dna in java that shows format of (0, 10, 6) which need to pass a until test
instead of looking like this
ACAAGATGCC ATTGTCCCCC GGCCTCCTGC TGCTGCTGCT CTCCGGGGCC ACGGCCACCG
CTGCCCTGCC CCTGGAGGGT GGCCCCACCG GCCGAGACAG CGAGCATATG CAGGAAGCGG
CAGGAATAAG GAAAAGCAGC CTCCTGACTT TCCTCGCTTG GTGGTTTGAG TGGACCTCCC
AGGCCAGTGC CGGGCCCCTC ATAGGAGAGG AAGCTCGGGA GGTGGCCAGG CGGCAGGAAG
GCGCACCCCC CCAGCAATCC GCGCGCCGGG ACAGAATGCC CTGCAGGAAC TTCTTCTGGA
AGACCTTCTC CTCCTGCAAA TAAAACCTCA CCCATGAATG CTCACGCAAG TTTAATTACA
It looks like this
ATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGG....
here is my code
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for(int i = 0; i < groupsPerLine; i++) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
formattedSequence.append(sequence.charAt(num));
num++;
}
}
}
}
return sequence;
}
}
You should append a white space to the sequence after a dna sequence is appended (at the end of the inner for loop). Also, when a line is full, you should append a new line (\n) character to the sequence(at the end of the outer for loop).
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for(int i = 0; i < groupsPerLine; i++) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
formattedSequence.append(sequence.charAt(num));
formattedSequence.append(" ");
num++;
}
}
formattedSequence.append("\n");
}
}
return formattedSequence.toString();
}
Looking at your code, I think you just missed some little things here and there, add a new line break after a certain character count and a space after some groups, and also you were returning the wrong variable.
Here check this code I edited based on yours, I just added some simple stuff and you got the remaining right.
public String formatInGroups(int index, int basesPerGroup,
int groupsPerLine) {
// I suppose you have a 'sequences' list somewhere
sequences.add(dna());
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
if (num % (basesPerGroup * groupsPerLine) == 0){
formattedSequence.append("\n");
}
formattedSequence.append(sequence.charAt(num));
num++;
}
}
formattedSequence.append(" ");
}
return formattedSequence.toString().trim();
}
Little things to consider on your next problem:
1 - You were returning your original sequence instead of the formattedSequence.toString();
2 - Try to avoid using global variables, you can declare them inside your for loop;
3 - Try using better variable names, instead of num you could name your variable after something that it is doing, like charPositionCounter, it will improve your code readability.
I am trying to write a program that:
1) asks for user input to create an array of 10 elements
2) checks to make sure the elements are distinct
3) identifies the highest value among the elements.
I think Im close but I keep receiving this error message:
error: variable i is already defined in method main(String[])
for (int i = 0; i < myList.length; i++) {
Here is my full code:
import java.util.Scanner;
public class max101 {
public static void main(String[] args) {
double[] myList = new double[10];
double max = myList[0];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " distinct numbers: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble ();
for(int i = 0; i <myList.length; i++) {
for(int j = i+1; j<myList.length; j++) {
if(myList[i] == (myList[j])); {
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if(myList[i] != (myList[j])); {
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
}
}
Try using different variable names in your loops
If you dont want to do the above dont reinitialize the variable with int just put i = 0
It might also be useful to look into how scope works.
My suspicion is you’re not ending your blocks properly — a block meaning from { to }. When I have my IDE indent your code, it is:
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
for (int i = 0; i < myList.length; i++) {
for (int j = i + 1; j < myList.length; j++) {
if (myList[i] == (myList[j]))
;
{
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if (myList[i] != (myList[j]))
;
{
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
I think you see now that i is declared inside a for loop that already declares i. Also once you’ve detected a duplicate I think you should break out of the two loops rather than checking for more duplicates, and not find a max until the user has entered 10 new numbers.
One more tip, don’t put a semicolon after your if ( … ), it breaks your logic.
I'm trying to count consecutive letters in java using JOptionPane and when I try to compile and run my code I get this:
exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range: 5
I feel like I have most of it down so I'm not exactly sure what's wrong here. Any help would be appreciated.
My code:
import javax.swing.JOptionPane;
public class Project {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enter a string...");
while (true) {
if (input.equals("Stop")) System.exit(0);
else {
int count = 0;
int len = input.length();
for (int i = 0; i < len; i++) {
if (input.charAt(i) == input.charAt(i + 1)) count++;
}
JOptionPane.showMessageDialog(null, "There are " +
count + "pairs of consecutive letters.");
input = JOptionPane.showInputDialog(null,
"Enter a string...");
}
}
}
}
Problem is:
input.charAt(i + 1)
This will throw an error because when you are at the last element of the array it will try and get the next element but there isn't one. Consider revising your logic slightly.
In your for loop you could do:
for (int i = 0; i < len - 1; i++) {
The JOptionPane has absolutely nothin to do with that, you should fix your title. The problem is here :
for (int i = 0; i < len; i++) {
if (input.charAt(i) == input.charAt(i + 1)) count++;
}
replace that piece of code with
for (int i = 0; i < len - 1 ; i++) {
if (input.charAt(i) == input.charAt(i + 1)) count++;
}
This is a basic error, it is important for an efficient programer to be able to deal with this alone and quickly.
I am a student in a beginning java class, I got some help earlier today on my assignment, which really helped! So I thought I would give it one more try, before I throw in the towel on this last part. I have been able to get everything going, but my sort just doesn't work. I have to use this format, as my professor does not want us to use sort APIs. It processes correctly, meaning I get the same results by hand as when I run it, so I think the problem is in the logic itself. Can anyone see what I am doing wrong and offer any hints or helps. Thanks in advance. Here is my code for my sort loop:
int i, j; // used to index into the array
double temp;
for (i = 1; i < count ; ++i) {
temp = students[i].getGPA();
j = i - 1;
while (j >= 0 && temp < students[j].getGPA())
{
students[j + 1] = students[j];
j = j - 1;
}
students[j + 1]= students[i];
}
Your are not doing the swapping correctly. Check this sample code:
for (int i = 0; i < students.length; i++)
{
for (int j = 1; j < students.length - i; j++)
{
if (students[j - 1].getGPA() > students[j].getGPA())
{
// assuming that your class name is Student
Student temp = students[j - 1];
students[j - 1] = students[j];
students[j] = temp;
}
}
}
Your problem is that the first iteration through the while loop overwrites students[i]. You need to keep students[i], and not just its GPA, in a temporary value when you enter the for loop.
Refined your logic little bit. Plz verify for appropriateness!
package com.kvvssut.misc;
public class SortArray {
public static void main(String[] args) {
double [] studentsGPA = {8.3,7.2,10,6.5,4.9};
int count = studentsGPA.length;
int i, j; // used to index into the array
double temp;
for (i = 1; i < count ; ++i) {
j = i;
while (j > 0 && (temp = studentsGPA[j]) < studentsGPA[--j]) { // can use students[j].getGPA() similarly
studentsGPA[j+1] = studentsGPA[j];
studentsGPA[j] = temp;
}
}
for (double sgpa : studentsGPA ) {
System.out.println(sgpa);
}
}
}
I would like my print statement to be outside the loop so the statement doesn't print the same thing over and over. The for loop below simply checks a number from one array against another to find out how many matches have been found. Defining the variables above and printing the statements below results in a "variable not initialised error" which is understandable.
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
int lottMtch = count(chkNum, rndNum);
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
System.out.print(chkNum);
}
else {
System.out.print("no matches found");
}
}
Declare the variable before the loop and then do your stuff in the loops, like adding one to the variable if it is found, then print it out afterwards if it is more than 0. Something like this...
int var = 0;
for(...) {
if(found)
var++;
}
if(var > 0)
sysout(var);
Of course this code won't work but it is a start. For your learning experience I will let you implement this idea with your code.
this would not really make sense ..
if you want than Try this ...
int lottMtch[]=new int[myArray.length];
Arrays.fill(lottMtch, 0);
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
lottMtch[i] = count(chkNum, rndNum);
}
for (int i = 0; i < 6; i++)
{
if (lottMtch[i] > 0)
System.out.println(lottMtch[i] + " matches found "+ myArray[i]);
}
If you wan to found just how many match of rndNum in myArray Than try this
Here i assume rndNm is global
int lottMtch=0;
for (int i = 0; i < 6; i++)
{
lottMtch += count(myArray[i], rndNum);
}
if (lottMtch> 0)
System.out.println(lottMtch + " matches found "+ rndNum);
As per discussed in comment Try this ..
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < 6; i++)
{
Integer chkNum = myArray[i];
Integer cnt = (Integer)count(myArray[i], rndNum);
if(cnt>0)
{
if(map.get(chkNum)==null)
map.put(chkNum,1);
else
map.put(chkNum, map.get(chkNum)+1);
}
}
for (Object key : map.keySet())
System.out.println(map.get(key) + " matches found "+key.toString());
This is because if you only declare the variables above the loop and only initialize said variables in the loop, when you attempt to print them outside of the loop, there's no guarantee that they would have been initialized.
So, perhaps you want something like this:
int lottMtch = 0;
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
lottMtch += count(chkNum, rndNum);
//System.out.print(chkNum); this would not really make sense outside of the loop
}
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
}
else
{
System.out.print("no matches found");
}
You need to declare a variable outside the loop if you plan to access it after the loop exits.
You need to initialise variables outside the loop. Try this:
int chkNum = 0;
int lottMtch = 0;
for (int i = 0; i < 6; i++)
{
chkNum = myArray[i];
lottMtch = count(chkNum, rndNum);
}
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
System.out.print(chkNum);
}
else {
System.out.print("no matches found");
}