【问题标题】:Can you have a boolean expression repeat in a while loop?你可以在while循环中重复一个布尔表达式吗?
【发布时间】:2019-05-13 01:50:35
【问题描述】:

我找到了一种方法可以让我的程序识别某事物是否是回文,但如果不是,程序就不会重复。

在我提供的代码之前,我已经实现了布尔部分。

最初是用 if 语句设置的,想用 while 替换,但是类似 while (!yespalin(potentialp)) 的东西也不起作用

Scanner scan = new Scanner(System.in);      
String potentialp;
System.out.println("Please enter a potential palindrome: ");
potentialp = scan.nextLine();

while (yespalin(potentialp))
{
    System.out.println("That string is a palindrome");  
}
while (!yespalin(potentialp))
    System.out.println("That string is not a palindrome, please enter another: ");  
    potentialp = scan.nextLine();
}   

如果不是回文,我希望程序重复

【问题讨论】:

    标签: java if-statement while-loop palindrome


    【解决方案1】:

    对于初学者,我发现您第二次缺少“{”。

    但是我不明白为什么你需要 2 个 while 循环。

    如果您逐行阅读代码,您就会理解为什么第一个循环是唯一打印“正确”行的循环。 但是,如果你输入了一个错误的回文,它永远不会进入第一个循环,因此不会打印出想要的句子。

    如果我没有记错,如果你输入正确的值,你想要 1 个循环将结束 看起来像这样:

    Scanner scan = new Scanner(System.in);      
    String potentialp;
    System.out.println("Please enter a potential palindrome: ");
    potentialp = scan.nextLine();
    
    while (!yespalin(potentialp)){
        System.out.println("That string is not a palindrome, please enter another: ");  
        potentialp = scan.nextLine();  
    }
    System.out.println("That string is a palindrome"); 
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-12
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多