Click here to Skip to main content
15,923,087 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
there two codes and the answers are both runtime error, could you explain me what are the hints which would tell us that the answer is a runtime error

a- what is What does the following method return when the input array is{ 1, 2, 3 }?

Java
public static int mystery(int[] array) {
 int i = 0;
 int count = 0;
 while (i <= array.length) {
 if (array[i] %2 == 0) { 
count++;
}
 i++;
} 
return count;
}



the second one is :What String does the following code return if the input to the method is the String with contents ABCDE.

Java
public static String mystery(String input) { 
String tricky = ""; 
for (int i = 0; i < input.length(); i++) { 
tricky = tricky + input.charAt(i); 
i++; 
tricky = tricky + input.charAt(i);
} 
return tricky;
}


What I have tried:

(nothing)
Posted
Updated 5-Apr-18 7:53am
v4

a) You know, array indices are zero-based (see, for instance Java Arrays[^]).

b) This is a beautiful example of ugly code. The lesson is: never mess up with with loop variables.
 
Share this answer
 
v2
Quote:
what are the hints which would tell us that the answer is a runtime error

Knowing how each and every statement really works and "running" each line of code in your head.

That's about the only useful hint you can get on an assignment like this.
 
Share this answer
 
Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
C++
public static int mystery(int[] array) {
  int i = 0;
  int count = 0;
  while (i <= array.length) {
    if (array[i] %2 == 0) {
      count++;
    }
    i++;
  }
  return count;
}


public static String mystery(String input) {
  String tricky = "";
  for (int i = 0; i < input.length(); i++) {
    tricky = tricky + input.charAt(i);
    i++;
    tricky = tricky + input.charAt(i);
  }
  return tricky;
}

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900