Sei sulla pagina 1di 4

MIS 202 – Introduction to Programming Exercise sheet 1

EXERCISE SHEET 1
Ex1. Write a Java program to print your name and age in two separate lines.

Solution:

public class Exercise1

public static void main(String args[])

System.out.println(“My name is Ahmed Mohamed”);

System.out.println(“I am 22 years old”);

Another Solution:

public class Exercise1

public static void main(String args[])

System.out.println(“My name is” + “ Ahmed Mohamed”);

System.out.println(“I am” +” 22”+” years old”);

Page 1 of 4
MIS 202 – Introduction to Programming Exercise sheet 1

Another Solution:

public class Exercise1

public static void main(String args[])

int number1 = 22

System.out.printf(“%s %s”, “My name is” , “ Ahmed Mohamed”);

System.out.printf( “%s%d %s”, “I am” + number1+” years old”);

Ex2. Write a Java program to display the asterisk pattern as shown below:

*****

*****

*****

*****

*****

Solution:

public class Exercise2

public static void main(String[] args)

System.out.println("*****");

System.out.println("*****");

Page 2 of 4
MIS 202 – Introduction to Programming Exercise sheet 1

System.out.println("*****");

System.out.println("*****");

System.out.println("*****");

Ex3. Write a Java program to display a diamond shape with asterisks.

Solution 1:

public class Exercise3 //this exercise will display an empty diamond

public static void main(String args[])

System.out.println(“ * “);

System.out.println(“ * * “);

System.out.println(“* *“);

System.out.println(“ * * “);

System.out.println(“ * “);

Solution 2:

public class Exercise3 //this exercise will display a full diamond

public static void main(String args[])

System.out.println(“ * “);

Page 3 of 4
MIS 202 – Introduction to Programming Exercise sheet 1

System.out.println(“ *** “);

System.out.println(“*****“);

System.out.println(“ *** “);

System.out.println(“ * “);

Ex4. Use escape characters to print your name, ID, and the course’s name is a box, which should look
like this:

Suggested Solution: (there are other ways to solve this problem.. you don’t necessarily have to use the
\t escape character)
public class Exercise4
{
public static void main(String args[])
{
System.out.println( "+-----------------------+" );
System.out.println( "|\t\t\t\t\t\t|" );
System.out.println( "|\tAhmed Mohamed\t\t|" );
System.out.println( "|\t\t\t\t\t\t|" );
System.out.println( "|\t20151234\t\t\t|" );
System.out.println( "|\t\t\t\t\t\t|" );
System.out.println( "|\tJava Programming\t|" );
System.out.println( "+-----------------------+" );
}
}

Page 4 of 4

Potrebbero piacerti anche