Tuesday 24 November 2015

cs java programs


Question 1:
Write the following method that retruns the maximum value in an ArrayList of Integers. The
methods returns null if the list is nul or the list size is 0.
public static Integer max(ArrayList<Integer> list)
Write a test program that prompts the user to enter a sequence of numbers ending with 0, and
invokes this method to return the largest number in the input.
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package week10s;
/**
*
* @author kishore
*/
import java.util.*;
public class ArrayListMax {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter the elements : ");
int temp;
do {
temp = input.nextInt();
if (temp != 0) {
list.add(temp);
}
} while (temp != 0);
System.out.println("Maximum number is " + max(list));
}
public static Integer max(ArrayList<Integer> list) {
if (list == null || list.isEmpty()) return null;
int max = list.get(0);
for (int i : list) {
if (i > max) {
max = i;
}
}
return max;

}
}
Output:
run:
Enter the elements : 76
6
5
3
0
Maximum number is 76

Question 2:
Write a program the meets the following requirements:
• Creates an array with 100 randomly chosen integers.
• Prompts the user to enter the index of the array, then displays the corresponding element value.
If the specified index is out of bounds, display the message Out of Bounds. ( Use try-catch
block)
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package week10s;
/**
*
* @author kishore
*/
import java.io.*;
public class RandomArray {
public static void main(String ar[]) throws NumberFormatException, IOException{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int arr[]=new int[100];
for(int i=0;i<arr.length;i++){
int randomnumber=(int) (Math.random()*100);
arr[i]=randomnumber;
}
for(int i=0;i<arr.length;i++){
System.out.println("Random Numbers are"+i+"="+ arr[i]);
}
System.out.println("Enter which index element do you want?");
for(int i=0;i<100;i++){
try{
int index=Integer.parseInt(br.readLine());
if(index>100){
System.out.println("Out of Bounds");
}
else{
System.out.println("Given Index Having Element "+arr[index]);

}
}catch(Exception e){
System.out.println("Please enter a valid number");
}
}
}
}
Output:
run:
Enter which index element do you want?
34
Given Index Having Element 71
123
Out of Bounds
101
Out of Bounds