![](/img/trans.png)
[英]Creating an N by N grid of letters so that no two adjacent letters are the same
[英]If in a String adjacent letters occurring in the word are same then print “same” otherwise “diff”
我正在尝试,但有时输入4整数会给出错误的输出。 请更新我的代码或给我一些想法。 以下是我的示例输出。 和我正在尝试的代码。
输出示例:-
input:-
3
remember
occurring
apple
diff
Same
same
码:-
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");
}
}
您没有在每次运行之间将标志重置为初始值。 注意,我已经将标志更改为布尔值而不是整数,并且现在在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");
}
}
}
}
只需使用正则表达式即可:更短,更简单
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");
}
您的代码的问题是您永远不会重置标志。 如果情况相同,那么在程序的其余执行时间中,标记将保持为0。 因此,在第一个“相同”之后的所有情况也将产生“相同”。 为了解决这个简单的问题,请将您的flag = 0
代码移动到第一个while循环内。 就像这里的某个地方:
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....
那应该解决您的问题。 我希望这有帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.