[英]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 . 我正在尝试,但有时输入4整数会给出错误的输出。 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();
注意,我已经将标志更改为布尔值而不是整数,并且现在在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.
如果情况相同,那么在程序的其余执行时间中,标记将保持为0。 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. 为了解决这个简单的问题,请将您的
flag = 0
代码移动到第一个while循环内。 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 :)
我希望这有帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.