Continue operator doesn't continue the for loop - java

Trying to continue iterating if (str1Number == str2Number), but the loop stops after incrementing the i variable
String getOldestVersion (String str1, String str2) {
String[] str1Arr = str1.split("\\.");
String[] str2Arr = str2.split("\\.");
String result = "";
int str1Number = 0;
int str2Number = 0;
for (int i = 0; i < str1Arr.length-1; i++) {
str1Number = Integer.valueOf(str1Arr[i]);
str2Number = Integer.valueOf(str2Arr[i]);
if (str1Number > str2Number) {
result = str1;
break;
} else if (str1Number == str2Number) {
i++;
continue;
} else {
result = str2;
break;
}
}
return (result);
}

As said in the comments "using continue as the last statement in a loop doesn't make any sense." why?
because the continue statement is used to bypass the execution of below statements in the current iteration but in your case it's being used as the last statement.
it seems like what you want is if this condition is true --> if (str1Number == str2Number) then you don't want to execute any of the logic in the loop, in which case you can do:
for (int i = 0; i < str1Arr.length-1; i++){ // did you mean i < str1Arr.length ?
str1Number = Integer.valueOf(str1Arr[i]);
str2Number = Integer.valueOf(str2Arr[i]);
if (str1Number == str2Number) // <---- I've moved it to here
continue;
if (str1Number > str2Number) {
result = str1;
break;
} else {
result = str2;
break;
}
}
I've also removed the i++; that was inside the if block as I "assumed" it might have been a typo/mistake.

Since, continue operation itself tell to increase iteration variable - i, you don't need to increase it there. You may simply write:
else if (str1Number == str2Number){
continue;
}

The continue keyword just sends control up to the top of the loop (after executing the increment part of the for construct). The condition is still evaluated though, so it will only continue the loop if the loop condition is satisfied.
Probably, in your case, i < str1Arr.length-1 is false.

Judging from your method's name and its return value, all you want to find is the input string that has the lowest integer as its version identifier in it.
For that, below should suffice. No loops needed at all
public class Foo {
public static void main(String[] args) {
System.out.println(getOldestVersion("abc.12", "abc.14"));
}
public static String getOldestVersion(String v1, String v2) {
return parseInteger(v1) > parseInteger(v2) ? v2 : v1;
}
public static int parseInteger(String input) {
return Integer.valueOf(input.replaceAll("\\D", ""));
}
}
If your input string is something like 12.13.14.15, you could use
public class Foo {
public static void main(String[] args) {
System.out.println(getOldestVersion("12.18", "14.15"));
}
public static String getOldestVersion(String v1, String v2) {
return Stream.of(v1.split("\\.")).mapToInt(Integer::parseInt).min().orElse(Integer.MAX_VALUE) > Stream.of(v2.split("\\.")).mapToInt(Integer::parseInt).min().orElse(Integer.MAX_VALUE)
? v2 : v1;
}
public static int parseInteger(String input) {
return Integer.valueOf(input.replaceAll("\\D", ""));
}
}

Related

how to count many times a character occurs in a string without using s loop

the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");

Compile Errors Java: Boolean Array Method

getting compile errors and just cannot get this code to work the way I need it to, it's beginning to drive me mad! Basically I am trying to get my boolean array in my method to iterate through the array, find out if False is listed more consecutively or if True is and return either true or false. In my program the array i have listed should return false. Any ideas? thanks in advance.
public class trueOrfalse
{
public static void main(String [] args)
{
boolean[] guess = {false,true,false,false,false,true,true};
boolean result = longerTF(guess);
}
public static boolean longerTF(boolean[] guess)
{
int variable = 0;
for(int x = 0; x < guess.length; x++)
{
if(guess[x] > true)
{
return true;
}
else
{
return false;
}
}
}
i don't know where to start
first of all this is wrong
if(guess[x] > true)
it should be
if(guess[x]==true)
since an if statement expects a boolean result and you have boolean values in your array this will have the same effect
if(guess[x])
you also missed a case. when the array is empty you would never run into the for loop, but your method still needs to return a boolean value. you could throw a runtime-exception or a default value like return false; at the end of your method
your for-loop does not make sense, since your method will return a result within the first iteration (if the array is not empty). your longerTF method could be also looking like this
public static boolean longerTF(boolean[] guess) {
if(guess.length>0)
return guess[0];
throw new IllegalArgumentException("The array must not be empty");
}
i'd suggest a general book like "programming: Learn the Fundamentals of Computer Programming Languages". you need to understand first the basics of programming before you try to implement anything.
The comparison​ operators >, etc., are neither legal nor meaningful for boolean operands. What did you intend guess[x] > true to accomplish?
Since guess is a boolean[] you are allowed to test
if (guess[x])
or
if (! guess[x])
and to
return guess[x];
EDIT
You want the loop to count consecutive values. This loop does not, but it shows how such a structure works for a simpler problem.
public boolean dominant(boolean[] guess) {
int tCount = 0;
for (int ix = 0; ix < guess.length; ++ix) {
if (guess[ix]) {
++tCount;
}
}
return tCount >= guess.length / 2;
}
Here is a "corrected" version:
public class trueOrfalse {
public static void main(String[] args) {
boolean[] guess = { false, true, false, false, false, true, true };
boolean result = longerTF(guess);
}
public static boolean longerTF(boolean[] guess) {
int variable = 0;
for (int x = 0; x < guess.length; x++) {
if (guess[x]) {
variable++;
}
}
return (variable > (guess.length-variable));
}
}
You forgot one closing braket }, a return statement and boolean compare cannot be with < or >.
As mentioned by everyone above. You can't use > to compare two booleans.
For your purpose to count the number of consecutive true/false, you need two different counters. You can run a loop and keep incrementing the counter as you encounter repeated item of true/false, if not you can just reset the counter to 1. I have put on a hasty solution below to give you an idea. I haven't tested it well it seems to work. Hope this helps.
public class trueOrfalse {
public static void main(String[] args) {
boolean[] guess = { false,true,false,false,false,true,true };
boolean result = longerTF(guess);
System.out.println("result: " +result);
}
public static boolean longerTF(boolean[] guess) {
int consecutiveFalseCount = 1;
int consecutiveTrueCount = 1;
for (int x = 0; x < guess.length; x++) {
if (guess[x] == true) {
if(x!=0 && x<guess.length){
if(guess[x-1] == true){
consecutiveTrueCount = consecutiveTrueCount + 1;
} else {
consecutiveTrueCount = 1;
}
}
} else {
if(x!=0 && x<guess.length-1){
if(guess[x-1] == false){
consecutiveFalseCount = consecutiveFalseCount + 1;
} else {
consecutiveFalseCount = 1;
}
}
}
}
System.out.println("Consecutive True count: " +consecutiveTrueCount);
System.out.println("Consecutive False count: " +consecutiveFalseCount);
if(consecutiveTrueCount>consecutiveFalseCount){
return true;
} else {
return false;
}
}
}

For if loop in Java with array

Why does this code give me an error? I'm tyring to return the index of the first string in strArr that matches string s.
private String strArr[];
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
}
You are not initialising the array (therefore will get a NullPointerException when you try and get it's length)
You are not returning from the method if the string is not found
public class StringArrayIndex {
private String strArr[] = new String[]{"bar","foo", "cas"};
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
return -1;
}
public static void main(String[] args){
System.out.println(new StringArrayIndex().indexOf("foo"));
}
}
When submitting to Stack Overflow you should try to give more information (full code samples, error messages etc) so people can help you more easily.
You need to also return some value e.g. -1 after your loop.
Your return is in an IF statement so the Java compiler is
not sure you will ever enter this IF. And if you don't, you might
never return a value from your method. Therefore the compile-tome error.
You are not returning anything if you do not find the string in the array.
You should return something if the condition is never evaluated to true (outside your for loop for instance, you could return -1).
In your case, not all paths return a value.
because if your method need to return something, it should return in all cases:
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
return -1; //if not find
}
it should return if your condition never get satisfied.
public class MyIndexOf {
private String strArr[] = {"x", "y", "z"};
public int indexOf(String s) {
for (int i = 0; i < strArr.length; i++) {
if (strArr[i].equals(s)){
return i;
}
}
return -1;
}
public static void main(String[] args) {
MyIndexOf self = new MyIndexOf();
System.out.println(self.indexOf("x"));
}
}

Error in my Java code

I've got a problem with my Java program. There is an error in my code on line 16 (t = T[i];) which implies an error on line 12. It says :
Syntax error on token "=",VariableInitializer expected after this token.
Could I have some help ?
public class Ngrams {
public static boolean estPrefixe(String t, String s) {
int Longs = s.length();
if (t.substring(0, Longs) == s) {
return true;
} else {
return false;
}
}
public static int nbOccurences(String[] T, String s) {
int compteur = 0;
String t = null;
for (int i = 0; i < T.length; i++) {
t = T[i];
if (estPrefixe(t, s)) {
compteur++;
}
return compteur;
}
}
Notwithstanding the fact that you're comparing Strings with == instead of .equals(), and that a right bracket seems to have gone AWOL, at the end of your program, you're "missing" a return statement in nbOccurences. Even though you have one in the for-loop, if you never enter the loop, you don't return anything.
Move your return statement down one line, outside of the loop instead.
public static int nbOccurences(String[] T, String s) {
int compteur = 0;
String t = null;
for (int i = 0; i < T.length; i++) {
t = T[i];
if (estPrefixe(t, s)) {
compteur++;
}
}
return compteur;
}
The method nbOccurences does not always return an int value. If T is null or empty (length = 0) no value is returned. So you should add another return statement after the for loop.
As others mentioned already you should use equals to compare strings. This however, is not producing a syntax error.
Well there's a serious bug in this line:
if (t.substring(0, Longs) == s) {
This test will always be false, because == compares object references, not values. Change it to:
if (t.substring(0, Longs).equals(s)) {
But the whole method is pointless. Change it to:
public static boolean estPrefixe(String t, String s) {
return t.startsWith(s);
}
Or just delete the method altogether because it adds no value whatsoever.

Numbers Won't Increment

First my call back to increment I know is not correct. I am not sure what to do. I need increment to use temp when it hits that case that requires that call back. I can't change increment to pass a parameter into it because the graders test script wont allow for it. The second problem is that it wont increment any input. For instance if you just call increment on the number 23 it just returns 23. The test script for the grader looks something like this:
public class TestBigNaturalSimple {
public static void main(String[] args) {
BigNatural b1 = new BigNatural(); // default constructor
BigNatural b2 = new BigNatural(23); // one-argument int constructor
BigNatural b3 = new BigNatural("346"); // one-argument String constructor
BigNatural b4 = new BigNatural(b2); // one-argument BigNatural
// constructor
b1.increment();
b3.decrement();
System.out.println(b1.toString()); // should print out 1
System.out.println(b4.toString()); // should print out 23
}
}
My code is:
public class BigNatural {
private String num;
public BigNatural(String input) {
num = input;
}
public BigNatural(BigNatural input) {
num = input.toString();
}
public BigNatural(Integer input) {
num = input.toString();
}
public BigNatural() {
Integer i = 0;
num = i.toString();
}
public void increment() {
Integer first = 0;
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if (num.length() > 1)
{
if (last < 9) {
last++;
}
else
{
if (num.length() >= 2)
{
last = 0;
String temp = new String(num.substring(0, num.length()-2));
increment();
}
else
{
last++;
}
}
}
else
{
if (last < 9)
{
last++;
}
else
{
last = 0;
first = 1;
}
}
String t = last.toString();
if (first > 0)
{
String x = first.toString();
num.concat(x);
}
num.concat(t);
}
public void decrement() {
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if(num.length() > 1)
{
if(last == 0)
{
String temp = new String(num.substring(0, num.length()-2));
decrement();
}
else
{
last--;
}
}
else
{
if(last > 0)
{
last--;
}
else
{
last = 0;
}
}
String t = last.toString();
num.concat(t);
}
public String toString() {
return num;
}
}
That has to be the most complicated way to increment a number I have ever seen. ;) I assume you have to do it that way.
From what I can see you don't change num anywhere. I would expect this to be obvious if you used a debugger. ;)
Try using num = num.concat(t) if you expect num to change.
Note: String is immutable so you cannot change it, you can only replace it.
EDIT: Here is a version provided for your own interest. Your professor will know you didn't write this, so don't copy it. ;)
public void increment() {
num = increment(num);
}
private static String increment(String s) {
if (s.length() <= 0) return "1";
char ch = s.charAt(s.length() - 1);
String top = s.substring(0, s.length() - 1);
return ch < '9' ? top + ++ch : increment(top) + '0';
}
Strings are immutable in Java. Hence, the code
num.concat(t);
in your increment method will not do what you expect.
First, apply the rule don't repeat yourself:
to increment is to add 1
to decrement is to add -1
Thus you simply need to write on function that takes a number as input and add it to your BigNatural:
public void increment() {
add(1);
}
public void decrement() {
add(-1);
}
private void add(int i) {
// Your homework here ...
// You will have only one function to debug and correct, not 2
}
Second: as pointed in other answers, num.concat(t); does not do what you expect, you'll need num = num.concat(t);. Always refer to the Java documentation when you use a function you don't know. If you don't have an editor that allows you to debug your programs, I strongly suggest you get one: Eclipse for instance but other editors might be better as learning tool. The added benefit is that the tools will format the code for you, warn you about lots of mistakes, ...

Categories

Resources