فيما يلي امثلة لاستخدام المتحولات variables في جافا
كود جمع متغيرين من نوع string:
String firstName="ahmed";
String lastName="mahdi";
String fullName=firstName+" "+lastName;
System.out.println(fullName);
كود جمع متغيرين من نوع رقم:
int number1=15;
int number2=5;
int result=number1+number2;
System.out.println(result);
كود ادخال الاسم والكنية من الكيبورد وجمعهما وطباعة النتيجة:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter first name: ");
String firstname=input.next();
System.out.println("enter last name: ");
String lastname=input.next();
String fullname=firstname+" "+lastname;
System.out.println(fullname);
}
}
كود ادخال رقمين من الكيبورد وجمعهما وطباعة نتيجة الجمع:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter first number:");
int number1=input.nextInt();
System.out.println("enter second number:");
int number2=input.nextInt();
int result=number1+number2;
System.out.println(result);
}
}
كود تعريف متغير من نوع boolean وطباعته:
boolean is_smoker=true;
System.out.println(is_smoker);
برنامج لحساب مساحة ومحيط المربع:
write java program to calculate square area and perimeter, program should prompts user to enter side length, then calculate the area and perimeter based on it
/*write java program to calculate square area and perimeter, program should prompts user to enter side length, then calculate the area and perimeter based on it*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("please enter the side length");
int sideLength=input.nextInt();
int area=sideLength*sideLength;
System.out.println("the square area is "+area);
int perimeter=sideLength*2;
System.out.println("the square perimeter is "+perimeter);
}
}
برنامج لحساب مساحة ومحيط المستطيل:
write java program to calculate rectangle area and perimeter, program should prompts user to enter length and width, then calculate the area and perimeter based on it
/*write java program to calculate rectangle perimeter, program should prompts user to enter length and width, then calculate the area and perimeter based on it*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("please enter the length of rectangle:");
int length=input.nextInt();
System.out.println("please enter the width of rectangle:");
int width=input.nextInt();
int area=length*width;
System.out.println("the rectangle area is "+area);
int perimeter=(length+width)*2;
System.out.println("the rectangle perimeter is "+perimeter);
}
variable VS constant in java
مقارنة بين المتغير والثابت في جافا:
برنامج يحسب مساحة دائرة:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
final double PI = 3.14159; // Declare a constant
// Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter a radius
System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();
// Compute area
double area = radius * radius * PI;
// Display result
System.out.println("The area for the circle of radius " +
radius + " is " + Math.round(area));
}
}
اولويات العمليات الرياضية في جافا:
الاولوية بالترتيب كالتالي:
- الاس ^ power
- الزيادة بمقدار واحد ++ increment والنقصان بمقدار واحد -- decrement
- باقي القسمة Remainder %
- الضرب والقسمة * / multiplication and subtraction
- الاشارات الايجابية + والاشارات السلبية - unary plus and minus operators
- الجمع والطرح + - add and subtract
- المساواة = assignment
int n1=5;
int n2=4;
int n3=7;
int n4=12;
int result=n1+n2+n3+n4;
System.out.println("n1+n2+n3+n4 = "+result);
result=n1+n2*n3-n4;
System.out.println("n1+n2*n3-n4 = "+result);
result=(n1+n2)*(n3-n4);
System.out.println("(n1+n2)*(n3-n4) = "+result);
Casting in java
امثلة على قص انواع البيانات في لغة جافا
//cast float to integer
int x = (int)1.9;
int y = (int)2.8;
System.out.println(x);
System.out.println(y);
//cast to float
float x = (float)1;
float y = (float)2.8;
float w = (float)4.2;
System.out.println(x);
System.out.println(y);
System.out.println(w);
امثلة عن استخدام المتغيرات ( المتحولات variables ) في لغة البرمجة java
--------------------------------------------------------------------------------------------------------
برنامج يقوم بالتبديل بين قيمتي متحولين, باستخدام متحول وسيط مؤقت:
//write java program to switch values between 2 variables
int x=5;
int y=10;
System.out.println("x before is : "+x+" y before is : "+y);
int temp=x;
x=y;
y=temp;
System.out.println("x after is : "+x+" y after is : "+y);
مثال الة حاسبة بسيطة, تقوم بتنفيذ العمليات الحسابية الاربعة على عددين مدخلين من الكيبورد:
//create simple calculater
Scanner input = new Scanner(System.in);
System.out.println("please enter first number:");
int num1=input.nextInt();
System.out.println("please enter second number:");
int num2=input.nextInt();
int summation_result=num1+num2;
int subtraction_result=num1-num2;
int multiplication_result=num1*num2;
int division_result=num1/num2;
int remainder_result=num1%num2;
System.out.println("the summation result is :" + summation_result);
System.out.println("the subtraction result is :"+subtraction_result);
System.out.println("the multiplication result is :"+multiplication_result);
System.out.println("the division result is :"+division_result);
System.out.println("the remainder is :"+remainder_result);
برنامج يحسب مساحة الشكل المسدس(سداسي الاضلاع):
/*
(Geometry: area of a hexagon) Write a program that prompts the user to enter the
side of a hexagon and displays its area.
*/
import java.util.Scanner;
public class Exercise_02_16 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter the side of a hexagon
System.out.print("Enter the side: ");
double side = input.nextDouble();
// Compute the area of the hexagon
double area = ((3 * Math.pow(3, 0.5)) / 2) * Math.pow(side, 2);
// Display result
System.out.println("The area of the hexagon is " + area);
}
}
برنامج يحسب فوائد القروض باستخدام Java :
/*
(Financial application: calculate interest) If you know the balance and the annual
percentage interest rate, you can compute the interest on the next monthly payment
using the following formula:
interest = balance * (annualInterestRate/1200)
Write a program that reads the balance and the annual percentage interest rate and
displays the interest for the next month.
*/
//put the following code in main function:
Scanner input = new Scanner(System.in);
// Prompt the user to enter a balance and
// the annual percentage interest rate
System.out.print("Enter balance and interest rate (e.g., 3 for 3%): ");
double balance = input.nextDouble();
double annualInterestRate = input.nextDouble();
// Calculate the interest
double interest = balance * (annualInterestRate / 1200);
// Display result
System.out.println("The interest is " + interest);
برنامج يحسب المسافة بين نقطتين:
/*
(Geometry: distance of two points) Write a program that prompts the user to enter
two points (x1, y1) and (x2, y2) and displays their distance between them.
*/
import java.util.Scanner;
public class Exercise_02_15 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two points
System.out.print("Enter x1 and y1: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
System.out.print("Enter x2 and y2: ");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
// Calucate the distance between the two points
double distance = Math.pow(Math.pow(x2 - x1, 2) +
Math.pow(y2 - y1, 2), 0.5);
// Display result
System.out.println("The distance between the two points is " + distance);
}
}
برنامج يحسب طول المدرج بناءا على تسارع الطائرة:
/*
(Physics: finding runway length) Given an airplane’s acceleration a and take-off
speed v, you can compute the minimum runway length needed for an airplane to
take off using the following formula:
v^2
length = ---
2a
Write a program that prompts the user to enter v in meters/second (m/s) and the
acceleration a in meters/second squared (m/s2), and displays the minimum runway
length.
*/
import java.util.Scanner;
public class Exercise_02_12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create new Scanner object.
// Prompt user to enter the airplane's acceleration a and take-off spead v.
System.out.print("Enter speed and acceleration: ");
double speed = input.nextDouble();
double acceleration = input.nextDouble();
// Compute the minimum runway length
// needed for an airplane to take off.
double length = Math.pow(speed, 2) / (2 * acceleration);
// Display result
System.out.println("The minimum runway length for this" +
" airplane is " + length);
}
}
مثال اخر :
/*
(Population projection) Rewrite Programming Exercise 1.11 to prompt the user
to enter the number of years and displays the population after the number of years.
Use the hint in Programming Exercise 1.11 for this program. The population
should be cast into an integer. Here is a sample run of the program:
*/
import java.util.Scanner;
public class Exercise_02_11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create a Scanner object
// Prompt the user to the number of years
System.out.print("Enter the number of years: ");
int years = input.nextInt();
// Calculate population projection
int population = 312032486 + (((31536000 / 7) - (31536000 / 13)
+ (31536000 / 45)) * years);
// Display the results
System.out.println("The population in " + years + " is " + population);
}
}
برنامج طبي لحساب معادل ال BMI:
/*
(Health application: computing BMI) Body Mass Index (BMI) is a measure of
health on weight. It can be calculated by taking your weight in kilograms and
dividing by the square of your height in meters. Write a program that prompts the
user to enter a weight in pounds and height in inches and displays the BMI. Note
that one pound is 0.45359237 kilograms and one inch is 0.0254 meters.
*/
import java.util.Scanner;
public class Exercise_02_14 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final double KILOGRAMS_PER_POUND = 0.45359237;
final double METERS_PER_INCH = 0.0254;
// Prompt the user to enter a weight in pounds
System.out.print("Enter weight in pounds: ");
double weight = input.nextDouble();
// Prompt the user to enter height in inches
System.out.print("Enter height in inches: ");
double height = input.nextDouble();
// Convert weight to kilograms
weight = weight * KILOGRAMS_PER_POUND;
// Convert height to meters
height = height * METERS_PER_INCH;
// Compute BMI
double bodyMassIndex = weight / Math.pow(height, 2);
// Display result
System.out.println("BMI is " + bodyMassIndex);
}
}
برنامج يطلب من المستخدم ادخال قيم 3 نقاط تشكل مثلث ومن ثم يحسب ويطبع مساحة المثلث:
/*
(Geometry: area of a triangle) Write a program that prompts the user to enter
three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.
*/
import java.util.Scanner;
public class Exercise_02_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter three points
System.out.print("Enter three points for a triangle: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double x3 = input.nextDouble();
double y3 = input.nextDouble();
// Compute the area of a triangle
double side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
double side2 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
double side3 = Math.pow(Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2), 0.5);
double s = (side1 + side2 + side3) / 2;
double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
// Display result
System.out.println("The area of the triangle is " + area);
}
}
مثال على استخدام المتغيرات وعمليات الادخال والطباعة:
/*
(Science: wind-chill temperature) How cold is it outside? The temperature alone
is not enough to provide the answer. Other factors including wind speed, relative
humidity, and sunshine play important roles in determining coldness outside.
In 2001, the National Weather Service (NWS) implemented the new wind-chill
temperature to measure the coldness using temperature and wind speed. The
formula is
twc = 35.74 + 0.6215ta - 35.75v^0.16 + 0.4275tav^0.16
where ta is the outside temperature measured in degrees Fahrenheit and v is the
speed measured in miles per hour. twc is the wind-chill temperature. The formula
cannot be used for wind speeds below 2 mph or temperatures below -58 ºF or
above 41ºF.
Write a program that prompts the user to enter a temperature between -58 ºF and
41ºF and a wind speed greater than or equal to 2 and displays the wind-chill temperature.
Use Math.pow(a, b) to compute v0.16
*/
import java.util.Scanner;
public class Exercise_02_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and
// 41F and a wind speed greater than or equal to 2.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58ºF and 41ºF: ");
double temperature = input.nextDouble();
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
double speed = input.nextDouble();
// Compute the wind chill index
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed, 0.16) +
0.4275 * temperature * Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill index is " + windChill);
}
}
(Science: calculating energy) Write a program that calculates the energy needed
to heat water from an initial temperature to a final temperature. Your program
should prompt the user to enter the amount of water in kilograms and the initial
and final temperatures of the water. The formula to compute the energy is
Q = M * (finalTemperature – initialTemperature) * 4184
where M is the weight of water in kilograms, temperatures are in degrees Celsius,
and energy Q is measured in joules.
/*
(Science: calculating energy) Write a program that calculates the energy needed
to heat water from an initial temperature to a final temperature. Your program
should prompt the user to enter the amount of water in kilograms and the initial
and final temperatures of the water. The formula to compute the energy is
Q = M * (finalTemperature – initialTemperature) * 4184
where M is the weight of water in kilograms, temperatures are in degrees Celsius,
and energy Q is measured in joules.
*/
import java.util.Scanner;
public class Exercise_02_10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create new Scanner object.
// Prompt the user to enter the amount of water in kilograms.
System.out.print("Enter the amount of water in kilograms: ");
double kilograms = input.nextDouble();
// Prompt the user to enter the initial temperature.
System.out.print("Enter the initial temperature: ");
double initialTemperature = input.nextDouble();
// Prompt the user to enter the final temperature.
System.out.print("Enter the final temperature: ");
double finalTemperature = input.nextDouble();
// Calculate the energy
double energy = kilograms * (finalTemperature - initialTemperature) * 4184;
// Display result
System.out.println("The energy needed is " + energy);
}
}
(Physics: acceleration) Average acceleration is defined as the change of velocity
divided by the time taken to make the change, as shown in the following formula:
v1 - v0
a = ---------
t
Write a program that prompts the user to enter the starting velocity v0 in meters/
second, the ending velocity v1 in meters/second, and the time span t in seconds,
and displays the average acceleration.
/*
(Physics: acceleration) Average acceleration is defined as the change of velocity
divided by the time taken to make the change, as shown in the following formula:
v1 - v0
a = ---------
t
Write a program that prompts the user to enter the starting velocity v0 in meters/
second, the ending velocity v1 in meters/second, and the time span t in seconds,
and displays the average acceleration.
*/
import java.util.Scanner;
public class Exercise_02_09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create a Scanner object
// Prompt the user to enter the starting velocity v0 in meters/second.
// The ending velocity v1 in meters/second, and the time span t in seconds.
System.out.print("Enter v0, v1 and t: ");
double v0 = input.nextDouble();
double v1 = input.nextDouble();
double t = input.nextDouble();
// Calculate the average acceleration
double a = (v1 - v0) / t;
// Display result
System.out.println("The average acceleration is " + a);
}
}
(Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays
the current time in GMT. Revise the program so that it prompts the user to enter
the time zone offset to GMT and displays the time in the specified time zone.
/*
(Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays
the current time in GMT. Revise the program so that it prompts the user to enter
the time zone offset to GMT and displays the time in the specified time zone.
*/
import java.util.Scanner;
public class Exercise_02_08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create new Scanner object
// Prompt user to enter the time offset of GMT
System.out.print("Enter the time zone offset to GMT: ");
int offset = input.nextInt();
// Obtain the total milliseconds since midnight, Jan 1, 1970
long totalMilliseconds = System.currentTimeMillis();
// Obtain the total seconds since midnight, Jan 1, 1970
long totalSeconds = totalMilliseconds / 1000;
// Compute the current second in the minute in the hour
long currentSecond = totalSeconds `;
// Obtain the total minutes
long totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
long currentMinute = totalMinutes `;
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
long currentHour = totalHours $;
currentHour = currentHour + offset;
// Display results
System.out.println("Current time is " + currentHour + ":"
+ currentMinute + ":" + currentSecond);
}
}
(Find the number of years) Write a program that prompts the user to enter the
minutes (e.g., 1 billion), and displays the number of years and days for the minutes.
For simplicity, assume a year has 365 days. Here is a sample run:
/*
(Find the number of years) Write a program that prompts the user to enter the
minutes (e.g., 1 billion), and displays the number of years and days for the minutes.
For simplicity, assume a year has 365 days. Here is a sample run:
*/
import java.util.Scanner;
public class Exercise_02_07 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter the number of minutes
System.out.print("Enter the number of minutes: ");
int minutes = input.nextInt();
// Compute the number of years and days
int years = minutes / 525600;
int days = (minutes R5600) / 1440;
// Display results
System.out.println(minutes + " minutes is approximately " + years
+ " years and " + days + " days");
}
}
(Sum the digits in an integer) Write a program that reads an integer between 0 and
1000 and adds all the digits in the integer. For example, if an integer is 932, the
sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the
extracted digit. For instance, 932 = 2 and 932 / 10 = 93.
/*
(Sum the digits in an integer) Write a program that reads an integer between 0 and
1000 and adds all the digits in the integer. For example, if an integer is 932, the
sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the
extracted digit. For instance, 932 = 2 and 932 / 10 = 93.
*/
import java.util.Scanner;
public class Exercise_02_06 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create new Scanner object
// Prompt the user to enter a number between 0 and 1000.
System.out.print("Enter a number between 0 and 1000: ");
int number = input.nextInt();
// Compute the sum of the digits in the integer.
int lessThan10 = number ; // Extract the digit less than 10
number /= 10; // Remove the extracted digit
int tens = number ; // Extract the digit between 10 to 99
number /= 10; // Remove the extracted digit
int hundreds = number ; // Extract the digit between 100 to 999
number /= 10; // Remove the extracted digit
int sum = hundreds + tens + lessThan10;
// Display results
System.out.println("The sum of the digits is " + sum);
}
}
(Financial application: calculate tips) Write a program that reads the subtotal
and the gratuity rate, then computes the gratuity and total. For example, if the
user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5
as gratuity and $11.5 as total.
/*
(Financial application: calculate tips) Write a program that reads the subtotal
and the gratuity rate, then computes the gratuity and total. For example, if the
user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5
as gratuity and $11.5 as total.
*/
import java.util.Scanner;
public class Exercise_02_05 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // Create new Scanner object.
// Prompt the user to enter the subtotal and the gratuity rate
System.out.print("Enter the subtotal and a gratuity rate: ");
double subtotal = in.nextDouble();
double gratuityRate = in.nextDouble();
// Calculate gratuity and total
double gratuity = subtotal * (gratuityRate / 100);
double total = subtotal + gratuity;
// Display results
System.out.println("The gratuity is $" + gratuity +
" and total is $" + total);
}
}
برنامج يطلب من المستخدم ادخال الاسم الاول والكنية ويطبع الاسم الكامل:
package javaapplication10;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first name");
System.out.println("enter 2ed name");
String firstname=input.next();
char firstch= firstname.charAt(0);
System.out.println(firstch+" first ch");
int len = firstname.length();
System.out.println("length "+len);
}
}
مثال برنامج يقوم بحساب مجموع قيم رتب الاحاد والعشرات والمئات للرقم:
/*(Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
*/
System.out.println("Enter a number between 0 and 1000:");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
System.out.println(number);
int sum=number%10;
System.out.println(sum);
number=number/10;
System.out.println(number);
sum=sum+number%10;
System.out.println(sum);
number=number/10;
System.out.println(number);
sum=sum+number%10;
System.out.println(sum);
طباعة جدول يوضح نتائج حساب القوة للعدد:
/*(Print a table) Write a program that displays the following table. Cast floating point numbers into integers.
a b pow(a, b)
1 2 1
2 3 8
3 4 81
4 5 1024
5 6 15625
*/
System.out.println("a b pow(a, b)");
System.out.println("1 2 "+(int)Math.pow(1, 2));
System.out.println("2 3 "+(int)Math.pow(2, 3));
System.out.println("3 4 "+(int)Math.pow(3, 4));
System.out.println("4 5 "+(int)Math.pow(4, 5));
System.out.println("5 6 "+(int)Math.pow(5, 6));
برنامج يقوم بحساب مساحة المثلث:
/*(Geometry: area of a triangle) Write a program that prompts the user to enter
three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.
The formula for computing the area of a triangle is:
s = (side1 + side2 + side3)/2
area = squareroot(s(s - side1)(s - side2)(s - side3))
note: "side" is refers to the distance between 2 points
*/
Scanner input = new Scanner(System.in);
// Prompt the user to enter two points
System.out.print("Enter x1 and y1: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
System.out.print("Enter x2 and y2: ");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
System.out.print("Enter x3 and y3: ");
double x3 = input.nextDouble();
double y3 = input.nextDouble();
double side1=Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
double side2=Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
double side3=Math.pow(Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2), 0.5);
double s=(side1 + side2 + side3)/2;
double area = Math.pow(s*(s - side1)*(s - side2)*(s - side3),0.5);
System.out.println("The area of the triangle is "+area);