I seem to get a null when my code runs [closed] - java

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 8 years ago.
Improve this question
import java.util.StringTokenizer;
public class PigLatins {
String str1;
int vowelIndex;
String[] vowels = {"a","e","i","o","u","A","E","I","O","U"};
String counter = "";
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
}
At this part result[x].substring(1,vowelIndex) in the if statement, it seems to return null, why is it wrong and how could I fix it? (I removed the driver class as stackoverflow told me to I had too much code)

You should change :
for(int i = 0;i<vowels[i].length();i++)
to
for(int i = 0;i<vowels.length;i++)
Since you want to iterate over all the vowels in the array.
vowels[i].length() will always give you 1, since it's the length of the i'th String in the vowels array.
Beside that, it would make more sense to change the vowels array from String[] to char[].

the problem here is that the vowelIndex is 0 while you start in index 1 for the substring.
i don't quite understand what you are trying to achive but you need to check in you if statement the value of vowelIndex:
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i]))
the whole function should be
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
also you should not use an array of strings of you need an array of charecters, or if i understand correctly you should use a set of charecters

Related

Encode the string using stream api [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am looking for solution using stream api for below requirement. basically we need to write a encryption logic to convert a string
aaabbbbaae --> a3b4a2e1
Solution without stream's api :
public static void main(String[] args) {
String sampleString = "aaabbbaaaaaee";
char charters[] = sampleString.toCharArray();
char currentChar = charters[0];
char prevChar = charters[0];
int count = 0;
String str = "";
for (char c : charters) {
if(c==currentChar) {
count++;
prevChar = c;
}
else {
str = str + prevChar + count;
currentChar = c;
count=1;
}
}
System.out.println(str+currentChar+count);
}
This would be pretty easy to do yourself
String encryptToLettersAndNumbers(String input) {
String product = "";
char last = input.charAt(0);
int streak = 0;
for(int i = 0; i < input.length(); i++) {
if(input.charAt(i) == last) {
streak++;
} else {
product = product + last + streak;
streak = 1;
last = input.charAt(i);
}
}
product = product + last + streak;
return product;
}
Note that this code is untested. Furthermore this will be a very unsafe method of encryption because h1e1l2o1 is pretty easy to guess.
This should get you started-
String sampleString = "aaabbbaaaaaee";
Arrays.asList(sampleString.chars().mapToObj(c->(char)c).toArray(Character[]::new)).stream().forEach(c->{
//You can put your logic here to process
System.out.print(c);
});
This will convert your String to a Character list and stream through it.

How can I write a java program to check if a string is a substring of another string without using indexOf(), contains(), etc? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
for (int i = 0; i < str1.length(); i++)
{
String c = str1.substring(i, i + 1);
for (int j = 0; j < str2.length(); j++)
{
String d = str1.substring(j, j + 1);
if (d != c)
{
System.out.println("no");
}
else
{
System.out.println("yes");
}
}
}
I know this is not even correct but I have no idea how to start.
Do you mean as you would do in the classical introductory programming exercise?
E.g. something like this?
String a = "Hello, world!";
String b = "world";
boolean contained;
contained = false;
for (int i = 0; i < a.length() - b.length() + 1 && !contained; i++) {
contained = true;
for (int j = 0; j < b.length() && contained; j++)
if (a.charAt(i + j) != b.charAt(j))
contained = false;
}
System.out.println(contained ? "b is a substring of a" : "b is not a substring of a");
How can I write a java program to check if a string is a substring of
another string without using indexOf(), contains(), etc?
There are many ways (also based on which functions/methods you use) e.g. the following solution uses String#length and String#equalsIgnoreCase in addition to String#substring (the method which you have already used in your code). The logic checks if the subject substring is equal to (ignoring case) the substring of the same length starting from an index in str.
public class Main {
public static void main(String[] args) {
// Test
System.out.println(isSubstring("World", "Hello World!"));
System.out.println(isSubstring("foo", "Hello World!"));
}
static boolean isSubstring(String substring, String str) {
if (substring == null || str == null) {
return false;
}
int len = substring.length();
for (int i = 0; i <= str.length() - len; i++) {
if (substring.equalsIgnoreCase(str.substring(i, i + len))) {
return true;
}
}
return false;
}
}
Output:
true
false

Why won the if statement execute? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I wrote a simple program in Java which writes a word backwards. Trying to check if "hello" works. In if-statement I'm checking that string is equal to "olleh". Could anyone see why the if statement won't execute.
public class MyProgram {
public static void main(String[] args) {
String x = "hello";
System.out.println(back(x));
}
public static String back(String str) {
String y = " ";
String temp = " ";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
}
Try this it will work
public class MyProgram
{
public static void main(String[] args)
{
String x = "hello";
System.out.println(back(x));
}
public static String back(String str )
{
String temp = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
temp = temp + lets;
}
if (temp.equals("olleh")) {
System.out.println("nice");
}
return temp;
}
}
If you will initialize y variable to empty string instead of space your if-statement will execute and print "nice". Also you do not need a temp string as you don't use it. You probably want to return you reverted string back (alternatively you can make your method void and remove the return statement).
public static String back(String str) {
String y = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
By the way, it's better to use StringBuilder when you're concatenating strings in a loop.

Finding substring occurrence in string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find the number of substrings in a given string. Currently, My code doesn't take account of over lapping strings.
For example
substr = "cde"
str = "cdcde"
My code:
public static int ssCount(String str, String substr) {
int count = 0;
int strlen = str.length();
int substrlen = substr.length();
int numsubstr = 0;
int substrpointer = 0;
for (int i = 0; i < strlen; i++) {
if (str.charAt(i) == substr.charAt(substrpointer)) {
substrpointer++;
count++;
}
else {
count = 0;
substrpointer = 0;
}
if (count == substrlen) {
numsubstr++;
count = 0;
}
}
return numsubstr;
}
My attempt:
public static int ssCount(String str, String substr) {
int count = 0;
int strlen = str.length();
int substrlen = substr.length();
int numsubstr = 0;
int substrpointer = 0;
int firstchar = 0;
for (int i = 0; i < strlen; i++) {
if (str.charAt(i) == substr.charAt(substrpointer)) {
substrpointer++;
count++;
if (str.charAt(i) == substr.charAt(0)) {
firstchar = i;
}
}
else {
count = 0;
substrpointer = 0;
i = firstchar;
}
if (count == substrlen) {
numsubstr++;
count = 0;
}
}
return numsubstr;
}
I tried to add a 2nd pointer that will point to the next occurrence of the first character of the substring in order to continue the comparisons from that spot. However I am having trouble because I can run into some infinite loops.
This finds all overlapping sub-strings in a larger string. The non-regex way followed by the regex way. An interesting problem.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
<P>{#code java OverlappingSubstringsXmpl}</P>
**/
public class OverlappingSubstringsXmpl {
public static final void main(String[] igno_red) {
String sToFind = "cdc";
String sToSearch = "cdcdcdedcdc";
System.out.println("Non regex way:");
int iMinIdx = 0;
while(iMinIdx <= (sToSearch.length() - sToFind.length())) {
int iIdxFound = sToSearch.indexOf(sToFind, iMinIdx);
if(iIdxFound == -1) {
break;
}
System.out.println(sToFind + " found at index " + iIdxFound);
iMinIdx = iIdxFound + 1;
}
System.out.println("Regex way:");
Matcher m = Pattern.compile(sToFind, Pattern.LITERAL).matcher(sToSearch);
boolean bFound = m.find();
while (bFound) {
System.out.println(sToFind + " found at index " + m.start());
bFound = m.find(m.start() + 1);
}
}
}
Output:
[C:\java_code\]java OverlappingSubstringsXmpl
Non regex way:
cdc found at index 0
cdc found at index 2
cdc found at index 8
Regex way:
cdc found at index 0
cdc found at index 2
cdc found at index 8
Not sure what your question is, probably how to fix your code, but my recommendation is to look into standard approaches to solving this problem, such as the KMP algorithm. It efficiently takes into account overlaps too.

Can anybody help me to correct the following code?

Please help me to identify my mistakes in this code. I am new to Java. Excuse me if I have done any mistake. This is one of codingbat java questions. I am getting Timed Out error message for some inputs like "xxxyakyyyakzzz". For some inputs like "yakpak" and "pakyak" this code is working fine.
Question:
Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
public String stringYak(String str) {
String result = "";
int yakIndex = str.indexOf("yak");
if (yakIndex == -1)
return str; //there is no yak
//there is at least one yak
//if there are yaks store their indexes in the arraylist
ArrayList<Integer> yakArray = new ArrayList<Integer>();
int length = str.length();
yakIndex = 0;
while (yakIndex < length - 3) {
yakIndex = str.indexOf("yak", yakIndex);
yakArray.add(yakIndex);
yakIndex += 3;
}//all the yak indexes are stored in the arraylist
//iterate through the arraylist. skip the yaks and get non-yak substrings
for(int i = 0; i < length; i++) {
if (yakArray.contains(i))
i = i + 2;
else
result = result + str.charAt(i);
}
return result;
}
Shouldn't you be looking for any three character sequence starting with a 'y' and ending with a 'k'? Like so?
public static String stringYak(String str) {
char[] chars = (str != null) ? str.toCharArray()
: new char[] {};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'y' && chars[i + 2] == 'k') { // if we have 'y' and two away is 'k'
// then it's unlucky...
i += 2;
continue; //skip the statement sb.append
} //do not append any pattern like y1k or yak etc
sb.append(chars[i]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(stringYak("1yik2yak3yuk4")); // Remove the "unlucky" strings
// The result will be 1234.
}
It looks like your programming assignment. You need to use regular expressions.
Look at http://www.vogella.com/articles/JavaRegularExpressions/article.html#regex for more information.
Remember, that you can not use contains. Your code maybe something like
result = str.removeall("y\wk")
you can try this
public static String stringYak(String str) {
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='y'){
str=str.replace("yak", "");
}
}
return str;
}

Categories