Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 循环没有在应该结束时结束_Java - Fatal编程技术网

Java 循环没有在应该结束时结束

Java 循环没有在应该结束时结束,java,Java,当用户输入字符N或N时,我试图使循环结束,但当我运行程序时,循环不会正确结束。似乎答案的字符没有被循环本身读取,所以有人能帮我吗 import java.util.Scanner; public class Project4_Baker { public static void main(String[] args) { Scanner s = new Scanner(System.in); char answer; System.out.println("

当用户输入字符N或N时,我试图使循环结束,但当我运行程序时,循环不会正确结束。似乎答案的字符没有被循环本身读取,所以有人能帮我吗

import java.util.Scanner;

public class Project4_Baker
  {
  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    char answer;
    System.out.println("=============");
    System.out.println("Prime or Not?");
    System.out.println("=============");

    do
    {
        System.out.print("Enter a whole number ==>");
        int n = s.nextInt();

        System.out.println();

        if(isPrime(n))
        {
            System.out.println(n + " is a prime number.");
        }
        else
        {
        System.out.println(n + " is a composite number.");
        }

        System.out.println();

        System.out.print("Do another (Y/N)==>");
        answer = s.next().charAt(0);

    }while(answer != 'N'|| answer != 'n');

}

public static boolean isPrime(int n)
{
    if(n <= 1)
    {
        return false;
    }
    for (int i = 2; i < Math.sqrt(n); i++)
    {
        if (n%i==0)
        {
            return false;
        }
    }
    return true;
}
}
import java.util.Scanner;
公共类项目4
{
公共静态void main(字符串[]args)
{
扫描仪s=新的扫描仪(System.in);
答案;
System.out.println(“======================”);
System.out.println(“是否素数?”);
System.out.println(“======================”);
做
{
System.out.print(“输入整数==>”;
int n=s.nextInt();
System.out.println();
if(isPrime(n))
{
System.out.println(n+“是一个素数。”);
}
其他的
{
System.out.println(n+“是一个复合数。”);
}
System.out.println();
系统输出打印(“再做一次(Y/N)==>”;
答案=s.next().charAt(0);
}while(答案!=“N”|答案!=“N”);
}
公共静态布尔iPrime(int n)
{
如果(n尝试


您需要字符不等于'N'并且也不等于'N'

的情况,它应该是
while(answer!='N'&&answer!='N');
.With
while(answer!='N'| answer!='N'))
,如果有人输入
N
,它将继续,因为
answer
等于
N
,但它不等于
N

您试图在while-lopp语句中将字符串与字符进行比较。 将您的字符转换为int,并使用unicode表查找字符代码,例如n为110

在循环之前:

int a = 0;
a = (int)answer;
...(while a != 110 || ...)
在你的循环中:

int a = 0;
a = (int)answer;
...(while a != 110 || ...)

问题在于循环条件

while(answer != 'N' || answer != 'n')
上述条件始终为真

改用这个:

while(answer == 'Y' || answer == 'y')

编辑:忘了我的答案吧,它完全错了!字符是一个字符,字符串是多个字符。然后删除你的答案。的确。这是一个很容易导致严重错误的错误。