Programming Homework Help

CISC 1115 CUNY BMCC How to Generate Random Numbers in Java Questions

 

1. a. Correct the following code so that it generates 50 random integers in the range of 30 up to and including 110 and stores the numbers in array r. Correct all errors.

int [ ] r = new int[49];

for (int i=0; i<r.length+1;i++){

r[i] = 10+Math.random()*100;

}


b. The following code checks if two characters next to each other in a String str are the same. If a match is found, it prints a message as shown below. Find all errors and correct them so the output for the String str in the example is

7 has a match

j has a match

String str = “ghu7763459823jj”;

for (int i=1; i<=str.length()-1; i–)

{ if (str.charAt(i-1) == str.charAt(i))

System.out.println(str.charAt(i-1)+” has a match”);

}


2. For the following array, you are to perform a binary search:

int nums[ ] = {1, 13, 78, 89, 96, 100, 112, 125, 230, 310, 423, 578, 1000};

Search for the number 126 by showing the low, midpoint and high values at each step before it reports that 126 is NOT found in the array.

Low

Mid

High

3. 1.Trace the following three sections of code in the tables below. When the name of an array is given in the trace chart, show the values of all elements of the array

public class Test2 {

public static void main(String[ ] args) {

//PART A

int[ ] arr = {10,20,30};

int num=changeIt(arr[1]);

//PART B

int[] arr1 = {10,20,30};

changeOne(arr1,1);

//PART C

int[] arr2 = {10,20,30};

int[] newArr = changeTwo(arr2);

} // end main

static int changeIt(int n) { n = n*50; return n;}

static void changeOne(int[ ] arr, int ndx) { arr[ndx]= arr[ndx]*4; }

static int[] changeTwo(int[ ] arr){

for (int i=0; i<arr.length; i++) arr[i]= arr[i]*5;

return arr;

}

} // end class

PART A

arr in main before invoke changeIt

n in changeIt right before return

num after invoke changeIt

arr after invoke changeIt

PART B

arr1 in main before invoke changeOne

arr in changeOne after the assignment

arr1 in main after invoke changeOne

PART C

arr2 in main before invoke changeTwo

arr in changeTwo after loop ends

newArr after invoke changeTwo

arr2 after invoke changeTwo

4. Given the following String source = “12dcxvlobcQakijkflobcPQ987”;

use the String methods indexOf, substring, and lastIndexOf (together with any other Java code except charAt) to:

a. Write Java code to count how many times a specific String str appears in source. For example, how many times lob appears. Write generic code for String str, not lob.

b. Write Java code to extract a String search from the String source. For example, extract the string Qak. Write generic code for search, not Qak.

5. 1.Given an amount of change in cents as an integer (say 92), write Java code to compute how many half dollars, quarters, dimes, nickels and pennies it consists of.

For example, 92 cents would be 1 half dollar, 1 quarter, 1 dime, 1 nickels and 2 pennies