【问题标题】:i can't show the output to the user我无法向用户显示输出
【发布时间】:2015-10-31 19:32:00
【问题描述】:

我编写了这段代码,但每次我尝试通过 System.out.print 语句向用户显示输出时都会出错。

代码的目的是检查数组是否是“回文”。

import java.util.Scanner;
public class u {
public static void main(String[] args) {
    int [] arr = {1,2,3,4,3,2,1};
    int counter1 = 0,counter2 = arr.length-1;
    int x = arr.length/2;
    while (counter1 < x ) {
        if (arr[counter1] == arr [counter2]){
            counter1++;
            counter2--;
        } else {System.out.println(":("); break;}

    } 
    System.out.println("Bingo!");
  }}

【问题讨论】:

  • 您的System.out.print() 声明在哪里?您收到什么错误?
  • 我编辑了问题..你现在可以看到
  • 您的代码运行良好。它有什么问题?
  • 如果数组不是回文数组,它会给出错误的输出。
  • System.out.println("Bingo!");while 循环之外,所以它总是会被执行。我建议在循环之前声明一个boolean,设置为true。在您的else 块中,包含一个将其设置为false 的语句。然后,在循环之后,创建一个if 语句,如果该布尔变量设置为true,则仅打印"Bingo!"

标签: java arrays if-statement


【解决方案1】:

如果问题是程序总是打印“Bingo!”这是因为 break 只结束了 while 循环。还有“宾果!”行在while循环之外,所以它仍然会被调用。您可以通过将break 更改为return 来避免这种情况。你也可以使用标签:

x: {
   while(...) {
        ...
        else break x;
   }
   System.out.println("Bingo!");
}

【讨论】:

    【解决方案2】:
    import java.util.Scanner;
    public class u {
    public static void main(String[] args) {
    boolean d = false; 
    int [] arr = {2,9,3,4,4,3,9,2};
    int counter1 = 0,counter2 = arr.length-1;
    int x = arr.length/2;
    while (counter1 < x ) {
        d = false;
        if (arr[counter1] == arr [counter2]){
            counter1++;
            counter2--;
            d = true;
        } else break;
         }
    if (d)
    System.out.println("Bingo!");
    else System.out.println(":(");
    }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多