【问题标题】:How to know what is the logical error?如何知道什么是逻辑错误?
【发布时间】:2016-09-22 22:45:56
【问题描述】:

编写了一个程序来查找以空格分隔的行中给出的单个整数的立方体。

这是程序。它有一些逻辑错误。它适用于输入为字符的任何情况。

class Cube{

    void process(){
        int i=0,sum=0,j;
        int cube;
        int ar[]=new int[100];
        Scanner scan=new Scanner(System.in);
        while(scan.hasNext()){
            if(scan.hasNextInt()){
               ar[i]=scan.nextInt();
               i++;
            }
            else{
                scan.next();
            }
        }     
        for(j=0;j<=i;j++){
            cube=ar[j]*ar[j]*ar[j];
            sum=sum+cube;
        }
        System.out.print(sum);
    }  
    public static void main(String args[]){
        Cube obj=new Cube();
        obj.process();
    }
}

输入通过在线编译器给出:1 2 3 4 5 或任意长度

【问题讨论】:

  • 你的输出是什么,你期望什么?
  • 您的实际问题的答案是debugging
  • @JohannisK 输入是通过在线编译器的输入面板给出的。我编译并得到了正确的输出。但是测试用例不能通过
  • 你可以使用 Netbeans。

标签: java arrays operators


【解决方案1】:

如果输入在单行中为1 2 3 4 5 ,您可以使用它将输入作为字符串,然后将其解析为字符串数组。

Scanner scan=new Scanner(System.in);
String line[] = scan.nextLine().split(" "); //split by space
for(int i=0;i<line.length;i++){
int val = Integer.parseInt(line[i]);
int cube = val*val*val;
}

【讨论】:

    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多