It would be helpful to keep track of values of i in a table.
public class ReviewOne { /** * The program illustrates arrays for a midterm review * Author: Elena Machkasova * What will be printed by the following program? */ public static void main(String[] args) { int [] data1 = {4, 7, 5, 8, 3}; int [] data2 = {1, 6, 9, 7, 3}; int [] result = new int[data1.length + data2.length]; for (int i = 0; i < data1.length; ++i) { result[2*i] = data1[i]; result[2*i + 1] = data2[i]; } printIntArray(result); } /** * * The method prints its argument <code>arr</code> * element by element on one line, separated by commas, * with [ before the first element and ] after the last one * */ public static void printIntArray(int [] arr) { System.out.print("["); for (int i = 0; i < arr.length; ++i) { System.out.print(arr[i]); if (i != arr.length - 1) System.out.print(", "); } System.out.println("]"); } }
Draw memory picture for all the object variables involved.
import java.util.Stack; public class Stacks { // What will be printed by the following program? public static void main(String [] args){ Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); Stack<Integer> stack3 = stack1; stack1.push(1); stack2.push(2); stack3.push(3); stack1.push(4); stack2.push(5); stack3.push(6); stack1.pop(); stack2.pop(); System.out.println("stack 1 = " + stack1); System.out.println("stack 2 = " + stack2); System.out.println("stack 3 = " + stack3); } }
The method has to work as described in comments. Useless operations are considered a mistake. Type safety violations are considered a mistake, even if the program compiles and runs.
public class CorrectMistakes {
// correct all mistakes in the following program:
public static void main(String [] args) {
int myarray = new int[10];
for (int i = 1; i <= arr.size(); ++i) {
myarray[i] = i - 1;
}
printIntArray(myarray);
replace(myarray);
printIntArray(myarray);
}
/**
* The method replaces all even elements n of the given array
* by n + 1.
* The elements remain in the original order
**/
public static int [] replaceEvens(int [] arr) {
for (j = 0; j < arr.length; ++j) {
if (arr[j] % 2 == 0) {
myarray[i] = arr[j] + 1;
}
}
return arr;
}
/**
*
* The method prints its argument arr
* element by element on one line, separated by commas,
* with [ before the first element and ] after the last one
*
*/
public static void printIntArray(int [] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; ++i) {
System.out.print(arr[i]);
if (i != arr.length - 1)
System.out.print(", ");
}
System.out.println("]");
}
}
Write and test a method that takes an array of strings and a stack
of strings and returns true if the contents of the array is the same as
that of the stack (the same strings in the same order) and false otherwise.
The bottom
of the stack corresponds to the first element of the array.
At the end of the method the stack must contain all of the initial elements
in the same order as before the method.