这段代码出了什么问题? [英] What's wrong with this code ?

查看:107
本文介绍了这段代码出了什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在SPOJ上给出错误答案,但在ideone上运行完美(已经尝试了数百个测试用例)。



当我使用确切的逻辑和时使用C语言实现它然后它在SPOJ上完美运行。



ideone链接:www.ideone.com/MUVrrE

关于spoj的问题: www.spoj.com/problems/ONP/



This code is giving "wrong answer" on SPOJ but works perfectly on ideone (have tried hundreds of test cases).

When I use the exact logic and implement it using C language then it works perfectly on SPOJ.

ideone link : www.ideone.com/MUVrrE
Problem on spoj : www.spoj.com/problems/ONP/​

import java.io.*;
class abc
{
public static void main(String[] args) throws Exception
{
try{
    String x="",y="",str="";
    String [] A= new String[20];
    String op="";
    int i=0, j=0, k=0, ctr=0, n=0;
    BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    n=Integer.parseInt(br.readLine());
    for(i=0;i<n;i++)
        A[i] = br.readLine();
    for(k=0;k<n;k++)
        {
        str=A[k];
        for(i=0;i<str.length();i++)
            {
            if(str.charAt(i)=='(')
                {
                ctr++;
                for(j=i+1;j<str.length();j++)
                    {
                    if((str.charAt(j)=='+' || str.charAt(j)=='-' || str.charAt(j)=='*' || str.charAt(j)=='/' || str.charAt(j)=='^') && ctr==1)
                        {
                        op+=str.charAt(j);
                        x=str.substring(0,j);
                        y=str.substring(j+1);
                        str=x+y;
                        }
                    if(str.charAt(j)=='(')
                        ctr++;
                    if(str.charAt(j)==')')
                        ctr--;
                    if(ctr==0)
                        {
                        x= str.substring(0,j);
                        y= str.substring(j);
                        str= x+ op+ y;
                        op="";
                        break;
                        }
                    }
                }
                ctr=0; op="";
                }
            for(i=0;i<str.length();i++)
                {
                if(str.charAt(i)!=')' && str.charAt(i)!='(')
                    System.out.print(str.charAt(i));
                }
            if(k!=n-1)
                System.out.println();
            }
        }
    catch(Exception e)
        {
        return;
        }
    }
}

推荐答案

让我们猜测问题不在您的代码中。问题与外部行为有关。



解决方案:是时候学习调试器了。



使用调试器逐步运行程序,特别注意变量。

比较ideome和SPOJ的行为。



您应该很快发现错误。
Lets guess the problem is not in your code. The problem is linked to an external behaviour.

Solution: it's time to learn the debugger.

Run your program step by step with the debugger, pay special attention to variables.
Compare behaviour with ideome and SPOJ.

You should find pretty quickly what is wrong.


这篇关于这段代码出了什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆