ansh
ansh

Reputation: 67

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

Input:-

agxgw
3
2 4
2 5
7 14

Output:-

Yes
No
Yes

I just answer with “Yes” or “No” using the following rule: I will just select two integers a and b, if the element at the position a is same as the element as position b in the non-ending chant. Answer Yes, otherwise say No.

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

Upvotes: 3

Views: 82

Answers (3)

chyoo CHENG
chyoo CHENG

Reputation: 720

you can rewrite part 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 index of Java's array starts with zero.

Upvotes: 0

Deepak
Deepak

Reputation: 1545

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

So just calculate the mod of of string length b1 and c1 and then compare if chars are same or not.

for example:

mod can be calculated with % operator.

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

now char m1 and m2 are smaller than stringlength of k so just compare if both are same or not.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

String#charAt is zero-index based, and the values in b1 and c1 assume it's one-index based.

Solution: decrease b1 and c1 before evaluating 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;

Upvotes: 2

Related Questions