Scope of Local Variable [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I'm still confused with scope of local variable
This code doesn't work because i in "i & n" is not resolved. I have identified it on for loops as int i =0. is it not enough? (This is adding nth character altogether our of string).
public String everyNth(String str, int n) {
String result = "";
for (int i = 0; i <= str.length(); i++); {
if (i%n == 0) {
result = result + str.charAt(i);
}
else {
result = result;
}
}
return result;
}

To expand on Jon Skeet's answer-worthy comment, the semi-colon at the end of for (int i = 0; i <= str.length(); i++); finishes the for-statement, and i is no longer in scope after the semi-colon.

You are a few errors:
You can remove the else{ ... } part because you don't need it.
You have a extra ';' in your for loop statement.
There is a mistake on the index of the for loop. You need to do 'i less than' str.length(), instead of i<=str.length(). Basically your for loop will try to access the full-length index of your character array, but actually it exceeds length. For example, the index for string 'hello' is 0,1,2,3,4. But "hello".length() is actually 5. If you try to access the 5th index of your string, you will see a 'java.lang.StringIndexOutOfBoundsException' exception.
Also, you want the every Nth value, you want to do (i-1)%n. Again it is because of the index issue. Try to plug in parameters in your logic and use your pencil to write down the result, and you will see why.
And of course when i==0, you don't want (0-1)%n to happen. So skip i==0 by adding 'i!=0'.
Now, the following is the working code:
public static String everyNth(String str, int n) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if ((i-1)%n == 0 && i!=0)
result = result + str.charAt(i);
}
return result;
}

Related

Leetcode longest common prefix [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 3 months ago.
Improve this question
I am having a hard time following this solution. I understand we set a prefix, and loop through the remainder of the array and keep chopping the prefix until prefix fully exists in each string but why are we doing strs[i].indexOf(output) != 0 in the while loop?
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0) {
return "";
}
String output = strs[0];
for(int i = 1; i < strs.length; i++) {
while(strs[i].indexOf(output) != 0) {
output = output.substring(0, output.length() - 1);
}
}
return output;
}
Much more understandable (and efficient) would be to use "not startWith."
while (!strs[i].startsWith(output)) {
output = output.substring(0, output.length() - 1);
}
indexOf would also search at other positions for a substring equal to output.
This would be more readable as "as long as strs[i] does not start with the prefix, shorten the prefix by 1. An empty prefix (output) would exit the loop. (You might then also break out of the for loop.)
!= 0 means that the prefix string did not start at the beginning of the string. If the index > 0 it was further into the string. If it was -1 it didn't exist in the string at all. If it was == 0 it started at the beginning.
Notice that the while loop keeps backing up using substring until a prefix matches the beginning. Then it exits the while loop. Then it continues to see if the next string contains the first and backs up until they share an equal prefix. This continues until either a longest common prefix is returned or an empty string.

java regex questions [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 5 years ago.
Improve this question
Given that I have a string of number, like "12354789556", I need to check that string whether has digits from 0 to 9 at least once.
Can anyone tell me whether i can express this in regex please?
If your strings contains only digits for example "123548955664789556" then try:
System.out.println(myString.chars().distinct().count() == 10);
if your string can also contain letters for example sth like "bbb1235489556fhjerfs64789556"
System.out.println(myString.replaceAll("[^\\d]", "").chars().distinct().count() == 10);
With lookaheads :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
If you want to restrict the string to digits only in addition to making sure it contains every digit :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)\d+$
Note that a version without lookaheads would be technically possible, but would realistically have to be crafted by code as it would have to enumerate all possible orders between digits (10! = 3628800 enumerations).
You can also do it in Java like this:
boolean containsAll = true;
for (int i = 0; i < 10; i++) {
if (!str.contains("" + i)) {
containsAll = false;
}
}
return containsAll;
A non-regex way would be to loop through the String and return false if the indexOf returns -1:
static boolean checkAll(String s, char[] allNums) {
for (int i = 0; i < allNums.length; i++) {
if (s.indexOf(allNums[i]) == -1) {
return false;
}
}
return true;
}
Example

how to reverse n characters of n parts in string using java [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 5 years ago.
Improve this question
For example, string = "ABCDEFGH". if n=2, then output should be "BADCFEHG"; if n=3, output should be "CBAFEDHG".
I know i should use stringbuilder to reverse, but how can i split the string to n parts and then reverse each part?
I will not give you a code for this, you need to learn by trying.
Do this requirement step by step :
how to read that String block by block : String.substring(int, int) in a loop. You need to understand how to calculate the boundery of each blocks
how to reverse a String : see about Reverse a String in JAVA
create the output by mixing those two steps.
Don't try to do everything in once. Find how to do those two separatly, then put the logic together. This is quite simply in the end.
String newStr="";
String oldStr = "ABCDEFGH";
for(int i =0; i<oldStr.length();i+=n) {
if(i+n >= oldStr.length()){
n = oldStr.length()-i;
}
newStr += new StringBuilder(oldStr.substring(i,i+n)).reverse().toString();
}
Edit: Sorry for missreading your question, this little loop does what you're asking for!
What we are doing here is making oldString.length() / n iterations to split the String in n portions. Because the length might not be dividable by your n we have to check if i+n wont be larger than the length of your word (eventually creating a IndexOutOfBoundsException). If this is the case we just set n so that it adds to i to the rest of the word. Hope that explains it well.
I've given you most of the code but it's unfinished. You will have to understand what I left out and how to fix it to complete the problem.
String originalString = someString; //String from user
String tempString = ""; //String used for temporary reasons
String finalString = ""; //Your end result
int n = someNumber; //Number from user
//Loops through the original string, incrementing by n each time
for (int i = 0; i < originalString.length() - n; i += n)
{
//Gives us the current substring to reverse
tempString = originalString.substring(i, i + n);
//Starts at end of substring and adds each char to the final string
for (j = n - 1; j >= 0; j--)
{
finalString += tempString.charAt(j);
}
}

Java's weird unreachable code error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I'm writing a program that identifies whether a String "xyz" is certralized in the input String or not. I create a variable that stores the position of "xyz" with a for loop, and then compare it to the number of chars before and after, creating ints with .substring() and .length(). Strangely enough, the code doesn't compile after the first if - which returns true or false, saying whatever return statement after that is unreachable.
Could anyone help me wrap my head around this?
Thanks a lot!
Maybe because the length variables haven't been run yet and, for the compiler,
they will always be different? How to solve that?
public static boolean xyzCenter(String str){
//identifies the position of "xyz" within the String.
int xyzPosition=1;
//loops through the string to save the position of the fragment in a variable.
for(int i = 0; i<str.length(); ++i){
if(str.length()>i+2 && str.substring(i, i+3).equals("xyz")){
xyzPosition=i;
}
}
//ints that determine the length of what comes before "xyz", and the
length of what comes after.
int lengthBeg = str.substring(0, xyzPosition).length();
int lengthEnd = str.substring(xyzPosition+3, str.length()).length();
if ((lengthBeg != lengthEnd));{
return false;
} //this compiles.
return true; //this doesn't!
if ((lengthBeg != lengthEnd)); <----- remove that semicolon
When you put a semicolon at the end of an if it is like having an empty if block. Your code is equivalent to
if ((lengthBeg != lengthEnd)) {
// Do nothing
}
{
return false;
}
return true; // Unreachable because we already returned false

Why does it keep saying unreachable ? Where am I meant to put the assignment statement then? [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 8 years ago.
Improve this question
public String toString() {
return questionText + "\n";
char label = 'a';
for(int i= 0; i < answers.length; i++){
return "("+label+")"+" "+answers[i]+ "\n";
label++;
}
}
It keeps saying line 4 is unreachable.
Because of return Statement at the very first line.
Once return is called, following lines doesn't matter.
I don't know what questionText is doing, but it may work fine even without the first line itself. Cheers
Because you have a return statement (question text) immediately after the start. So the char assignment will not run
After the return, you've left the function. Anything below that (within this function) can never execute.
This is how it should be with your code, and please dont forget, if answers.length() is just 2 also, it will return only first answer as you are already calling return. I would recommend saving this in list and returning list.
public String toString() { return questionText + "\n"; char label = 'a';
for(int i= 0; i < answers.length; i++){
label++;
return "("+label+")"+" "+answers[i]+ "\n";
}
With list :
public String toString() {
List<String> stringList = new ArrayList();
for(int i= 0; i < answers.length; i++){
arrayList.add(answers);
label++;
}
return arrayList;
I cannot understand your data structure as its written very badly by you. So, I can only help this much.

Categories