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

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.

Related

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.

Odd character out given two strings

Beginner here -
I need to find the odd character out in a set of two strings. Everything compiles but when it goes to print out the odd character, it prints out the characters of the longer string..Does anyone know how i can fix it?
thanks
public class odd
{
public static void main(String[] args)
{
String str1;
String str2;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 2 words:");
str1 = keyboard.nextLine();
str2 = keyboard.nextLine();
int n1 = str1.length();
int n2 = str2.length();
int x1 = 0, x2 = 0;
if (Math.abs(n1-n2)==1)
{
if (n1 > n2)
{
x1 = n1;
x2 = n2;
}
if(n1 < n2)
{
x1 = n2;
x2 = n1;
String temp = str1;
str1 = str2;
str2 = str1;
}
}
else
{
System.out.print("Invalid input.");
}
for (int i=0; i < x1; i++)
{
for (int j = 0; j < x2; j++)
{
if(str1[i]==str2[j])
{
System.out.println("Extra letter is: " + str1[i]);
break;
}
}
}
}
}
if(str1[i]==str2[j])
{
System.out.println("Extra letter is: " + str1[i]);
break;
}
You're checking if the character matches, and then printing if it does, when your stated intention is the opposite: to check if they differ, and then print if that is the case. Change your == to != and you should get the desired result.
For the sake of clarity, == is the equal-to operator, and != is the not-equal operator.
For you program to work your first string minus second string must be equal to 1:
Math.abs(n1-n2)==1
Fix this piece of code, Hint: is it needed ?
#jjuutz Use below method to get the difference between two strings.
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
int at = indexOfDifference(str1, str2);
if (at == -1) {
return EMPTY;
}
return str2.substring(at);
}
public static int indexOfDifference(String str1, String str2) {
if (str1 == str2) {
return -1;
}
if (str1 == null || str2 == null) {
return 0;
}
int i;
for (i = 0; i < str1.length() && i < str2.length(); ++i) {
if (str1.charAt(i) != str2.charAt(i)) {
break;
}
}
if (i < str2.length() || i < str1.length()) {
return i;
}
return -1;
}

Java var from statement doesn't save

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;
}
}

Odd return on PEMDAS calculator

It seems that this calculator works for all other cases, except cases like this:
(2*3^4)
It does not return 162, instead, it returns 0.0.
I identified that the error must be from the method public static double operation, since the default return statement is 0.0
Here is the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StackC<Item> implements Stack<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
public StackC() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4)
resize(a.length/2);
return item;
}
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
return a[N-1];
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
public ReverseArrayIterator() {
i = N;
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
//---------------------------------------------------------------------
public static void main(String[] args) {
StackC<String> Operator = new StackC<String>();
StackC<Double> Values = new StackC<Double>();
while (!StdIn.isEmpty()) {
String token = StdIn.readString();
try {
Double x = Double.parseDouble(token);
Values.push(x);
}
catch(NumberFormatException nFE) {
}
if (token.equals("("))
Operator.push(token);
if (token.equals(")"))
{
if (Operator.peek() != "(")
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
Operator.pop();
}
if(token.equals("*") || token.equals("+") || token.equals("/") || token.equals("-") || token.equals("^") )
{
if(!Operator.isEmpty())
{
String prev = Operator.peek();
int x = comparePrecedence(token, Operator.peek()); // You need to compare precedence first
if(x == -1 || x == 0)
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
}
Operator.push(token);
}
}
while(!Operator.isEmpty())
{
String prev = Operator.peek();
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
System.out.println(Values.pop());
}
public static double operation(String operator, double a, double b) {
if (operator.equals("+"))
return a + b;
else if (operator.equals("-"))
return a - b;
else if (operator.equals("*"))
return a * b;
else if (operator.equals("/"))
return a / b;
else if (operator.equals("^"))
return Math.pow(a,b);
return 0.0;
}
public static int comparePrecedence(String x, String y)
{
int val1 = 0;
int val2 = 0;
if(x.equals("-"))
val1 = 0;
if(y.equals("-"))
val2 = 0;
if(x.equals("+"))
val1 = 1;
if(y.equals("+"))
val2 = 1;
if(x.equals("/"))
val1 = 2;
if(y.equals("/"))
val2 = 2;
if(x.equals("*"))
val1 = 3;
if(y.equals("*"))
val2 = 3;
if(x.equals("^"))
val1 = 4;
if(y.equals("^"))
val2 = 4;
if(val1 > val2)
return 1;
else if(val2 > val1)
return -1;
else
return 0;
}
}
Everything above the dotted line was given via the professor, and is not the problem for the code.
StdIn is simply a method that reads inputs.

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