Java var from statement doesn't save - java

I can't save var stop so it can stop for cycle. I just need when tryOpen is true to exit that method and stop doing recursion.
public void moznosti(char [] arr, String pr, int a, int b) {
boolean stop = false;
if (b == 0) {
char [] heslo = pr.toCharArray();
for (int i = 0; i < heslo.length; i++) {
System.out.print(heslo[i]);
}
System.out.println();
if (tryOpen(heslo)) {
stop = true;
System.out.println("END");
}
return;
}
if (stop == false) {
for (int i = 0; i < a; i++) {
String tmp = pr+arr[i];
moznosti(arr, tmp, a, b-1);
}
}
}

Stop is a local variable here. If you make it a static global variable it will work, but note that you will have to set it to false before every time you call moznosti.
The above will work, but it isn't that good of a practice.
The best method would be to make your function return true when it succeeds. Then you can check success before making any more recursive calls:
if (b == 0) {
char[] heslo = pr.toCharArray();
for (int i = 0; i < heslo.length; i++) {
System.out.print(heslo[i]);
}
System.out.println();
if (tryOpen(heslo)) {
System.out.println("END");
} else {
for (int i = 0; i < a; i++) {
String tmp = pr + arr[i];
if (moz(arr, tmp, a, b - 1)) {
return true;
}
}
}
}

Thanks for help, this is what I did now it's working but it is slow...
public boolean moznosti(char [] arr, String pr, int a, int b) {
if (b == 0) {
char [] heslo = pr.toCharArray();
if(tryOpen(heslo)) {
return false;
}
return true;
}
for (int i = 0; i < a; i++) {
String tmp = pr+arr[i];
if (moznosti(arr, tmp, a, b-1) == false) {
return false;
}
moznosti(arr, tmp, a, b-1);
}
return true;
}
}

Related

How to make this method only have 1 return statement instead of 2

My professor has a rule that "there should be no more than one return statement in any method". Now I've written a pretty simple method in my first project. How would I make this have only return statement without ruining functionality?
public static int find(int correctNumber, int numArray[], int lastNum) {
for (int i = 0; i < lastNum; i++) {
if (numArray[i] == correctNumber) {
return i;
}
}
return -1;
Use another variable to assign the value and then apply a break within the if clause to exit the loop.
public static int find(int correctNumber, int numArray[], int lastNum) {
int returnValue = -1;
for (int i = 0; i < lastNum; i++) {
if (numArray[i] == correctNumber) {
returnValue = i;
break;
}
}
return returnValue;
}
And you will find that many professional programmers with lots of experience find it perfectly acceptable to use multiple return statements.
For example: This is the equals override from the JDK HashMap source. That code was written by four internationally recognized computer scientists, three of which have their PhD's.
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
like this?
public static int find(int correctNumber, int numArray[], int lastNum) {
int correctIndex = -1;
for (int i = 0; i < lastNum; i++) {
if (numArray[i] == correctNumber) {
correctIndex = i;
}
}
return correctIndex;
you can try this:
public static int find(int correctNumber, int numArray[], int lastNum) {
int temNum = -1;
for (int i = 0; i < lastNum; i++) {
if (numArray[i] == correctNumber) {
temNum = i;
break;
}
}
return temNum;
}
public static int find(int correctNumber, int numArray[], int lastNum) {
int i = lastNum - 1;
while (i >= 0 && numArray[i] != correctNumber) {
i--;
}
return i;
}
This differs slightly from your code in that, if the 'correctNumber' occurs twice, it will find the higher-index instance.
It could be expressed with a for-loop but I find I prefer the while-loop.
public static int find(int correctNumber, int numArray[], int lastNum) {
int i;
for (i = lastNum-1; i >= 0 && numArray[i] != correctNumber; i--) {
}
return i;
}

Im receiving a String index out of range question for a java program i wrote for my assignment

I would like to apologise in advance if im doing something wrong with the code formatting because this is my second time posting here
I have a java assignment due in a couple of days in which the user enters a string and only the integers are collected from it and placed in the array intArray
Now i think i got the logic right in the code below but when i run it in the main, it asks for the string and the boolean, when i enter both it gives me the error
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115"
This is what i entered for example
"Enter a string and true if you want to skip errors or false if you want to skip errors
sdak23
false"
this is my main:
import java.util.Scanner;
public class MainStringToIntArray {
public static void main(String[] args) {
Scanner intut = new Scanner(System.in);
Scanner input = new Scanner(System.in);
StringToIntArray s1 = new StringToIntArray();
System.out.println("Enter a string and true if you want to skip errors or false if you want to skip errors");
s1.scanStringToIntArray(intut.next(), input.nextBoolean());
}
}
import java.util.Arrays;
import java.util.Scanner;
public class StringToIntArray {
private int[] intArray = new int[10];
public StringToIntArray() {
Arrays.fill(intArray, Integer.MIN_VALUE);
}
public int indexOf(int intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == intToFind) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public int indexOf(String intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == Integer.parseInt(intToFind)) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public boolean contains(int intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public boolean contains(String intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public int get(int index) {
if(index < 0 && index > 10) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
public boolean scanStringToIntArray(String s, Boolean skipErrors) {
Boolean result = null;
Scanner input = new Scanner(s);
int l = s.length();
if ((skipErrors)) {
String discard = null;
for (int a = 0; a < l; a++) {
for (int z = 0; z < l; z++) {
if (input.hasNextInt(s.charAt(z))) {
intArray[a] = s.charAt(z);
System.out.println(a);
result = true;
}
else {
discard = discard + s.charAt(z);
}
}
}
}
else {
for (int v = 0; v < l; v++) {
for (int p = 0; p < l; p++) {
if ((input.hasNextInt(s.charAt(p)))) {
intArray[v] = s.charAt(p);
System.out.println(v);
}
else {
System.out.println(v);
result = false;
}
}
}
}
return result;
}
}
The issue is in the get method. It is logically impossible for the index to be both less than 0 and greater than 10; you probably want to use the logical or operator (||). Also, the maximum index of the array is actually 9, as arrays are zero indexed.
public int get(int index) {
if(index < 0 || index > 9) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
There are other logical errors in your code as well. All your indexOf methods should be returning the index where the element was first found instead of the element itself and your else branch is always resetting it to -1 each time it is not found.

Monotonic Functions in Java of Comparables

I am trying to implement an algorithm that checks if an array of comparable elements is increasing or decreasing. So far I have written this method:
class Solution {
public boolean isMonotonic(int[] A) {
int store = 0;
for (int i = 0; i < A.length - 1; ++i) {
int c = Integer.compare(A[i], A[i+1]);
if (c != 0) {
if (c != store && store != 0)
return false;
store = c;
}
}
return true;
}
}
I changed the method signature, by passing a generic method of comparables, but I'm struggling to implement the compareTo method. I am probably using the bounded generics wrong, but I'm not too sure?
My attempt:
public boolean Test(T[] n)
{
if (n.length < 3)
return true;
int direction = n[0].compareTo(n[1]);
for (int i = 1; i < n.length-1; i++){
int step = n[i].compareTo(n[i+1]);
if (step == 0)
continue;
if (direction == 0)
direction = step;
else if ( sdtep < 0 && direction > 0
|| step > 0 && direction < 0)
return false;
}
return true;
}
In order to make your method take a generic argument, change its header:
public static <T extends Comparable<? super T>> boolean isMonotonic(T[] A)
You can then compare items of the array using the Comparable::compareTo method:
int c = A[i].compareTo(A[i+1]);
Monotone function:
public static boolean isMonotone(int[] a) {
boolean monotone = true;
int i=0;
while(a[i]==a[i+1]) {
i++;
}
if(a[i]>a[i+1]) {
for(int j=0;j<(a.length-1);j++) {
if(!(a[j]>=a[j+1])){
monotone=false;
}
}
}
if(a[i]<a[i+1]) {
for(int j=0;j<(a.length-1);j++) {
if(!(a[j]<=a[j+1])){
monotone=false;
}
}
}
return monotone;
}
Strictly monotone function:
public static boolean isMonotone(int[] a) {
boolean monotone = true;
if(a[0]>a[1]) {
for(int i=0;i<(a.length-1);i++) {
if(!(a[i]>a[i+1])){
monotone=false;
}
}
}
if(a[0]<a[1]) {
for(int i=0;i<(a.length-1);i++) {
if(!(a[i]<a[i+1])){
monotone=false;
}
}
}
if(a[0]==a[1]) return false;
return monotone;
}

Compares two strings lexicographically using charAt() and without using compareTo() method

if the first string is lexicographically greater than the second string it should return 1,if equal return 0,else -1.It is return 1,-1,0 correctly for some cases,but for this str1 and str2 the return is coming out to be the opposite of the desired output.
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]) {
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1, testcase2);
System.out.println("Result : " + result);
}
// write your code here
public int newCompare(String str1, String str2) {
int l1 = str1.length();
int l2 = str2.length();
int max = 0;
if (l1 <= l2) {
max = l1;
}
else
max = l2;
int count = 0;
for (int i = 0; i < max; i++) {
char ch1 = str1.charAt(i);
char ch2 = str2.charAt(i);
if (str2.charAt(i) > str1.charAt(i)) {
return - 1;
}
if (str1.charAt(i) > str2.charAt(i)) {
return 1;
}
if (l1 == l2) {
if (ch1 == ch2) {
count++;
}
if (count == max) {
return 0;
}
}
}
if (l1 == l2) return 0;
if (l1 > l2)
return 1;
else
return - 1;
}
}
Here's a simplified answer
public class TestStrings {
public static void main(String[] args) {
System.out.println(compare("Mike", "Mike")); // returns 0
System.out.println(compare("Mikee", "Mike")); // returns 1
System.out.println(compare("Mike", "Mikee")); // returns -1
}
public static int compare(String s1, String s2) {
for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 > c2) {
return 1;
} else if (c2 > c1) {
return -1;
}
}
if (s2.length() > s1.length()) {
return -1;
} else if (s1.length() > s2.length()){
return 1;
} else {
return 0;
}
}
}
I used a loop, with the stopping condition as the length of the shortest word. If the words are equal after the length of the shortest word, then the longer word is automatically larger. That's what the if statement at the bottom is for.
you can try:
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]){
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public int newCompare(String str1, String str2){
int l1=str1.length();
int l2=str2.length();
int max=0;
if(l1<=l2)
{
max =l1;
}
else
max=l2;
int count=0;
for (int i =0;i<max;i++) {
char ch1=str1.charAt(i);
char ch2=str2.charAt(i);
if(str2.charAt(i)>str1.charAt(i))
{
return -1;
}
if(str1.charAt(i)>str2.charAt(i))
{
return 1;
}
}
if(l1==l2)
{
return 0;
}else if (l1 < l2){
return -1;
}else{
return 1;
}
}
In this case where String testcase1 = "helloworld" and String testcase2= "hellojavaworld"
your for loop will run from char 'h' to char 'o'(i=0 to i=4) and none of the if conditions inside your for loop will be satisfied and as soon as i gets incremented to 5
//str1.charAt(i)='w' and str2.charAt(i)=j
if(str1.charAt(i)>str2.charAt(i)) //w(ASCII=119) > j(ASCII=106)
{
return 1; //return 1 and control return to the calling function
}
So result=1. Or in short your code is working properly.
You can specify what you want the output to be.

How to know if a given string is substring from another string in Java

Hi
I have to compute if a given string is substring of a bigger string.
For example
String str = "Hallo my world";
String substr = "my"
The method "contains" should return true because str contains substr (false otherwise).
I was looking for something like "contains" at the String class
but I didn't find it. I suppose that the only solution is to use
pattern matching. If this is the case which would be the better (cheapest) way
to do this?
Thanks!
There is a contains() method! It was introduced in Java 1.5. If you are using an earlier version, then it's easy to replace it with this:
str.indexOf(substr) != -1
String str="hello world";
System.out.println(str.contains("world"));//true
System.out.println(str.contains("world1"));//false
Javadoc
String s = "AJAYkumarReddy";
String sub = "kumar";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == sub.charAt(count)) {
count++;
} else {
count = 0;
}
if (count == sub.length()) {
System.out.println("Sub String");
return;
}
}
use indexOf it will return -1 if no match (contains was added in 1.5, maybe you are using older jdk?) see "contains(CharSequence s)" method in String class in JDK 1.4.2 for details
if (str.indexOf(substr) >= 0) {
// do something
}
I think there is a String function that does just what you are asking: String.indexOf(String).
See this link: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
So, then you could write this function:
public boolean isSubstring(String super, String sub) {
return super.indexOf(sub) >= 0;
}
String.indexOf(substr) complexity is O(n2).. Luixv asked a cheaper solution.. But as far as , I know there is no better algorithm than current one.
public boolean isSubString(String smallStr, String largerStr) {
char[] larger = largerStr.toCharArray();
char[] smaller = smallStr.toCharArray();
int i = 0;
for (int j = 0; j < larger.length; j++) {
if(larger[j] == smaller[i]){
if(i == smaller.length -1){
//done we found that this string is substring
return true;
}
i++;
continue;
}else{
if(i > 0){
//that means we encountered a duplicate character before and if string was substring
// it shouldn't have hit this condition..
if(larger.length - j >= smaller.length){
i = 0;
//reset i here because there are still more characters to check for substring..
}else{
//we don't have enough characters to check for substring.. so done..
return false;
}
}
}
}
return false;
}
here is a general method that you can use
public static boolean isSubstring(String s1, String s2) {
if(s1.length() == s2.length())
return s1.equals(s2);
else if(s1.length() > s2.length())
return s1.contains(s2);
else
return s2.contains(s1);
}
public static boolean isSubstring(String s1, String s2){
if(s1.length()<s2.length()) return false;
if(s1.length()==s2.length()) return s1.equals(s2);
for(int i=0;i<=s1.length()-s2.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
int matchLength=1;
for(int j=1;j<s2.length();j++){
if(s1.charAt(i+j)!=s2.charAt(j)){
break;
}
matchLength++;
}
if(matchLength==s2.length()) return true;
}
}
return false;
}
This checks if s2 is a substring of s1.
You can use .substring(int beginIndex,int lastIndex) to check this program. Sample code goes as below:-
public class Test {
public static void main(final String[] args) {
System.out.println("Enter the first String");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String s1 = br.readLine();
System.out.println("Enter the second String");
String s2 = br.readLine();
boolean result = isSubStr(s1, s2);
if (result == true)
System.out.println("The second String is substring of the first String");
else
System.out.println("The second String is not a substring of the first String");
} catch (IOException e) {
System.out.println("Exception Caught: " + e);
}
}
public static boolean isSubStr(String st1, String s2) {
boolean result = false;
String tem_str = "";
int len1 = st1.length();
int i = 0;
int j;
while (i < len1) {
j = i+1;
while (j <=len1) {
tem_str = st1.substring(i, j);
if (tem_str.equalsIgnoreCase(s2)) {
result = true;
break;
}
j++;
}
i++;
}
return result;
}
}
Go through this method.
visit for tricky code
public static boolean isSubString(String s, String sub) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == sub.charAt(count)) {
count++;
} else {
i-=count;
count = 0;
}
if (count == sub.length()) {
return true;
}
}
return false;
}
Consider the following code:
If substring is present then it returns the start index of substring in a given string
Else returns -1
public static int isSubstring(String str, String pattern)
{
int str_length = str.length();
int pattern_length = pattern.length();
for (int i = 0; i <= str_length - pattern_length; i++)
{
int j;
for (j = 0; j < pattern_length; j++)
if (str.charAt(i + j) != pattern.charAt(j))
break;
if (j == pattern_length)
return i;
}
return -1;
}
String str1 = "Java8 makes Java more powerful";
String str2 = "Java";
char c;
char d;
int count=0;
boolean match = true;
for (int i = 0; i < str1.length(); i++) {
c = str1.charAt(i);
for (int j = 0; j < str2.length(); j++) {
d = str2.charAt(j);
if (c == d) {
match = true;
count++;
if(count== str2.length()){
i = str1.length();
break;
}
i++;
c = str1.charAt(i);
} else {
match = false;
}
}
}
if(match == true){
System.out.println("SubString ");
}
public class StringIsSubString {
public static void main(String[] args) {
String s1 = "wel";
String s2 = "12wlecome123";
boolean isSubStr = isSubStr(s1,s2);
System.out.println(isSubStr);
}
private static boolean isSubStr(String s1, String s2) {
String s3 = "";
int j = 0;
if(s1.length() > s2.length()) {
return false;
} else if(s1.equals(s2)){
return true;
} else {
for(int i=0; i<s1.length();i++) {
for(; j<s2.length();j++) {
if(s1.charAt(i) == s2.charAt(j)) {
s3 = s3 + s1.charAt(i);
break;
}
}
}
if(s3.equals(s1)) {
return true;
}
return false;
}
}
}
*In their any sub string will be count by the form of 1th place of string of substring *
int isSubstring(string s1, string s2) {
int M = s1.length();
int N = s2.length();
for (int i = 0; i <= N - M; i++) {
int j;
for (j = 0; j < M; j++)
if (s2[i + j] != s1[j])
break;
if (j == M)
return i;
}
return -1;
}
int main() {
string s1 = "kumar";
string s2 = "abhimanyukumarroy";
int res = isSubstring(s1, s2);
if (res == -1)
cout << "Not present";
else
cout << "Present at index " << res;
return 0;
}

Categories