0% found this document useful (0 votes)
17 views

(17170908) JAVA - Practice 1

Here is a nested for loop that prints the pattern: ```java for(int i=1; i<=5; i++) { for(int j=1; j<=i; j++) { System.out.print("*"); } System.out.println(); } ``` This will print: * ** *** **** ***** The outer for loop iterates 5 times, for each row. The inner for loop iterates from 1 to i, where i is the current row number. This prints one more * each row, building the triangle pattern. After each inner loop completes, it prints a new line to go to the next row.

Uploaded by

DASMION SKHS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

(17170908) JAVA - Practice 1

Here is a nested for loop that prints the pattern: ```java for(int i=1; i<=5; i++) { for(int j=1; j<=i; j++) { System.out.print("*"); } System.out.println(); } ``` This will print: * ** *** **** ***** The outer for loop iterates 5 times, for each row. The inner for loop iterates from 1 to i, where i is the current row number. This prints one more * each row, building the triangle pattern. After each inner loop completes, it prints a new line to go to the next row.

Uploaded by

DASMION SKHS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

NAME: MD TASNIM KHAN

ID: 17170908

DATE: 4 DEC 2019

Problem 1:

A program that prompts the user to enter a letter and displays its corresponding number.

Source code:

package practice1;

import java.util.Scanner;

public class LetterNumber {

public static void main(String args[]) {

Scanner input = new Scanner(System.in);

// Prompt the user to enter a letter

System.out.print("Enter a letter: ");

String s = input.nextLine();

char ch = s.charAt(0);

ch = Character.toUpperCase(ch);

// Display its corresponding number

int number = 0;

if (Character.isLetter(ch)) {
if (ch >= 'W') {

number = 9;

} else if (ch >= 'T') {

number = 8;

} else if (ch >= 'P') {

number = 7;

} else if (ch >= 'M') {

number = 6;

} else if (ch >= 'J') {

number = 5;

} else if (ch >= 'G') {

number = 4;

} else if (ch >= 'D') {

number = 3;

} else if (ch >= 'A') {

number = 2;

System.out.println("The corresponding number is " + number);

} else {

System.out.println(ch + " is an invalid input");

Input:

1. Enter a letter: X
2. Enter a letter: h

Output:

1. The corresponding number is 9


2. The corresponding number is 4
Run Screenshot:
Problem 2:

A program that prompts the user to enter two characters and displays the major and status represented in
the characters.
The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates
whether a student is a freshman, sophomore, junior, or senior.

Source code:

package practice1;

import java.util.Scanner;

public class StudentMajorAndStatus {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);

System.out.print("Enter two characters: ");


String status = in.next();

char major = Character.toUpperCase(status.charAt(0));


char year = status.charAt(1);

String courseName = "";


String yearName = "";

if (major == 'M' || major == 'I' || major == 'C') {


switch (major) {
case 'M':
courseName = "Mathematics";
break;
case 'C':
courseName = "Computer Science";
break;
case 'I':
courseName = "Information Technology";
break;
default:
break;
}

switch (year) {
case '1':
yearName = "Freshman";
break;
case '2':
yearName = "Sophmore";
break;
case '3':
yearName = "Junior";
break;
case '4':
yearName = "Senior";
break;
default:
break;
}
System.out.printf("%s %s%n", courseName, yearName);
} else {
System.out.printf("Invalid input.%n");
}
}
}

Input:

1. Enter two characters: M2


2. Enter two characters: c4

Output:

1. Mathematics Sophomore
2. Computer Science Senior
Run Screenshot:
Problem 3:

A program that prompts the user to enter three cities and displays them in ascending order.

Source code:

package practice1;

import java.util.Scanner;

public class OrderThreeCities {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Prompt the user to enter three cities

System.out.print("Enter the first city: ");

String city1 = input.nextLine();

System.out.print("Enter the second city: ");

String city2 = input.nextLine();

System.out.print("Enter the third city: ");

String city3 = input.nextLine();

String temp;

if ((city2.compareTo(city1) < 0) && (city2.compareTo(city3) < 0)) {

temp = city1;

city1 = city2;

city2 = temp;

} else if ((city3.compareTo(city1) < 0) && (city3.compareTo(city2) < 0)) {

temp = city1;

city1 = city3;

city3 = temp;
}

if (city3.compareTo(city2) < 0) {

temp = city2;

city2 = city3;

city3 = temp;

// Display cities in ascending order

System.out.println("The three cities in alphabetical order are "

+ city1 + " " + city2 + " " + city3);

Input:

Enter the first city: Dhaka


Enter the second city: Hangzhou
Enter the third city: Beijing

Output:

The three cities in alphabetical order are - Beijing, Dhaka, Hangzhou


Run Screenshot:
Problem 4:

A program that reads an unspecified number of integers, determines how many positive and negative
values have been read, and computes the total and average of the input values (not counting zeros). Your
program ends with the input 0. Display the average as a floating-point number.

Source code:

package practice1;

import java.util.Scanner;

public class CountingPositiveNegativeAverage {

public static void main(String[] args) {


// Display the instruction
System.out.println(
"Enter an int value, the program exits if the input is 0");
// Create a Scanner
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int positive = 0; // the number of positive integer
int negative = 0; // the number of negative integer
int total = 0; // the number of number entered
double sum = 0.0; // the sum of all the integers

// While the number is not 0


while (number != 0) {
// Count the positive
if (number > 0) {
positive++;
} // Count the negative
else {
negative++;
}
// Count the total
total++;
sum += number;

number = input.nextInt();
}

// Compute the total and the average


double average = sum / total;

System.out.println("The number of positives is " + positive);


System.out.println("The nubmer of negatives is " + negative);
System.out.println("The total is " + total);
System.out.println("The average is " + average);
}
}

Input:

Output:

The average is -6.333333333333333


Run Screenshot:

Problem 5:

Homework 2.3, SubtractionQuizLoop.java generates five random subtraction questions. Revise the
program to generate ten random addition questions for two integers between 1 and 15. Display the correct
count and test time.

Source code:

package practice1;

import java.util.Scanner;

public class SubtractionQuizLoop {


public static void main(String[] args) {

final int NUMBER_OF_QUESTIONS = 10; // Number of questions

int correctCount = 0; // Count the nubmer of correct answers

int count = 0; // Count the number of questions

long startTime = System.currentTimeMillis();

String output = " "; // output string is initially empty

Scanner input = new Scanner(System.in);

while (count < NUMBER_OF_QUESTIONS) {

// 1. Generate two random single-digit integers

int number1 = 1 + (int) (Math.random() * 15);

int number2 = 1 + (int) (Math.random() * 15);

// 2. Prompt the student to answer "What is number1 + number2?"

System.out.print(

"What is " + number1 + " + " + number2 + "? ");

int answer = input.nextInt();

// 3. Grade the answer and display the result

if (number1 + number2 == answer) {

System.out.println("You are correct!");

correctCount++; // Increase the correct answer count

} else {

System.out.println("Your answer is wrong.\n" + number1

+ " + " + number2 + " should be " + (number1 + number2));

// Increase the question count

count++;

output += "\n" + number1 + "+" + number2 + "=" + answer


+ ((number1 + number2 == answer) ? " correct" : " wrong");

long endTime = System.currentTimeMillis();

long testTime = endTime - startTime;

System.out.println("Correct count is " + correctCount

+ "\nTest time is " + testTime / 1000 + " seconds\n" + output);

Input:

What is 3 + 14? 17
What is 3 + 12? 19
What is 8 + 12? 20
What is 14 + 7? 21
What is 15 + 14? 30
What is 15 + 14? 29
What is 3 + 15? 16
What is 10 + 5? 76
What is 13 + 5? 23
What is 4 + 13? 17

Output:

What is 3 + 14? 17
You are correct!
What is 3 + 12? 19
Your answer is wrong.
3 + 12 should be 15
What is 8 + 12? 20
You are correct!
What is 14 + 7? 21
You are correct!
What is 15 + 14? 30
Your answer is wrong.
15 + 14 should be 29
What is 15 + 14? 29
You are correct!
What is 3 + 15?
16
Your answer is wrong.
3 + 15 should be 18
What is 10 + 5? 76
Your answer is wrong.
10 + 5 should be 15
What is 13 + 5? 23
Your answer is wrong.
13 + 5 should be 18
What is 4 + 13? 17
You are correct!
Correct count is 5
Test time is 403 seconds

3+14=17 correct
3+12=19 wrong
8+12=20 correct
14+7=21 correct
15+14=30 wrong
15+14=29 correct
3+15=16 wrong
10+5=76 wrong
13+5=23 wrong
4+13=17 correct

BUILD SUCCESSFUL (total time: 6 minutes 43 seconds)

Run Screenshot:
Problem 6:

Write a nested for loop that prints the following output:

Source code:

package practice1;

public class PyramidPattern {

public static void main(String[] args) {

// Init

int row = 0;

int maxRows = 8;

int num = 1;

int indent = maxRows - 1;

// Printing loop

while (row < maxRows) {

// Indent

for (int i = 0; i < indent; ++i) {


System.out.print(" ");

// Print nums

for (int i = 0; i < num; ++i) {

System.out.printf("%4d", (int) Math.pow(2.0, i));

for (int i = num - 2; i >= 0; --i) {

System.out.printf("%4d", (int) Math.pow(2.0, i));

// New line

System.out.println("");

// Adjustments

++row;

--indent;

++num;

Output:

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Run Screenshot:
Problem 7:

To display all the prime numbers between 2 and 1,000, inclusive. Display eight prime numbers per line.
Numbers are separated by exactly one space.

Source code:

package practice1;

public class PrimeNumbers {

public static void main(String[] args) {

final int NUMBER_OF_PRIMES_PER_LINE = 8; // Display 8 per line

int count = 0; // Count the number of prime numbers

System.out.println(

"The prime numbers between 2 and 1,000, inclusive are \n");

// Repeatedly find prime numbers

for (int number = 2; number <= 1000; number++) {

// Assume the number is prime

boolean isPrime = true; // Is the current number prime?

// Test whether number is prime

for (int divisor = 2; divisor <= number / 2; divisor++) {

if (number % divisor == 0) { // If true, number is not prime

isPrime = false; // Set isPrime to false

break; // Exit the for loop

}
// Display the prime number and increase the count

if (isPrime) {

count++; // Increase the count

if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {

// Display the number and advance to the new line

System.out.println(number);

} else {

System.out.print(number + " ");

Output:

The prime numbers between 2 and 1,000, inclusive are

2 3 5 7 11 13 17 19
23 29 31 37 41 43 47 53
59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131
137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263
269 271 277 281 283 293 307 311
313 317 331 337 347 349 353 359
367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457
461 463 467 479 487 491 499 503
509 521 523 541 547 557 563 569
571 577 587 593 599 601 607 613
617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719
727 733 739 743 751 757 761 769
773 787 797 809 811 821 823 827
829 839 853 857 859 863 877 881
883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
Run Screenshot:
Problem 8:

A program that prompts the user to enter the year and first day of the year and displays the calendar table
for the year on the console.

Source code:

package practice1;

import java.util.Scanner;

public class DisplayCalendars {

public static void main(String[] strings) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a year: ");


int year = input.nextInt();

System.out.print("Enter the first day of the year: ");


int startDay = input.nextInt();

int numberOfDaysInMonth = 0;
for (int month = 1; month <= 12; month++) {
System.out.print(" ");
switch (month) {
case 1:
System.out.println("January " + year);
numberOfDaysInMonth = 31;
break;
case 2:
System.out.println("February " + year);
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
numberOfDaysInMonth = 29;
} else {
numberOfDaysInMonth = 28;
}
break;
case 3:
System.out.println("March " + year);
numberOfDaysInMonth = 31;
break;
case 4:
System.out.println("April " + year);
numberOfDaysInMonth = 30;
break;
case 5:
System.out.println("May " + year);
numberOfDaysInMonth = 31;
break;
case 6:
System.out.println("June " + year);
numberOfDaysInMonth = 30;
break;
case 7:
System.out.println("July " + year);
numberOfDaysInMonth = 31;
break;
case 8:
System.out.println("August " + year);
numberOfDaysInMonth = 31;
break;
case 9:
System.out.println("September " + year);
numberOfDaysInMonth = 30;
break;
case 10:
System.out.println("October " + year);
numberOfDaysInMonth = 31;
break;
case 11:
System.out.println("November " + year);
numberOfDaysInMonth = 30;
break;
case 12:
System.out.println("December " + year);
numberOfDaysInMonth = 31;
}
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

for (int i = 0; i < startDay; i++) {


System.out.print(" ");
}
for (int i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10) {
System.out.print(" " + i);
} else {
System.out.print(" " + i);
}
if ((i + startDay) % 7 == 0) {
System.out.println();
}
}
System.out.println("");

startDay = (startDay + numberOfDaysInMonth) % 7;


}
}

}
Input:

Enter a year: 2019


Enter the first day of the year: 2

Output:
Run Screenshot:
Problem 9:

Decimal to binary and Decimal to octal:


(Decimal to binary) A program that prompts the user to enter a decimal integer and displays its
corresponding binary value.
(Decimal to octal) A program that prompts the user to enter a decimal integer and displays its
corresponding octal value.

Source code: (Decimal to binary)

package practice1;

import java.util.Scanner;

public class DecimalToBinary {

public static void main(String[] args) {


// Create Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to enter a decimal integer


System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();

// Convert the decimal number to a binary number


String binary = ""; // Holds the binary value
for (int i = decimal; i > 0; i /= 2) {
binary = (i % 2) + binary;
}

// Display the corresponding binary value of the decimal integer


System.out.println(
"The binary value of the decimal \"" + decimal + "\" is: " + binary);
}
}
Source code: (Decimal to octal)

package practice1;

import java.util.Scanner;

public class DecimalToOctal {

public static void main(String[] args) {


Scanner input = new Scanner(System.in); // Create a Scanner

// Prompt the user to enter a decimal integer


System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();

// Convet decimal to octal


String octal = ""; // Hold octal value
for (int i = decimal; i > 0; i /= 8) {
octal = i % 8 + octal;
}

// Display results
System.out.println("The octal of " + decimal + " is " + octal);
}
}

Input:

Enter a decimal integer: 2 (Decimal to binary)

Enter a decimal integer: 23 (Decimal to octal)

Output:

The binary value of the decimal "2" is: 10 (Decimal to binary)

The octal of 23 is 27 (Decimal to octal)


Run Screenshot:

(Decimal to binary)

(Decimal to octal)
Problem 10:

A program that prompts the user to enter two strings and displays the largest common prefix of the two
strings.

Source code:

package practice1;

import java.util.Scanner;

public class LongestCommonPrefix {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Prompt the user to enter two strings

System.out.print("Enter the first string: ");

String string1 = input.nextLine();

System.out.print("Enter the second string: ");

String string2 = input.nextLine();

int index = 0; // Initialize index to 0

String prefix = ""; // Initialize prefix as empty string

// Get the largest common prefix of the two strings

while (string1.charAt(index) == string2.charAt(index)) {

prefix += string1.charAt(index);

index++;

// Display the result


if (prefix.length() > 0) {

System.out.println("The common prefix is " + prefix);

} else {

System.out.println(string1 + " and " + string2

+ " have no common prefix");

Input:

Enter the first string: Mohammad


Enter the second string: Tasnim

Enter the first string: Welcome Bangladesh


Enter the second string: Welcome China

Output:

Mohammad and Tasnim have no common prefix

The common prefix is Welcome


Run Screenshot:
Summary

To do all these program, I faced many problems but I solved that by myself. These kind of exercise will
help us to improve our skills.
Finally, I want to say that, I enjoyed a lot to solve all these problem.

You might also like