简体   繁体   中英

If in a String adjacent letters occurring in the word are same then print “same” otherwise “diff”

I am trying but for sometime input 4 integer it will give wrong output . please update my code or give me some idea. Below is my sample output. and the code which i am trying.

Example output:-

input:-
3
remember
occurring
apple



diff
Same
same

Code:-

Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int flag=1;

int a=sc.nextInt();
for (int i = 0; i <a; i++) {

    System.out.println("enter a string");
    String s=sc.next();
    char [] sq=s.toCharArray();
    for (int j = 0; j < sq.length-1; j++) {
        if(sq[j]==sq[j+1]) {
            flag=0;
            break;
        }
    }

    if(flag==1) {
        System.out.println("diff");
    } else {
        System.out.println("same");
    }

}

you were not resetting your flag to the initial value between each run. Notice that I have changed your flag to a Boolean value rather then an integer and it now resets just before the System.out.println();

package test;

import java.util.Scanner;

public class test {

public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);
    System.out.println("enter a number");
    boolean flag=true;

    int a=sc.nextInt();
    for (int i = 0; i <a; i++) {

        flag=true;
        System.out.println("enter a string");
        String s=sc.next();
        char [] sq=s.toCharArray();

        for (int j = 0; j < sq.length-1; j++) 
        {

            if(sq[j]==sq[j+1])
            {
                flag=false;
                break;
            }
        }

        if(flag)
        {
            System.out.println("diff");
        }
        else
        {
            System.out.println("same");
        }

    }

}

}

Just use Regex: short and simpler

public static void main(String[] args) {
    String s = "dess";
    boolean match = s.matches(".*([A-Za-z])\\1+.*");

    if (match)
        System.out.println("same");
    else
        System.out.println("diff");
}

The problem with you code is that your never reset your flag. If you have a 'same' case then you flag will stay at 0 for the rest of the excution time of the program. And therefore all cases after the first 'same' will also yield 'same'. To solve this simple move your flag = 0 code to inside the first while loop. Like somewhere here:

for (int i = 0; i <a; i++) {
   flag = 1;//<-- reset your flag variable
   System.out.println("enter a string");
   String s=sc.next();
   char [] sq=s.toCharArray();
   for (int j = 0; j < sq.length-1; j++) 
   {
       etc....

That should solve your problem. I hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM