سؤال 4 في Lab4:
Write a program which asks the user to enter their marital status, corresponding to a letter input. married = 'm', single = 's', divorced = 'd' , widowed = 'w'
When the user enters the letter, their corresponding status should be printed to the screen. If the user enters anything other than m,s,d, or w the message "Invalid Code" should be printed.
في هذا السؤال طلب إنك تكتب برنامج يقوم بسؤال المستخدم عن حالته الزوجية (متزوج، عازب، مطلق، أرمل) ومن ثم تجعل البرنامج يطبع حالته الزوجية على الشاشة ( الكونسول )، ورمز لكل حالة من الحالات بحرف:
متزوج = m، عازب = s، مطلق = d، أرمل = w، إذا قام المستخدم بإدخال قيم غير هذه القيم يظهر على الشاشة Invalid Code.
خطوات الحل:
1- أولاً نقوم بتعريف المتغير الذي سندخل عليه القيم ( لنفرض status )، ولكن يجب تعريفه على أنه String وليس char (لماذا؟) الجواب في الخطوة رقم 3
2- نستخدم السكانر لإدخال القيم إلى status
3- أنا استخدمت الـString لأنه لا يمكن إدخال حرف char باستخدام السكانر، فأدخلته باستخدام String وعملت له Casting إلى char ،،
4- نقوم بعمل Loop في حالة إذا كان المستخدم أدخل قيمة خاطئة ( while )
5- وفي الأخير استخدمت if statements لطباعة الحالات الموجودة، إذا ادخل حرف m يطلع متزوج، وإذا ادخل حرف s يطلع عازب وإذا أدخل حرف d يطلع مطلق واذا ادخل حرف w يطلع ارمل،
السورس كود:
كود PHP:
package lab4;
import java.util.*;
/
*
* @author deathpa1N
*/
public class Lab4 {
public static void main(String[] args) {
String status;
Scanner input=new Scanner(System.in);
System.out.println("Enter m for Married, s for Single, d for Divorced, and w for Widowed: ");
status = input.next();
char marital = status.charAt(0);
while (marital !='m' && marital !='s' && marital !='d' && marital !='w'){
System.out.println("Invalid Code");
System.out.println("Enter m for Married, s for Single, d for Divorced, and w for Widowed: ");
status = input.next();
marital = status.charAt(0);}
if (marital=='m')
System.out.println("Your Marital Status: Married");
else if (marital=='s')
System.out.println("Your Marital Status: Single");
else if (marital=='d')
System.out.println("Your Marital Status: Divocred");
else if (marital=='w')
System.out.println("Your Marital Status: Widowed");}
}
وسلامتكم، اذا في نقاط مو واضحة الرجاء تنبيهي لإعادة شرحها بالتفصيل