Publicité
Import java
Import java
Import java
Import java
Publicité
Import java
Import java
Import java
Import java
Import java
Publicité
Import java
Import java
Import java
Import java
Import java
Publicité
Import java
Import java
Import java
Import java
Import java
Publicité
Import java
Prochain SlideShare
Java programsJava programs
Chargement dans ... 3
1 sur 20
Publicité

Contenu connexe

Publicité

Import java

  1. importjava.util.Scanner; classFactorial { publicstaticvoidmain(Stringargs[]) { intn, c, fact = 1; System.out.println("Enteranintegertocalculate it'sfactorial"); Scannerin= newScanner(System.in); n = in.nextInt(); if (n< 0) { System.out.println("Numbershouldbe non-negative."); } else { for(c = 1; c <= n; c++) { fact = fact * c; } System.out.println("Factorial of "+ n + " is= " + fact); } } } //OUT PUTS //run:
  2. //Enteran integertocalculate it'sfactorial //3 //Factorial of 3 is = 6 //BUILD SUCCESSFUL (total time:13 seconds importjava.util.Scanner; classsequence1{ publicstaticvoidmain(String[] args) { sequence1fs=newsequence1(); fs.fibonacci(); } publicvoidfibonacci(){ intnumb1= 1; intnumb2= 1; inttemp= 0; @SuppressWarnings("resource") Scannerinput= newScanner(System.in); System.out.println("HowManyTerms?(Up To n)"); intx = input.nextInt(); x = x - 2; System.out.println(numb1); System.out.println(numb2);
  3. for(inti = 0; i < x; i++) { System.out.println(numb1+numb2 + " "); temp= numb1; numb1= numb2; numb2= temp+ numb2; } } } importjava.util.Scanner; classBinaryGCD { publicstaticvoidmain(String[] args) { Scannerinput= newScanner(System.in); System.out.println("Pleaseenterthe firstinteger:"); intb = input.nextInt(); System.out.println("Pleaseenterthe secondinteger:"); intd = input.nextInt(); System.out.println("The GCDof " + b + " and" + d + " is " + getGcd(b,d) + "."); } publicstaticintgetGcd(intb,int d) { intgcd = 1;
  4. if (b> d) { for(inti = d;i >= 1; i--) { if (b % i == 0 && d % i == 0) { return i; } } } else { for(intj = b; j >= 1; j--) { if (b % j == 0 && d % j == 0) { return j; } } } returngcd; } } //OUT PUTS // run: //Please enterthe firstinteger: //6 //Please enterthe secondinteger: //4 //The GCD of 6 and4 is2.
  5. //BUILD SUCCESSFUL (total time:9 seconds) importjava.util.Scanner; publicclassODDEVEN { } classOddOrEven{ publicstaticvoidmain(Stringargs[]) { intx; System.out.println("Enteranintegertocheckif itis oddor even"); Scannerin= newScanner(System.in); x = in.nextInt(); if (x % 2 == 0) { System.out.println("Youenteredanevennumber."); } else { System.out.println("Youenteredanoddnumber."); } } } //OUTPUT // run: //Enteran integertocheckif it isodd or even //3
  6. //Youenteredanoddnumber. //BUILD SUCCESSFUL (total time:8 seconds importjava.util.Scanner; classTrignometricFunctionsDemo{ publicstaticvoidmain(String[] args) { //Create a Scannerobjectwhichwill read //valuesfromthe console whichuserenters Scannerscanner= newScanner(System.in); //Gettinginputfromuserfrom the console System.out.println("Entervalueof angle indegrees"); //CallingnextDouble methodof scannerfor //takinga double value fromuserandstoring //it indegreesvariable double degrees=scanner.nextDouble(); System.out.println("Letscalculatethe sine,cosineandtanof angle ..."); //In orderto calculate sine ,cosine andtan of angle we //use the Math classthree static methodsbyname as : //1. Math.sin(a) -- Sine of a //2. Math.cos(a) -- Cosine of a
  7. //3. Math.tan(a) -- Tangentof a double sineOfAngle =Math.sin(degrees); double cosOfAngle=Math.cos(degrees); double tanOfAngle=Math.tan(degrees); System.out.println(); System.out.println("The Sine of "+ degrees+" degreesis: " + sineOfAngle); System.out.println("The Cosine of "+ degrees+ " degreesis:" + cosOfAngle); System.out.println("The Tangentof "+ degrees+ " degreesis:" + tanOfAngle); System.out.println(); System.out.println("Lets calculatethe sec,cosecandcot of angle ..."); //In orderto calculate sec,cosecand cot of angle we //justinverse the value of sin,cos and tan calculatedabove : //4. Secof a -- 1 / Sine of a //5. Cosecof a -- 1/ Cosine of a //6. Cotof a -- 1 / Tangentof a double secOfAngle =1 / Math.sin(degrees); double cosecOfAngle =1 / Math.cos(degrees); double cotOfAngle =1 / Math.tan(degrees);
  8. System.out.println("nTheSecof " + degrees+ " degreesis:" + secOfAngle); System.out.println("The Cosecof "+ degrees+" degreesis:" + cosecOfAngle); System.out.println("The Cotangentof "+ degrees+" degreesis: " + cotOfAngle); } } // OUTPUT //run: //Entervalue of angle indegrees //30 //Letscalculate the sine,cosine andtanof angle ... // //The Sine of 30.0 degreesis: -0.9880316240928618 //The Cosine of 30.0 degreesis:0.15425144988758405 //The Tangentof 30.0 degreesis: -6.405331196646276 // //Letscalculate the sec,cosecand cot of angle ... // //The Secof 30.0 degreesis: -1.012113353070178 //The Cosecof 30.0 degreesis:6.482921234962678 //The Cotangentof 30.0 degreesis: -0.15611995216165922 //BUILD SUCCESSFUL (total time:9 seconds)
  9. importjava.util.Scanner; classdecimal { } classDecimalBinaryProgram{ publicstaticvoidmain(String[] args) { Scannerin= newScanner(System.in); while (true){ System.out.println("Enterintegerindecimal form(or#to quit):"); Strings1 = in.nextLine(); if ("#".equalsIgnoreCase(s1.trim())) { break; } System.out.println(decimalToBinary(s1)); System.out.println("Enterintegerinbinaryform (or# to quit):"); Strings2 = in.nextLine(); if ("#".equalsIgnoreCase(s2.trim())) { break; } System.out.println(binaryToDecimal(s2)); }
  10. } private staticStringdecimalToBinary(Strings) { intn = Integer.parseInt(s,10); StringBuildersb= newStringBuilder(); if (n== 0) { return"0"; } intd = 0; while (n>0) { d = n % 2; n /= 2; sb.append(d); } sb= sb.reverse(); returnsb.toString(); } private staticStringbinaryToDecimal(Strings) { intdegree =1; intn = 0; for(intk = s.length() - 1; k >= 0; k--) { n += degree *(s.charAt(k) - '0'); degree *= 2;
  11. } returnn + ""; } } //OUTPUT //run: //Enterintegerindecimal form(or# to quit): //2 //10 //Enterintegerinbinaryform (or# to quit): //3 //3 //Enterintegerindecimal form(or# to quit): //3 //11 //Enterintegerinbinaryform (or# to quit): //4 //4 //Enterintegerindecimal form(or# to quit): //4 //100 //Enterintegerinbinaryform (or# to quit): //5 //5 //Enterintegerindecimal form(or# to quit):
  12. //5 //101 importjava.io.*; publicclassbetriangle { } // CSC108 Chapter4, Question19 // Name: Iam Me StudentID:555555555 // Tutor: AndriaHunter Prof:KenJackson // // ProgramDescription:Thisprogramusesthe Triangle class // to create a triangle object. Itthenusesthe is_right, // is_scalene,is_isosceles,andis_equilateral methods // to testwhat type of triangle itis. // The Triangle classcontainsthree variablestostore the length // of each side of the triange,andmethodsthatcan be usedtodetermine // determineif atriange isright,scalene,isoscelese,andequilateral. classTriangle { // Storesthe lengthof eachside of the Triangle object. private intside1,side2,side3; // Constructorto initialize the sidesof the triangle. publicTriangle(ints1,ints2, ints3) {
  13. side1= s1; side2= s2; side3= s3; } // Methodto testfor a right-angledtriangle. publicbooleanis_right() { if (((side1* side1) == ((side2*side2) + (side3* side3))) || ((side2*side2) == ((side1*side1) + (side3* side3))) || ((side3*side3) == ((side1*side1) + (side2* side2)))) { returntrue; } else { returnfalse; } } // Methodto testfor a scalene triangle. publicbooleanis_scalene() { if ((side1!=side2) && (side1!=side3) && (side2!= side3)) { returntrue; } else { returnfalse; } }
  14. // Methodto testfor an isoscelestriangle. publicbooleanis_isosceles() { if (((side1== side2) && (side1!=side3)) || ((side1== side3) &&(side1!= side2)) || ((side2== side3) &&(side2!= side1))) { returntrue; } else { returnfalse; } } // Methodto testfor an equilateral triangle. publicbooleanis_equilateral(){ if ((side1==side2) && (side1== side3)) { returntrue; } else { returnfalse; } } } // The Test_Triangle classcontainsone mainmethodwhere program // executionstarts. Itallowsthe usertocreate triangle objects // byenteringthe dimensionsforthe three sidesof the triangle, // andit determinesthe type of eachtriangle. The usertypes'n'
  15. // whentheywanttoquit the program(mustenterat least1 triangle). classTest_Triangle { // Main methodthatallowsthe userto enterthe dimentionsfor // three sidesof a triangle. These dimensionsare thenusedto // create a Triangle object,andthisobjectistestedtodetermine // whattype of triangle itis. publicstaticvoidmain(String[] args) throwsIOException{ //Declare stdinsodata can be readfrom input. DataInputStreamstdin=newDataInputStream(System.in); //loopexitswhenthe userresponse is"n" Stringuser_response="y"; while (!user_response.equals("n")) { //Ask userfor 3 dimensionsof triangle. System.out.println("nEnterside1length:"); intside1= Integer.parseInt(stdin.readLine()); System.out.println("Enterside2length:"); intside2= Integer.parseInt(stdin.readLine()); System.out.println("Enterside3length:"); intside3= Integer.parseInt(stdin.readLine());
  16. //Nowuse these valuestocreate aTriangle object. Triangle tri = newTriangle(side1,side2,side3); //Determine whatkindof triangle itis. System.out.println("nIstriangle right-angle?"+ tri.is_right()); System.out.println("Istriangle scalene? " + tri.is_scalene()); System.out.println("Istriangle isosceles? " + tri.is_isosceles()); System.out.println("Istriangle equilateral?" + tri.is_equilateral()); //Ask userif theywantto continue. System.out.println("nDoyouwanttoexamine more triangles?"); System.out.println("(type'y'foryesor 'n' for no)"); user_response =stdin.readLine(); } } } //OUTPUT // run: // //Enterside1length: //3 //Enterside2length: //2
  17. //Enterside3length: //1 // //Istriangle right-angle?false //Istriangle scalene? true //Istriangle isosceles? false //Istriangle equilateral?false // //Doyou wantto examine more triangles? //(type 'y'for yesor 'n' for no) //y // //Enterside1length: //7 //Enterside2length: //9 //Enterside3length: //8 // //Istriangle right-angle?false //Istriangle scalene? true //Istriangle isosceles? false //Istriangle equilateral?false // //Doyou wantto examine more triangles?
  18. //(type 'y'for yesor 'n' for no) /* * Sum five numbers and print the result */ public class FiveNumberSum { // Save as "FiveNumberSum.java" public static void main(String[] args) { int number1 = 11; // Declare 5 int variables to hold 5 integers int number2 = 22; int number3 = 33; int number4 = 44; int number5 = 55; int sum; // Declare an int variable called sum to hold the sum sum = number1 + number2 + number3 + number4 + number5; System.out.print("The sum is "); // Print a descriptive string System.out.println(sum); // Print the value stored in sum } } publicclassARTIMATIC{ } classArithmeticTest{ // Save as "ArithmeticTest.java" publicstaticvoidmain(String[] args) { intnumber1= 98; // Declare anint variable number1andinitializeitto98 intnumber2= 5; //Declare an intvariable number2andinitialize itto5 intsum,difference,product,quotient,remainder; //Declare five intvariablestoholdresults //PerformarithmeticOperations sum= number1+ number2;
  19. difference =number1- number2; product= number1* number2; quotient=number1/ number2; remainder=number1% number2; //Printresults System.out.print("The sum,difference,product,quotientandremainderof "); //Printdescription System.out.print(number1); //Printthe value of the variable System.out.print("and"); System.out.print(number2); System.out.print("are "); System.out.print(sum); System.out.print(","); System.out.print(difference); System.out.print(","); System.out.print(product); System.out.print(","); System.out.print(quotient); System.out.print(",and"); System.out.println(remainder); ++number1; // Incrementthe value storedinthe variable "number1"by1 //Same as "number1= number1+ 1" --number2; //Decrementthe value storedinthe variable"number2"by1 //Same as "number2= number2- 1"
  20. System.out.println("number1afterincrementis"+ number1); //Printdescriptionandvariable System.out.println("number2afterdecrementis"+ number2); quotient=number1/ number2; System.out.println("The newquotientof "+ number1+ " and " + number2 + " is" + quotient); } } //OUT PUT // run: //The sum,difference,product,quotientandremainderof 98 and 5 //are 103, 93, 490, 19, and 3 //number1afterincrementis99 //number2afterdecrementis4 //The newquotientof 99 and 4 is24 //BUILD SUCCESSFUL (total time:1 second)
Publicité