&引用;“线程中的异常”;还有更多 import java.util.Scanner; 公共阶级权力{ 公共静态void main(字符串[]args){ 双x,prod=1; int n; 字符串s; 扫描仪输入=新扫描仪(System.in); System.out.print(“此程序打印x(x是实数)并提升到n的幂(n是整数)。\n”); 外环: while(true){ 系统输出打印(“输入x和n:”); x=输入.nextDouble(); n=input.nextInt(); 对于(inti=1;i

&引用;“线程中的异常”;还有更多 import java.util.Scanner; 公共阶级权力{ 公共静态void main(字符串[]args){ 双x,prod=1; int n; 字符串s; 扫描仪输入=新扫描仪(System.in); System.out.print(“此程序打印x(x是实数)并提升到n的幂(n是整数)。\n”); 外环: while(true){ 系统输出打印(“输入x和n:”); x=输入.nextDouble(); n=input.nextInt(); 对于(inti=1;i,java,Java,有两个问题。第一个问题是字符串可能为空,然后获取第一个字符将产生异常 import java.util.Scanner; public class Power1Eng { public static void main(String[] args) { double x, prod = 1; int n; String s; Scanner input = new Scanner(System.in); System.out.print("Thi

有两个问题。第一个问题是字符串可能为空,然后获取第一个字符将产生异常

import java.util.Scanner;

public class Power1Eng {

public static void main(String[] args) {

    double x, prod = 1;
    int n;
    String s;

    Scanner input = new Scanner(System.in);

    System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n");

    outer_loop:
    while (true) {
        System.out.print("Input x and n: ");
        x = input.nextDouble();
        n = input.nextInt();

        for (int i = 1; i <= n; i++) {
            prod *= x;
        }

        System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
        s = input.nextLine();

        if (s.charAt(0) == 'Y')
            continue;
        else if (s.charAt(0) == 'N')
            break;
        else {
            inner_loop:
            while (true) {
                System.out.print("Wrong input. Do you want to continue?(Y/N) ");
                s = input.nextLine();

                if (s.charAt(0) == 'Y')
                    continue outer_loop;
                else if (s.charAt(0) == 'N')
                    break outer_loop;
                else
                    continue inner_loop;
            }   
        }   
    }       
}

}
测试字符串的长度以查看是否至少有一个字符,或者只使用而不是
charAt

if (s.charAt(0) == 'Y')  // This will throw if is empty.

第二个问题是,您在第一次输入后输入了一个新行,而nextLine最多只能读取下一个新行字符。

您可以检查初始字符数,以确保所需的字符数正确。例如:

if (s.startsWith('Y'))
while(true)
{
//…一些代码。。。
如果(s.长度()<1)
{
继续;
}
//…一些代码。。。
}
这样,您甚至不必继续运行其余的代码,如果代码库更大,这将有助于优化性能。

您在控制台中看到的“红色文本”表示文本被发送到标准错误。在这种情况下,它表示您的程序已崩溃

您遇到的主要问题是这种逻辑:

while (true)
{
    // ... some code ...

    if (s.length() < 1)
    {
        continue;
    }

    // ... some code ...
}
System.out.print(“输入x和n:”);
x=输入.nextDouble();
n=input.nextInt();
对于(int i=1;i
System.out.print("Input x and n: ");
x = input.nextDouble();
n = input.nextInt();

for (int i = 1; i <= n; i++) {
    prod *= x;
}

System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
s = input.nextLine();