2017-02-22 41 views
-3

我正在尝试加拿大计算竞赛#2,但我的解决方案无法正常工作。它只会读取前几个字符(前三个我相信),只是结束循环,然后继续提供基于前三个字符的适当输出。 这是过去的纸:http://cemc.uwaterloo.ca/contests/computing/2015/stage%201/juniorEn.pdfCCC 2015解决方案?

我的代码

Scanner input = new Scanner(System.in); 
    String lines = input.next(); 
    char[] line = lines.toCharArray(); 
    int happy = 0; 
    int sad = 0; 

    int i = 0; 
    while(i < line.length) 
    {   
     if(line[i] == ':' && line[i+1] == '-') 
     { 
      if(line[i+2] == ')') 
       happy++; 
      else if(line[i+2] == '(') 
       sad++; 

      i+=3; 
     } 

     else i++; 

    } 

    if(happy == 0 && sad == 0) 
     System.out.print("none"); 
    else if(happy == sad) 
     System.out.print("unsure"); 
    else if(happy>sad) 
     System.out.print("happy"); 
    else if (sad>happy) 
     System.out.print("sad"); 
+2

'input.next'不会读取整行。它只读取空格分隔的单词。你可能想使用'input.nextLine'。 –

+1

即使解决了这个问题,答案中的错误也得到解决,您的代码将无法捕获像': - :-)'这样的输入。 –

+1

查看字符串'indexOf'函数,该函数在另一个字符串内搜索类似':-)'的子字符串,可以选择从字符串中的索引开始。 –

回答

1

认为与

while(i < line.length) 

如果i == line.length - 1

那么如果你

line[i+1] 

您将超出长度或阵列并获得OutOfBoundsException

相关问题