2011-10-28 50 views
-3
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; 
      } 
     } 
    }  
} 

} 

enter image description here“在线程异常”多

当我用刚刚next()方法上只有微不足道的逻辑错误,但是当我改变 next()方法nextLine()方法,这个错误显示。

我该如何解决这个问题?

回答

3

有两个问题。首先是你的字符串可能是空的,然后提取第一个字符会给出一个异常。

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

这两项测试中字符串的长度,看是否有至少一个字符,或者只是使用String.startsWith代替charAt

if (s.startsWith('Y')) 

的第二个问题是,你以后进入了一个新的生产线你的第一个输入,nextLine只能读取下一个新行字符。

0

您可以检查一个初始字符数,以确保您所期望的字符数是正确的。即:

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

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

    // ... some code ... 
} 

这样,你甚至不必继续运行的代码,如果代码库是较大的,将有助于优化性能的其余部分。

0

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

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

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(); 

假设用户输入是:

2.1 4(输入)

input.nextDouble()将采取2.1,在标准输入流上留下4(enter)
input.nextInt()将采取4,在标准输入流上留下(enter)
input.nextLine()将花费""(空字符串),最后从xn的初始用户输入中清除(enter)