Why is my for-loop not functioning? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm making a program that counts the number of vowels in a phrase that was assigned by my teacher. To do this I have made a for-loop that in theory should check each character for being a, then e, the i, and so on before moving on to the next character. For some reason though nothing in the for-loop works. The build output states that everything is fine, but the for-statements aren't functioning properly. I know that t actually is the correct letter because I printed what t was but the for loop still won't work. What confuses me is the build output is fine, so it must be a logic error, but I can't find where it is. Here is the code:
for (i = 0; i != phrase.length(); i++) {
String t = phrase.substring(i, i + 1);
if (t == "a") {
count++;
System.out.println(count);
}
if (t == "e") {
count++;
}
if (t == "i") {
count++;
}
if (t == "o") {
count++;
}
if (t == "u") {
count++;
}
}
System.out.println(count);
Many thanks to anyone who can help me!

the exit condition is wrong, try:
for (i = 0 ; i < phrase.length(); i++) {

You have several issues in your code.
1) First issue being the i == phrase.length(). This is the until condition. Change this to i <= phrase.length(). *
In your case this would have worked but it's better to do it right. Normally you check on values here that could for example grow bigger than 10 and if you skip 10 and keep counting you would enter an infinite loop. So always use <= or >=.
*edit: Correction you should use < since you have a substring working with i+1.
2) Don't use == for String (or any other object) comparison. That will compare the memory address instead. For String use the equals() method.
Also make sure to put the known literal "a", "b" and so up front since you could get a nullpointer exception otherwise.
3) It might be better to go for a charAt(0) first and then use == since you can compare char (primitive) values.
4) I also combined the if statements in one.
String phrase = "WazzUp ? Who’s On FIRST??? IDUNNO";
phrase = phrase.toLowerCase();
System.out.println("value of phrase is: "+phrase);
int count = 0;
for (int i = 0 ; i < phrase.length() ; i++) {
String t = phrase.substring(i, i + 1);
if ("a".equals(t) || "e".equals(t) || "i".equals(t) || "o".equals(t) || "u".equals(t) ) {
count++;
}
}
System.out.println("value of count is: "+count);

Check the for exit condition and String comparison, which should be done using equal: if ("a".equals(t)) { ... }.

Your for-decleration is wrong.
It should be
for(<startexpression> ; <any expression, that is still true> ; in-/decrement>)
In your case you start with i=0, so on the same run i cannot equal phrase.length()in your case. This is why you code does not get executet.
Try:
for (i = 0 ; i < phrase.length(); i++) {
instead.
Also, when comparing string, you should use
String.equals("whatever")
instead of the equeals-operator (=).

In your for loop, shouldn't it be i = phrase.length() instead of i ==? i == is doing comparison instead of setting i equal to (i = sets it equal to something instead of comparing)

As to what emilioicai said your conditions is wrong
for (i = 0 ; i == phrase.length(); i++) { <----! Wrong
for (i = 0 ; i < phrase.length(); i++) { <---- Correct
Also strings Should be compared with equals, so instead of this
if (t == "a") {
count++;
System.out.println(count);
}
You should have this
if ("a".equals(t)) {
count++;
System.out.println(count);
}
And if you want to go fancy you can do something like this :)
String phrase = "WazzUp ? Who’s On FIRST??? IDUNNO";
phrase = phrase.toLowerCase();
System.out.println("value of phrase is: "+phrase);
int count = 0;
String[] characters = new String[] {"a", "e", "i", "o", "u"};
for (int i = 0 ; i < phrase.length() ; i++) {
String t = phrase.substring(i, i + 1);
for(String character : characters){
if(character.equals(t)){
count++;
}
}
}
System.out.println("value of count is: "+count);
The above makes code nicer, more scalable, and easier to read

There are two errors about your code.
First, for (i = 0 ; i < phrase.length(); i++) {}
Second, if (t .equals("a")) { but not if (t == "a") {

try this:
for (i = 0; i != phrase.length(); i++) {
String t = phrase.substring(i, i + 1);
System.out.println(t);
if (t.equals("a")) {
count++;
System.out.println(count);
}
if (t.equals("e")) {
count++;
}
if (t.equals("i")) {
count++;
}
if (t.equals("o")) {
count++;
}
if (t.equals("u")) {
count++;
}
}
by the way, it's more common to change your condition to this:
i < phrase.length()
since it shows the progress better and increases the readability of your code.

Make it this way
String phrase = "WazzUp ? Who’s On FIRST??? IDUNNO";
phrase = phrase.toLowerCase();
int count = 0;
int i = 0;
System.out.println(phrase);
for (i = 0 ; i < phrase.length(); i++) {
String t = phrase.substring(i, i + 1);
if (t == "a") {
count++;
System.out.println(count);
}
if (t == "e") {
count++;
}
if (t == "i") {
count++;
}
if (t == "o") {
count++;
}
if (t == "u") {
count++;
}
}
System.out.println(count);

Related

String out of Index :java.lang.ArrayIndexOutOfBoundsException. String overflows maybe

class Solution {
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;//index of strs
int j;//index of the first one of string
for(j = 0; j < strs[0].length(); j++){
compareElement = strs[0].charAt(j);
for(i = 1; i < strs.length; i++){
if(compareElement == strs[i].charAt(j)){
if(i == strs.length - 1)
result += compareElement;
else
continue;
}
else{
break;
}
}
}
return result;
}
}
Test sample is
Input: ["flower","flow","flight"]
Output: "fl"
hi there I have got a problem with string in Java in my 4th small program in Leetcode. The aim of this function is to find the longest common prefix string amongst an array of strings. But the exception
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:614)
at Solution.longestCommonPrefix(Solution.java:11)
at __DriverSolution__.__helper__(__Driver__.java:4)
appears over again.
Has someone any idea? Thanks!
I think this is where you go wrong:
if(compareElement == strs[i].charAt(j))
j can become too large as it goes from 0 to strs[0].lenght() (see your outer loop).
If strs[i].lengt() is smaller than strs[0].length() you get an StringIndexOutOfBoundsException.
When you iterate through the comparison strings, you're never checking the length of the string you're comparing. In your example the test case flow. The char at index 4 doesn't exist since only indices 0-3 are defined. if(compareElement == strs[i].charAt(j)){ when j is 4 it'll mess up. In order to fix it you have to make sure you're not going past the length of the string. In addition to that look up what a StringBuilder is, for this small of a test case it won't matter however as you go up larger it will.
Your code fails if you have an element in the array which is shorter than the first element. You need to check that j is still smaller than the length of the string you're comparing:
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;// index of strs
int j;// index of the first one of string
for (j = 0; j < strs[0].length(); j++) {
compareElement = strs[0].charAt(j);
for (i = 1; i < strs.length; i++) {
if (j < strs[i].length() && compareElement == strs[i].charAt(j)) {
if (i == strs.length - 1)
result += compareElement;
else
continue;
} else {
break;
}
}
}
return result;
}

Brute force: count number of sub strings in a string array

What I am supposed to do is create an algorithm that counts the number of substrings in a piece of text where the substrings can be the letter B followed by C or C followed by B. I'm not sure what to do, but I tried it and came up with the result below. I'd like to know if I did it correctly.
int substrCount(String S[0...n-1]){
int count = 0;
for (int i = 0; i<=n-2; i++) {
for (int j=i+1; j<i+2; j++) {
if ((S[i] == 'B' && S[j] == 'C' ) || (S[i] == 'C' && S[j] == 'B')) {
count = count + 1;
}
}
}
}
I am gonna ignore whether it includes lowercase or uppercase for now. I also need to find the complexity of the algorithm from which I believe it is O(n^(2)). Did I do this correctly? If so, can I make it any more efficient?
This works well for me
static int substrCount( String str) {
int count=0;
for (int i=0; i<str.length()-1; i++)
{
boolean bc = (str.charAt(i) == 'B' && str.charAt(i+1) == 'C');
boolean cb = (str.charAt(i) == 'C' && str.charAt(i+1) == 'B');
if (bc || cb) {
count++;
}
}
return count;
}
You need to loop the sequence of chars in string just once to get the desired result. Check the couple of chars if they are equal "BC" or "CB" and move one index forward to the end of the string.
Output example:
"ACBAA" gives result 1
"ABCBA" gives result 2
"BCBCB" gives result 4
"BBBBB" gives result 0

Java Code output If input is "aabbba" then output should be "a2b3a1" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am doing one simple java code where if
input is : "aabbba"
then
output should be: "a2b3a1"
I have done the below coding but missing somewhere. So let me know my mistake.
public class Test {
public static void main(String[] args) {
String str = "aabbba";
int count = 1;
for (int i = 0; i < str.length(); i = i + count) {
count = 1;
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count = count + 1;
} else {
System.out.println(str.charAt(i) + "" + count);
break;
}
}//end of inner for
}//end of outer for
}//end of main
}//end of class
Actually you have too much code, You only need one loop, and you should be comparing the letter to the previous one, not attempting to compare each letter to every letter after it.
If you are confused about what your program is doing, the best place to start is to use your debugger to step through the code.
for(int i = 0, count = 1; i < str.length(); i++, count++) {
char ch = str.charAt(i);
char next = i + 1 < str.length() ? str.charAt(i + 1) : (char) -1;
if (ch != next) {
System.out.print("" + ch + count);
count = 0;
}
}
Using your effort and code, you simply did put the print to the wrong place
String str = "aabbba";
int count = 1;
for(int i = 0; i <str.length();i=i+count){
count =1;
for(int j = i+1; j<str.length();j++){
if(str.charAt(i) == str.charAt(j)){
count = count+1;
}
else{
break;
}
}
// Print here otherwise you will miss the last group of letters
// Also if you just want one line use .print instead of println
System.out.print(str.charAt(i)+""+count);
}
Using Java-8 and my StreamEx library it's a one-liner:
String input = "aabbba";
String result = IntStreamEx.ofChars(input).mapToObj(ch -> (char)ch)
.runLengths().join("").joining();
Step-by step:
IntStreamEx.ofChars(input): create IntStreamEx (enhanced IntStream) where each element is the corresponding character of input line.
.mapToObj(ch -> (char)ch): transform to StreamEx<Character> (enhanced Stream<Character>) where each element is the Character object.
.runLengths(): convert to EntryStream<Character, Long> (enhanced Stream<Map.Entry<Character, Long>>) where keys are Character objects and values are counts of equal adjacent characters.
.join(""): convert to StreamEx<String>, joining keys (characters) and values (counts) via given empty separator.
.joining(): final reduction to the resulting string without additional separators.
You're just missing the print of the last group of letters. you only print inside the loop once you found a different letter, you should take into account the last group of letters that has no "different letter" after it
I would suggest using a StringBuilder:
public String myOutput(String str) {
if (str == null || str.length() == 0)
return str;
StringBuilder sb = new StringBuilder();
int count = 1;
char currentChar;
for (int i = 0; i < str.length() - 1; i++) {
currentChar = str.charAt(i);
if (currentChar == str.charAt(i+1)) {
count++;
} else {
sb.append(currentChar);
sb.append(String.valueOf(count));
count = 1;
}
}
sb.append(str.charAt(str.length()-1));
sb.append(String.valueOf(count));
return sb.toString();
}
You only need 1 loop
System.out.println() will cause your output to have line break. You better use System.out.print(). Now your currrent code is resulting :
a2
b3

Find if Entered Password is valid or not?

This is an interview question. I think the code below, works a bit and has some errors. The problem is as follows -
In 1-9 keypad one key is not working. If some one enters a password then not working key will not be entered. You have given expected password and entered password. Check that entered password is valid or not
Ex: entered 164, expected 18684 (you need to take care as when u enter 18684 and 164 only both will be taken as 164 input)
The code which does above is below.
public static void main(String[] args){
System.out.println(IsAMatch("164","18684"));
}
static boolean IsAMatch(String actual, String expected)
{
char faultyKey = '\0';
int i = 0, j = 0;
for(; i < expected.length() && j < actual.length(); ++i)
{
if(actual.charAt(j) != expected.charAt(i))
{
if('\0' != faultyKey){
if(faultyKey != expected.charAt(i))
return false;
}
else{
faultyKey = expected.charAt(i);
}
}
else{
++j;
}
}
System.out.println("FaultyKey= "+faultyKey);
return (i == expected.length() - 1 && j == actual.length() - 1)? true : false;
}
It is detecting the faulty key correctly (Ex here it is 8), but giving wrong output (As False) Even though the test case used above should give true.
Any suggestions to fix this? If any better method/ideas are most appreciated.
Change the return statement to:
return (i == expected.length() && j == actual.length())? true : false;
The bug is that i and j are both increased first and then checked if they meet the loop condition. Obviously both i and j fail to meet the condition as the control flow breaks out from the loop. Therefore, i and j are exactly equal to expected and actual length respectively.
Moreover, the expression in your return statement is gratuitous. You could just return true at that point of the program as it is a tautology at that stage. I.e. there is no way that you can be at that point in your code and your expression evaluates to false.
static boolean IsAMatch(String actual, String expected) {
char faultyKey = '\0';
int i = 0, j = 0;
for (; i < expected.length(); ++i) {
if (j >= actual.length() || actual.charAt(j) != expected.charAt(i)) {
if ('\0' != faultyKey) {
if (faultyKey != expected.charAt(i)) {
return false;
}
} else {
faultyKey = expected.charAt(i);
}
} else {
++j;
}
}
System.out.println("FaultyKey= " + faultyKey);
return (i == expected.length() && j == actual.length()) ? true : false;
}
Consider the following condition
System.out.println(IsAMatch("164", "186848"));
Your logic will not work, because before i meets the length j would meet the actual length.
you dont need to have condition j < actual.length in for loop.
Your return statement should be :
return (i == expected.length() && j == actual.length()) ? true : false;
or, simpler :
return (i == expected.length() && j == actual.length());
because i and j reach the length of the strings when the loop ends.
The issue is with these two statements:
i == expected.length() - 1
j == actual.length() - 1
Remove the - 1 by each of them and it should work fine.

Java Counting letter,digit and symbol

I want to count the number of letter, digit and symbol using JAVA
However the result output is not ideal. it should be 5,2,4
but I got 5,2,13
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
} else if (y.contains("<")) {
symbol++;
}
}
System.out.println(charCount);
System.out.println( digitCount);
System.out.println( symbol);
It should be
} else if (temp == '<')) {
symbol++;
}
In your solution, for every non-letter-or-digit character you check if the entire string contains <. This is always true (at least in your example), so the result you get is the number of special characters in the string.
You should use y.charAt(i) == '<' rather than y.contains("<")
if you use y.contains("<"), it uses the whole string to check whether it contains '<' or not. Since String y contains '<'. When in for loop, there are 4 '<', 6 '+' and 3 '>'.
For checking such charraters, y.contains("<") always be true. That is why you get 13 (=4+6+3) for symbol rather than 4.
This bit is wrong:
y.contains("<")
You are checking the whole string each time when you only want to check a single character (temp)
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
****} else if (temp =="<") {
symbol++;
}
}****
else if (y.contains("<")) {
should be
else if (temp == '<') {
because else every time youu have no letter or digit it is raised.
y.contains("<")
seaches for the substring "<" in the string "apple66<<<<++++++>>>" and it always finds it. This happens 13 times which is the number of chars in the substring <<<<++++++>>>" which does contains neither a letter nor a digt.

Categories