Java prog upto week 8

  • 74 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
74
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
5
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Week-1 EXERCISE-1: 1a ) Aim: The Fibonacci valuesinthe sequenceare 1 and 1. Everysubsequentvalue isthe sumof the twovaluesprecedingit.Write ajavaprogram that usesbothrecursive andnon-recursivefunctionsto printthe nth value inthe fibbonacci sequence. Program:*/ importjava.lang.*; importjava.util.*; classFibonacci { publicstaticvoidmain(Stringargs[]) { inta=0,b=1,c; System.out.println("Enternvalue"); Scannersc = newScanner(System.in); intn = sc.nextInt(); inti=3; System.out.println("Fibonacci series fornis"); System.out.print(a+""+b+""); while(i<=n) { c=a+b; a=b; b=c; System.out.print(c+""); i++;
  • 2. } } } Output: Enter n value 5 Fibonacci seriesfornis 0 1 1 2 3
  • 3. 1b) Recursion program: importjava.lang.*; importjava.util.*; classFibonacciRec { publicstaticvoidmain(Stringargs[]) { inta=0,b=1; Recurssionfr=newRecurssion(); Scannersc = newScanner(System.in); System.out.println("Enternvalue"); intn= sc.nextInt(); System.out.println("Fibonacci seriesfornis"); System.out.print(""+a+""+b+" "); fr.recurssion(n,a,b); } } classRecurssion { inti=3; publicvoidrecurssion(intn,inta,intb) {
  • 4. intc; if(i<=n) { c=a+b; a=b; b=c; System.out.print(c+""); i++; recurssion(n,a,b); } } } Output: Enter n value 4 Fibonacci seriesfornis 0 1 1 2
  • 5. Week-2 2) Aim: Write a javaprogram that prompts the user for an integer and the prints out all prime numbers upto that integer. Program:*/ importjava.io.*; importjava.lang.*; importjava.util.*; classPrime { publicstaticvoidmain(Stringargs[]) { int i,j,n,count=0; Scannersc=newScanner(System.in); System.out.println("Enternvalue:"); n=sc.nextInt(); for(i=1;i<=n;i++) { count=0; for(j=1;j<=i;j++) { if(i%j==0) count++; } if(count==2) System.out.println("t"+i); }
  • 6. } } Output: Enter n value: 10 2 3 5 7
  • 7. Week-3 3a) Aim: Write a java program that checks whether a given stringisa palindrome or not. Ex: MADAM is a palindrome.*/ Program: importjava.util.*; publicclassPalan { publicstaticvoidmain(Stringa[]) { System.out.println("Enteranystring"); Strings=newScanner(System.in).next(); for(inti=0,j=s.length()-1;i<=j;i++,j--) { if(s.charAt(i)==s.charAt(j)); else { System.out.println("NotPalindrome"); System.exit(1); } } System.out.println("Palindrome"); } } Output: Enter any string MADAM
  • 8. Palindrome Enter anystring KAUSHIK Not Palindrome
  • 9. 3b) Aim: Write a javaprogram for sortinga givenlistof namesinascendingorder. Program: importjava.util.*; classSortst { publicstaticvoidmain(Stringa[]) { System.out.println("How manystringuwantto enter"); Scannersc=newScanner(System.in); intn=sc.nextInt(); Stringst[]=newString[n+1]; for(inti=0;i<n;i++) { System.out.println("Enterstring"+(i+1)); st[i]=sc.next(); } for(inti=0;i<n-1;i++) { for(intj=i+1;j<n;j++) { if(st[i].compareTo(st[j])>0) { Stringt=st[i]; st[i]=st[j]; st[j]=t;
  • 10. } } } System.out.println("Stringsinorderare :nn"); for(inti=0;i<n;i++) System.out.println(st[i]); } } Output: Enter string1 Kaushik Enter string2 College Enter string3 Engineering Enter string4 Courses Stringsinorder are: College Courses Engineering Kaushik
  • 11. Week-4 4a) Aim: write javaprogram that readsa file name fromthe user,thendisplayinformationabout whetherthe file exists,whetherthe fileis readable,whetherthe fileiswritable,the type of fileandthe lengthof the file inbytes Program:*/ importjava.io.*; importjava.util.*; classFileattr { publicstaticvoidmain(Stringargs[]) { File f1=newFile(args[0]); System.out.println(f1.exists()?"fileexists":"doesnotexist"); System.out.println("Filename:"+f1.getName()); System.out.println("Filepath:"+f1.getAbsolutePath()); System.out.println(f1.isDirectory()?"isadirectory":"isasimple file"); System.out.println(f1.canRead()?"canbe read":"cannotbe read"); System.out.println(f1.canWrite()?"canbe write":"cannotbe write"); System.out.println("lengthof fileinbytes:"+f1.length()); } } Output: File exists Filename:First.txt Filepath:D:First.txt Is a simple file
  • 12. Can be read Can be write Lengthof file inbytes:55
  • 13. 4b) Aim: write a java programthat readsa file anddisplaysthe file onthe screen,withaline number before eachline. Program:*/ importjava.io.*; publicclassReadFile { publicstaticvoidmain(String[] args) { try { FileReaderinput=newFileReader(args[0]); BufferedReaderbufRead=newBufferedReader(input); Stringline; intcount = 0; line = bufRead.readLine(); count++; while (line !=null) { System.out.println(count+":"+line); line = bufRead.readLine(); count++; } bufRead.close(); } catch (ArrayIndexOutOfBoundsExceptione) {
  • 14. System.out.println("Usage:javaReadFilefilenamen"); } catch (IOExceptione) { e.printStackTrace(); } } } Output: D:>java Readfile first.txt 1:This ismy file 2:Kaushikengineeringcollege 3:Visakhapatnam
  • 15. Week-5 5) Aim: Write a java programthat displaysthe numberof characters,linesandwordsina textfile. Program:*/ importjava.io.*; importjava.util.*; importjava.lang.*; publicclass ClwinText { private staticvoidlinecount(StringfName,BufferedReaderin) throwsIOException { longnumChar= 0; longnumLine=0; longnumWords= 0; Stringline; do{ line = in.readLine(); if (line !=null) { numChar+= line.length(); numWords+= wordcount(line); numLine++; } }while(line!=null); System.out.println("FileName:"+ fName); System.out.println("Numberof characters:" + numChar);
  • 16. System.out.println("Numberof words:"+ numWords); System.out.println("Numberof Lines:"+ numLine); } private staticvoidlinecount(StringfileName) { BufferedReaderin= null; try { FileReaderfileReader=newFileReader(fileName); in= newBufferedReader(fileReader); linecount(fileName,in); } catch(IOExceptione) { e.printStackTrace(); } } private staticlongwordcount(Stringline) { longnumWords= 0; intindex = 0; booleanprevWhiteSpace =true; while(index<line.length()) { char c = line.charAt(index++);
  • 17. booleancurrWhiteSpace =Character.isWhitespace(c); if(prevWhiteSpace &&!currWhiteSpace) { numWords++; } prevWhiteSpace=currWhiteSpace; } returnnumWords; } publicstaticvoidmain(String[] args) { longnumChar= 0; longnumLine=0; Stringline; try { if (args.length==0) { BufferedReaderin= new BufferedReader(newInputStreamReader(System.in)); line = in.readLine(); numChar= line.length(); if (numChar!= 0) { numLine=1; }
  • 18. System.out.println("Numberof characters:" + numChar); System.out.println("Numberof words:"+ wordcount(line)); System.out.println("Numberof lines:"+ numLine); } else { for(inti = 0; i < args.length;i++) { linecount(args[i]); } } } catch(IOExceptione){ e.printStackTrace(); } } } Output: File Name:ClwinText.java Number of characters:1928 Numberof words:246 Numberof lines:91
  • 19. Week -6 6a) Aim: write a javaprogram that: i)implementsstackADT. Program: importjava.io.*; importjava.util.*; classStack1 { inttop=-1,st[]=newint[5]; voidpush(intel) { st[++top]=el; } intpop() { return(st[top--]); } voiddisplay() { System.out.println("nStackelementsfromtoptobottomn"); for(inti=top;i>=0;i--) System.out.println(st[i]); } booleanisFull() {
  • 20. return(top==5-1); } booleanisEmpty() { return(top==-1); } } classStack { publicstaticvoidmain(Stringa[]) { Scannersc=newScanner(System.in); Stack1 s=newStack1(); intel=0,ch=1; while(ch!=4) { System.out.println("n1.PUSHn2.POPn3.DISPLAYn4.EXIT"); System.out.println("ENTERYOURCHOICE"); ch=sc.nextInt(); switch(ch) { case 1:if(s.isFull()) System.out.println("nstackisfull"); else {
  • 21. System.out.println("Enterelement"); el=sc.nextInt(); s.push(el); }break; case 2:if(s.isEmpty()) System.out.println("nstackisempty"); else { el=s.pop(); System.out.println("nDeletedelement="+el); }break; case 3:if(s.isEmpty()) System.out.println("nstackisempty"); else s.display(); break; case 4:break; default:System.out.println("nEntercorrectchoice"); } } } } Output: 1.PUSH 2.POP
  • 22. 3.DISPLAY 4.EXIT Enter yourchoice 1 Enter element 52 Enter yourchoice 1 Enter element 45 Enter yourchoice 3 Stack elementsfromtopto bottom 45 52 Enter yourchoice 2 Deletedelement=45 Enter yourchoice 4
  • 23. 6b) Aim: convertsinfix expressionintopostfixform. Program: importjava.io.*; importjava.util.*; publicclassInfixToPostfix { private StacktheStack; publicstaticvoidmain(String[] args) throwsIOException { BufferedReaderA = newBufferedReader(new InputStreamReader(System.in)); Stringmathex; System.out.println("enteramathematical expresion:"); mathex = A.readLine(); Stringinput= null; Stringoutput; InfixToPostfixtheTrans=newInfixToPostfix(mathex); output= theTrans.doTrans(); System.out.println("infix is:" + mathex + 'n'); System.out.println("postfix is:" + output + 'n'); }
  • 24. Stringinput; Stringoutput= ""; publicInfixToPostfix(Stringin) { input= in; intstackSize = input.length(); theStack= newStack(stackSize); } publicStringdoTrans() { for(intj = 0; j < input.length();j++) { char ch = input.charAt(j); switch(ch) { case '+': case '-': gotOper(ch,1); break; case '*': case '/': gotOper(ch,2); break; case '(': theStack.push(ch);
  • 25. break; case ')': gotParen(ch); break; default: output= output+ ch; break; } } while (!theStack.isEmpty()) { output= output+ theStack.pop(); } return output; } publicvoidgotOper(charopThis,intprec1) { while (!theStack.isEmpty()) { char opTop= theStack.pop(); if (opTop== '(') { theStack.push(opTop); break; } else { int prec2; if (opTop== '+' || opTop == '-')
  • 26. prec2 = 1; else prec2 = 2; if (prec2< prec1) { theStack.push(opTop); break; } else output= output+ opTop; } } theStack.push(opThis); } publicvoidgotParen(charch){ while (!theStack.isEmpty()) { char chx = theStack.pop(); if (chx == '(') break; else output= output+ chx; } }
  • 27. classStack { private intmaxSize; private char[] stackArray; private inttop; publicStack(intmax) { maxSize =max; stackArray= newchar[maxSize]; top = -1; } publicvoidpush(charj) { stackArray[++top] = j; } publicchar pop() { returnstackArray[top--]; } publicchar peek() { returnstackArray[top]; } publicbooleanisEmpty() { return(top == -1); } } }
  • 28. Output: Enter a mathematical expression A+b*c Infix is:a+b*c Postfix is:abc*+ Enter a mathematical expression (a+b)*(c/d)*e-f Infix is:(a+b)*(c/d)*e-f Postfix is:ab+cd/e*f-
  • 29. Week -7 7) Aim: Write a Java programthat createsthree threads.Firstthreaddisplays“GoodMorning” everyone second,the second threaddisplays“Hello”everytwosecondsandthe third threaddisplays“Welcome”everythree seconds. Program:*/ classA extendsThread { synchronizedpublicvoidrun() { try { while(true) { sleep(1000); System.out.println("goodmorning"); } } catch(Exceptione) { } } } classB extendsThread { synchronizedpublicvoidrun()
  • 30. { try { while(true) { sleep(2000); System.out.println("hello"); } } catch(Exceptione) { } } } classC extendsThread { synchronizedpublicvoidrun() { try { while(true) { sleep(3000); System.out.println("welcome"); } }
  • 31. catch(Exceptione) { } } } classThreadDemo { publicstaticvoidmain(Stringargs[]) { A t1=newA(); B t2=new B(); C t3=new C(); t1.start(); t2.start(); t3.start(); } } Output: goodmorning goodmorning hello goodmorning welcome hello goodmorning goodmorning
  • 32. Week -8 8) Aim: Sample Programtoimplementpackage package Demo; publicclassA { publicvoiddisplay() { System.out.println("HelloVinay"); } } importDemo.*; publicclasspackageDemo { publicstaticvoidmain(Stringargs[]) { A ob=newA(); ob.display(); } } Output: D:>cd demo D:Demo>javacA.java D:Demo>cd..
  • 33. D:>javac packageDemo.java D:>javapackageDemo Hello world