Java-Loop forหาอนุกรม

posted on 01 Dec 2009 17:00 by lavalin  in Java

public class LAB4

{
 public static void main(String[] args)
 {
  int i  ;
  double n = 0 ;
  for(i=1;i<=100;i++)
  {
   n = n+i;
  }
  System.out.print("1+2+3+...+100 = "+ n + "\n" );
  
  n = 0;
  for(i=2;i<=100;i = i+2)
  {
   n = n+i;
  }
  System.out.print("2+4+6+...+100 = "+ n + "\n" );


  n = 0;
  for(i=1;i<=100;i++)
  {
   n = n + (double)i/(i+1);
  }
  System.out.print("1/2 + 2/3 + 3/4 +...+ 100/101  = "+ n + "\n" );

  n = 0;
  for(i=1;i<=100;i++)
  {
   n = n + (double)((i*i)/(i+1));//ประมาณว่าเอาดับเบิ้ลมาคูณให้ค่าที่ได้เป็นทศนิยม
  }
  System.out.print("1/2 + 4/3 + 9/4 +...+ 10000/101  = "+ n + "\n" );


 }
}

Java-Scanner

posted on 01 Dec 2009 16:59 by lavalin  in Java

import java.util.Scanner;

public class LAB3
{
 public static void main(String[] args)

 {

 Scanner input = new Scanner(System.in);
 System.out.print("Please enter First number : ");
 int first =input.nextInt();
 System.out.print("Please enter second number : ");
 int second = input.nextInt();
 System.out.println();

 System.out.print("**********MENU**************\n");
    System.out.print("1. plus         \n"); 
    System.out.print("2. minus        \n");
    System.out.print("3. multiply     \n");
    System.out.print("4. divide       \n");
 System.out.print("****************************\n");

  System.out.print("Please Choos 1,2,3 or 4 : ");
  int choice = input.nextInt();
  System.out.println();
  int result = input.nextInt();


  switch(choice)
  {
   case 1 :result = first + second;
    break;
   case 2 :result = first - second;
    break;
   case 3 :result = first * second;
    break;
   case 4 :result = first / second;
    break;
            default: System.out.print("\n youmust enter only 1,2,3  or 4");
  }
    System.out.print("Result ="+result);
 System.out.println();

  }
}