Counting consecutive letters in java using JOptionPane? - java

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.

Related

How to Optimize Code and Code Optimization Theory

I have written a coding challenge. The requirement of the challenge is reversing the particular words in a sentence => still keep the oder the of the words in the sentence but reverse the characters of the word.
The input sample is something like this: RemoteIo is awesome-Candiates pass interview-best candiates are selected.
The sample output of the input above:
oIetomeR si emosewa
setaidnaC ssap weivretni
tseb setaidnac era detceles
As you can see the input sentences are separated by the - character so that mean we have 3 sentences in the example above and the sentence just able to contain anphabet characters and blank space only (one blank space between two words)
So my question is how can I optimize the below code and there is any theory/principle about Code Optimization. My code implementation in Java:
public class Test1 {
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
// Put sentences to a String array.
String[] data = input.split("-");
// Loop throw sentence array
for(int i = 0; i < data.length; i++) {
// Put the words from the sentence to a String array.
String[] words = data[i].split(" ");
// Loop throw the word array
for(int w = 0; w < words.length; w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >=0; j--) {
if (j != 0) {
System.out.print(words[w].charAt(j));
} else {
System.out.print(words[w].charAt(j) + " ");
}
}
if ( w == words.length -1) {
System.out.println();
}
}
}
}
}
The following code is bad: having ifs that refer to the loop variable is confusing and technically, maybe very slightly slower than the right way (though the compiler might just fix that for you.)
// Loop throw the word array
for(int w = 0; w < words.length; w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >=0; j--) {
if (j != 0) {
System.out.print(words[w].charAt(j));
} else {
System.out.print(words[w].charAt(j) + " ");
}
}
if ( w == words.length -1) {
System.out.println();
}
}
Instead do:
// Loop throw the word array
for(int w = 0; w < words.length; w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >0; j--) {
System.out.print(words[w].charAt(j) + " ");
}
System.out.print(words[w].charAt(j));
}
System.out.println();
Notice how I changed the j>=0 to j>0. The else block would only have triggered on the last repetition, so this is semantically equivalent.

How can I print a word two letters at a time? - java

The input is supposed to have an even length. The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho. I'm not sure how to make that jump.
public static void twoAtATime(String a) { // School
int len = a.length();
if(len%2 == 0) {
for(int i = 0; i <a.length()/2; i++) {
System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
System.out.println();
}
}
The output is supposed to be like this:
Sc
ho
ol
To fix it:
Increase i by 2.
Iterate until i < len.
You can improve it:
By calling substring once for two chars.
Using println with param.
Incrementing i once - i += 2.
After improvements:
public static void twoAtATime(String s) {
int len = s.length();
if (len % 2 == 0) {
for (int i = 0; i < len; ) {
System.out.println(s.substring(i, i += 2));
}
}
}

Receiving an error: variable i is already defined in method main

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.

Stopping a for loop without using break

I'm trying to write a program that prints all substrings of entered string. For example if user enter "rum" the output will be this:
r
u
m
ru
um
rum
import java.util.Scanner;
public class AllSubStrings
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = in.next();
String sub = "";
for(int i=0; i<str.length(); i++)
{
for(int a=0; a<str.length() ; a++)
{
if(i+a+1>str.length())break;
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
}
}
}
This program works perfectly but since we didn't learn how to use "break" in classes, i'm looking for something different. Any idea apart from "break" are welcome.
Thanks in advance.
You can use this while loop cycle instead of for:
int a = 0;
while (a < str.length && i + a < str.length()) {
sub = str.substring(a, i + a + 1);
System.out.println(sub);
a++;
}
Also it is possible to replace break with return statement
Calculate how many possible substrings there can be for a certain length. For example, length 1 = 1 substring, length 2 = 3, length 3 = 6, and so on.
Then loop for that many times. There should be a generic formula you can use for no matter how long of an input string.
You don't need a break to do this task.
int len = str.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.println( str.substring( i, j + 1 ) );
}
}
You can have two conditions in the for loop
for(int a = 0; a < str.length() && i + a < str.length(); a++)
{
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
Note that i + a + 1 <= str.length() is the same as i + a < str.length()

For loop with if inside not working

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.

Categories