Not getting the result I want in java using array and string?

Input: -

agxgw
3
2 4
2 5
7 14

      

Output: -

Yes
No
Yes

      

I simply answer "Yes" or "No" using the following rule: I will just choose two integers a and b if the element at position a is the same as the element as position b in the endless chant, Answer Yes, otherwise say not.

code:

import java.util.Scanner;

public class Gf {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);        
        String k=sc.next();
        int k1=k.length();
        int a=sc.nextInt();
        for (int i =0; i <a; i++) {
            int b=sc.nextInt();
            int b1=b%k1;
            int c=sc.nextInt();
            int c1=c%k1;
            if(k.charAt(b1)==k.charAt(c1)) {
                System.out.println("yes");
            } else {
                System.out.println("No");
            }
        }
    }
}

      

+3


source to share


3 answers


Once you get char b1 and c1. then you just need to find the weather symbols in the string k = "agxgw" at position b1 and c1 are the same or not. Now string k is small, but the integers b1 and c1 can be larger than the length.

So, just compute mod of string length b1 and c1 and then compare if characters are the same or not.

eg:



mod can be calculated using the% operator.

m1 = b1 % stringlength of k
m2 = c1 % stringlength ok k

      

now char m1 and m2 are less than string length k so just compare if both are the same or not.

0


source


String#charAt

is based on index zero, and the values ​​in b1

and c1

assume that it is based on one index.

Solution: reduce b1

and c1

before evaluation k#charAt

. Do this only if their values ​​are greater than zero.



int b=sc.nextInt();
int b1=b%k1;
int c=sc.nextInt();
int c1=c%k1;
b1 = b1 == 0 ? k1 - 1 : b1 - 1;
c1 = c1 == 0 ? k1 - 1 : c1 - 1;

      

+2


source


you can rewrite some of your code like this:

int b = sc.nextInt() - 1;
int b1 = b % k1;
int c = sc.nextInt() - 1;
int c1 = c % k1;

      

The reason is that the Java array index starts at zero.

0


source







All Articles