top of page
Java Arrays - Hands on 1
Problem 1:
​
Find Docs with Odd Pages
Create class Document with below attributes
id - int
title - String
folderName - String
pages - int
Write getters, setters and parameterized constructor as required.
Create class Solution with main method.
Implement static method - docsWithOddPages in Solution class.
This method will take array of Document objects and return another array with Document objects which has odd number of pages.
This method should be called from main method and display values of returned objects as shared in the sample (in ascending order of id attribute).
Before calling this method, use Scanner object to read values for four Document objects referring attributes in the above sequence.
Next call the method and display the result.
Consider below sample input and output:
Input:
1
resume
personal
50
2
question1
exams
55
3
question2
exams
45
4
India
misc
40
Output (each line has values separated by single space):
2 question1 exams 55
3 question2 exams 45
​
Solutions:
​
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner scn=new Scanner(System.in);
Document[] docsArray=new Document[4];
Document[] res=new Document[4];
for(int i=0;i<docsArray.length;i++)
{
docsArray[i]=new Document();
res[i]=new Document();
}
for(int i=0;i<docsArray.length;i++)
{
docsArray[i].id=scn.nextInt();
docsArray[i].title=scn.next();
docsArray[i].folderName=scn.next();
docsArray[i].pages=scn.nextInt();
}
res= docsWithOddPages(docsArray);
for(int i=0;i<res.length;i++)
{
if(res[i].getTitle()!=null)
System.out.println(res[i].getId()+" "+res[i].getTitle()+" "+res[i].getFolderName()+" "+res[i].getPages());
}
}
public static Document[] docsWithOddPages(Document[]docsArray){
Document[] oddDocs=new Document[4];
for(int i=0;i<docsArray.length;i++)
{
oddDocs[i]=new Document();
}
int k=0;
for(int i=0;i<docsArray.length;i++)
{
if(docsArray[i].pages%2!=0)
{
oddDocs[k++]=docsArray[i];
}
}
int p=oddDocs.length;
for(int i=0;i<p-1;i++){
for(int j=0;j<p-i-1;j++){
if(oddDocs[j].id>oddDocs[j+1].id){
Document t=oddDocs[j];
oddDocs[j]=oddDocs[j+1];
oddDocs[j+1]=t;
}
}
}
return oddDocs;
}
}
class Document
{
int id,pages;
String title,folderName;
public void setId(int id){
this.id=id;
}
public void setTitle(String title){
this.title=title;
}
public void setFolderName(String folderName){
this.folderName=folderName;
}
public void setPages(int pages){
this.pages=pages;
}
public int getId(){
return this.id;
}
public String getTitle(){
return this.title;
}
public String getFolderName(){
return this.folderName;
}
public int getPages(){
return this.pages;
}
}
Java Arrays - Hands on 1: About
bottom of page