100% found this document useful (1 vote)
143 views30 pages

Assignment 2

This document contains the solutions to 12 questions on Java programming assignments submitted by a student named Ishant Goyal from the National Institute of Technology Kurukshetra. The solutions include programs to calculate e to the power of a number, move all zeros to the end of an array, find the k largest elements in an array, check if a number is a palindrome, check if an array contains three increasing adjacent numbers, count numbers in a range divisible by a given number, check if one string contains another, compare strings lexicographically, check if a string contains a sequence of characters, trim whitespace from a string, check if an array contains 25 as the first or last element, and count occurrences of even numbers entered within a range

Uploaded by

Nishant Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
143 views30 pages

Assignment 2

This document contains the solutions to 12 questions on Java programming assignments submitted by a student named Ishant Goyal from the National Institute of Technology Kurukshetra. The solutions include programs to calculate e to the power of a number, move all zeros to the end of an array, find the k largest elements in an array, check if a number is a palindrome, check if an array contains three increasing adjacent numbers, count numbers in a range divisible by a given number, check if one string contains another, compare strings lexicographically, check if a string contains a sequence of characters, trim whitespace from a string, check if an array contains 25 as the first or last element, and count occurrences of even numbers entered within a range

Uploaded by

Nishant Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

NATIONAL INSTITUTE OF TECHNOLOGY

KURUKSHETRA

Academic Year:2020-21
Department : Computer Engineering
Course : Java Programming
Tutorial Assignment 2
Name: Ishant Goyal
Class : CS-3
Roll no.: 11912041
Ques 1. Write a program that reads an integer value and prints the value e raised
to the power of that number.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the integer");
int power=input.nextInt();
System.out.println("e raised to power "+power+"(e^"+power+") equals
"+Math.exp(power));
}
}

Output:

Ques 2. Write a Java program that reads an array of integers and then moves
every zero to the right side i.e. towards the end.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the number of elements");
int num=input.nextInt();
int[] arr=new int[num];
System.out.println("Enter the "+num+" elements of array");
for(int i=0;i<arr.length;i++){
arr[i]=input.nextInt();
}
int end=arr.length-1;
for(int i=0;i<arr.length && i<end;){
if(arr[i]==0){
int temp=arr[i];
arr[i]=arr[end];
arr[end]=temp;
end--;
}
if(arr[i]!=0){
i++;
}
}
System.out.println("After processing, array is:");
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}

Output:
Ques 3. Write a Java program to find the k (for given k) largest elements in a
given array. Elements in the array can be in any order. Don’t forget to check
boundary condition for k.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the number of elements");
int num=input.nextInt();
int[] arr=new int[num];
System.out.println("Enter the "+num+" elements of array");
for(int i=0;i<arr.length;i++){
arr[i]=input.nextInt();
}
System.out.println("Enter the value of k");
int k=input.nextInt();
if(k<=0 && k>arr.length){
System.out.println("Value of k you enter is invalid");
System.exit(0);
}
System.out.println(k+" largest elements in the array are:");
for(int i=0;i<k;i++){
int max=i;
for(int j=i+1;j<arr.length;j++){
if(arr[j]>arr[max]){
max=j;
}
}
swap(arr,i,max);
System.out.print(arr[i]+" ");
}
}
public static void swap(int[] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
Output:
Ques 4. Write a Java program to check if a given positive number is a
palindrome or not.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the positive number");
int num=input.nextInt();
if(num<0){
System.out.println("The entered number is not a positive integer");
System.exit(0);
}
String numString=num+"";
int l=numString.length();
boolean ans=true;
for(int i=0;i<l/2 && ans==true ;i++){
if(numString.charAt(i)!=numString.charAt(l-1-i)){
ans=false;
}
}
if(ans==true){
System.out.println("The entered positive number is a palindrome");
}
else{
System.out.println("The entered positive number is not a palindrome");
}
}
}

Output:
Ques 5. Write a Java program to check if an array of integers contains three
increasing adjacent numbers.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the number of elements");
int num=input.nextInt();
int[] arr=new int[num];
System.out.println("Enter the "+num+" elements of array");
for(int i=0;i<arr.length;i++){
arr[i]=input.nextInt();
}
boolean ans=true;
for(int i=0;i<arr.length-2;i++){
if(arr[i+1]>arr[i] && arr[i+2]>arr[i+1]){
break;
}
else{
ans=false;
}
}
if(ans==true){
System.out.println("Yes, this array contains 3 increasing adjacent
numbers");
}
else{
System.out.println("No, this array doesn't contains 3 increasing adjacent
numbers");
}
}
}

Output:
Ques 6. Write a Java program to find the number of integers within the range of
two specified numbers x & y and that are divisible by another number, p.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the range of numbers");
int start=input.nextInt();
int end=input.nextInt();
if(start>=end){
System.out.println("Values entered are not correct");
System.exit(0);
}
System.out.println("Enter the value of p");
int p=input.nextInt();
int count=0;
for(int i=start+1;i<end;i++){
if(i%p==0){
count++;
}
}
System.out.println("Number of integers between "+start+" and "+end+"
divisible by "+p+" = "+count);
}
}
Output:

Ques 7. Write a Java program to accept two strings and test if the second string
contains the first one.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the child string");
String child=input.nextLine();
System.out.println("Enter the parent string");
String parent=input.nextLine();
if(parent.contains(child)){
System.out.println("Second string contains the first string");
}
else{
System.out.println("Second string doesn't contains first string");
}
}
}
Output:

Ques 8. Write a Java program to read two strings from keyboard and compare
them lexicographically.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter first string");
String str1=input.nextLine();
System.out.println("Enter second string");
String str2=input.nextLine();
System.out.println("After comparing lexicographically,answer is :
"+str1.compareTo(str2));
}
}

Output:

Ques 9. Write a Java program to test if a given string contains the specified
sequence of char values.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter first string");
String str1=input.nextLine();
System.out.println("Enter sequence of char values to be tested");
String str2=input.nextLine();
System.out.println("Sequence of char values is "+
(str1.contains(str2)?"":"not")+" contained in String");
}
}
Output:

Ques 10. Write a Java program to trim any leading or trailing whitespace from a
given string.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the string");
String str=input.nextLine();
System.out.println("After Trimming any leading or trailing whitespace :
"+str.trim());
}
}

Output:

Ques 11. Write a Java program to test in array of integers of length at least 3, if
25 appears as either the first or last element of the array.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the number of elements in array(Min:3)");
int n=input.nextInt();
if(n<3){
System.out.println("Enter atleast 3");
System.exit(0);
}
int[] arr=new int[n];
System.out.println("Enter the elements of array");
for(int i=0;i<arr.length;i++){
arr[i]=input.nextInt();
}
if(arr[0]==25 || arr[arr.length-1]==25){
System.out.println("Test : Pass");
}
else{
System.out.println("Test : Fail");
}
}
}

Output:
Ques 12. Write a program that reads an arbitrary number of even integers that
are in the range 2 to 100 inclusive and counts how many occurrences of each
are entered. Indicate the end of the input by entering -1. After all input has been
processed, print all of the values that were entered by the user along with the
number of occurrences.
Ans.:
import java.util.Scanner;
public class ComputeExpression {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the even integers(Range: 2 to 100 both
inclusive) \nNote:Input will be end if you enter -1");
int[] count=new int[51];
int val=0;
while(true){
val=input.nextInt();
if(val==-1){
System.out.println("Bye");
break;
}
if( val%2!=0 || val<=0 || val>100){
System.out.println("Enter a correct input");
continue;
}
count[val/2]++;
System.out.println("Enter a new input");
}
System.out.println("-------------Input------Ends---------------");
System.out.println("-----------------Results-------------------");
for(int i=1;i<count.length;i++){
if(count[i]>0)
System.out.println(i*2+" is entered "+count[i]+" times");
}
}
}
Output:
Ques 13. Write a class called NumberOfSixes that represents the total number
of sixes hit by an IPL team in a given match. The NumberOfSixes class should
contain a single integer as instance data, representing the number of sixes hit.
Write a constructor to initialize the number of sixes to zero. Write a method
called setSix that increments the value by one whenever a six is hit, and another
method called getSix that returns the total number of sixes hit so far. Finally,
create a driver class called SixTracker that creates a few NumberOfSixes
objects and tests their methods.
Ans.:
import java.util.Scanner;
public class sixTracker{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
NumberOfSixes team1=new NumberOfSixes();
NumberOfSixes team2=new NumberOfSixes();
while(true){
System.out.println("Enter 1 for team1\nEnter 2 for team2\nEnter 3 to
exit");
int x=input.nextInt();
if(x==3){
System.exit(0);
}
else if(x>3){
System.out.println("Enter a right choice");
continue;
}
System.out.println("Enter 1 for increment in six\nEnter 2 for view
Sixes");
int y=input.nextInt();
if(x==1){
if(y==1){
team1.setSix();
}
else{
System.out.println("Number of sixes of Team1 =
"+team1.getSix());
}
}
else if(x==2){
if(y==1){
team2.setSix();
}
else{
System.out.println("Number of sixes of Team2 =
"+team2.getSix());
}
}
}
}
}
class NumberOfSixes {
public int sixes;
public NumberOfSixes(){
sixes=0;
}
public void setSix(){
sixes++;
}
public int getSix(){
return sixes;
}
}
Output:
Ques 14. Design and implement a set of classes that define various types of
reading material: books, novels, magazines, technical journals, textbooks, and
so on. Include data values that describe various attributes of the material, such
as the number of pages and the names of the primary characters. Include
methods that are named appropriately for each class and that print an
appropriate message. Create a main driver class to instantiate and exercise
several of the classes.
Ans.:
import java.util.Scanner;
class TextBook {
public int pages;
public int publicationYear;
public int price;
public String title;
public String author;
public String publication;
public void setValue(int page,int year,int rate,String t,String name,String
pub){
pages=page;
publicationYear=year;
price=rate;
title=t;
author=name;
publication=pub;
}
public void printValue(){
System.out.println("-------------------------------");
System.out.println("Details of Text Book: ");
System.out.println("-------------------------------");
System.out.println("Publication: " +publication);
System.out.println("No. of pages: " +pages);
System.out.println("Title: " +title);
System.out.println("No. of author: " +author);
System.out.println("Price: " +price+" Rupees");
System.out.println("Publication Year: " +publicationYear);
}
}
class Novel {
public int pages;
public int price;
public String title;
public String writer;
public String genre;
public String publication;
public void setValue(int page,int rate,String t,String name,String pub,String
gen){
pages=page;
price=rate;
title=t;
writer=name;
publication=pub;
genre=gen;
}
public void printValue(){
System.out.println("-------------------------------");
System.out.println("Details of Novel: ");
System.out.println("-------------------------------");
System.out.println("Publication: " +publication);
System.out.println("No. of pages: " +pages);
System.out.println("Title: " +title);
System.out.println("No. of writer: " +writer);
System.out.println("Price: " +price);
System.out.println("Genre: " +genre);
}
}
public class BookTracker{
public static void main(String[] args){
System.out.println("Let's create some reading materials and print their
details.");
TextBook book1=new TextBook();
Novel novel1=new Novel();
book1.setValue(1711,2018,4420,"Intro to Java Programming","Y. Daniel
Liang","Pearson");
novel1.setValue(68,665,"The Life, Lessons & Rules for Success","Steve
Jobs","Unknown","Motivational");
book1.printValue();
novel1.printValue();
}
}
Output:
Ques 15. Design a class named StopWatch. The class contains:
■ Private data fields startTime and endTime with getter methods.
■ A no-arg constructor that initializes startTime with the current time.
■ A method named start() that resets the startTime to the current time.
■ A method named stop() that sets the endTime to the current time.
■ A method named getElapsedTime() that returns the elapsed time for the
stopwatch in milliseconds.
Draw the UML diagram for the class and then implement the class in Java.
Ans.:
UML:

StopWatch
startTime : long
endTime : long
StopWatch()
Start()
Stop()
getStart()
getEnd()
getTimeElapsed()

import java.util.Scanner;
public class StopWatch {
private long startTime;
private long endTime;
public StopWatch(){
startTime=System.currentTimeMillis();
}
public void start(){
startTime=System.currentTimeMillis();
}
public void stop(){
endTime=System.currentTimeMillis();
}
public long getStart(){
return startTime;
}
public long getEnd(){
return endTime;
}
public long getTimeElapsed(){
return endTime-startTime;
}
public static void main(String[] args){
Scanner input=new Scanner(System.in);
StopWatch watch1=new StopWatch();
System.out.println("Enter 1 to start the stopwatch");
int ans=input.nextInt();
if(ans==1)
{
watch1.start();
System.out.println("CurrentTimeMillis : "+watch1.getStart());
}
else{
System.out.println("Input is wrong");
System.exit(0);
}
System.out.println("Enter 1 to stop the stopwatch");
ans=input.nextInt();
if(ans==1)
{
watch1.stop();
System.out.println("CurrentTimeMillis : "+watch1.getEnd());
}
else{
System.out.println("Input is wrong");
System.exit(0);
}
System.out.println("Enter 1 to get time elapsed in millisecond");
ans=input.nextInt();
if(ans==1)
{
System.out.println("Time elapsed in MilliSecond :
"+watch1.getTimeElapsed());
}
else{
System.out.println("Input is wrong");
System.exit(0);
}
}
}

Output:

--------------------------THANKS-----------------------------

You might also like