0% found this document useful (0 votes)
2 views10 pages

Java Assignment With Codes

Uploaded by

Sania Nowshin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Java Assignment With Codes

Uploaded by

Sania Nowshin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

Given array: numbers[] = {11,7,2,15,6}


Find out the difference between the max and second max value. Output: 4
public class DifferenceMaxToSecondMax {
public static void main(String[] args){
int array[] = {11,7,2,15,6};
int max = findMax(array);
int sMax = findsMax(array);
System.out.println(max);
System.out.println(sMax);
int diff = max-sMax;
System.out.println("Difference Between max and second max:
"+diff);

}
public static int findMax(int[] array){
int max =array[0];
for (int i=0; i<array.length; i++){
if(array[i]>max){
max = array[i];
}
}
return max;
}
public static int findsMax(int[] array){
int max =array[0];
int sMax = array[0];
for (int i=0; i<array.length; i++){
if(array[i]>max){
sMax = max;
max = array[i];
}
else if (array[i]>sMax && array[i]!=max){
sMax=array[i];
}
}
return sMax;
}
}
2. Given array: numbers[] = {11,7,2,15,6}
In the above array, sum of the prime numbers only. Output: 20
public class SumOfPrimeNumbers {
public static void main(String[] args) {
int numbers[] = {11,7,2,15,6};
Boolean isPrime = true;
int sum = 0;
for(int i = 0; i< numbers.length; i++){
int num = numbers[i];
if(num<2){
continue;
}
for (int j=2; j<num; j++){
if(num%j==0){
isPrime = false;
}
}
if(isPrime){
sum +=num;
}
}
System.out.println(sum);
}
}

3. Given array: numbers[] = {11,7,7, 11, 2,15, 6, 6}


Remove the duplicate values and then sum of the unique digits only. Output: 41
public class RemoveDuplicate {
public static void main(String[] args) {
int numbers[] = {11, 7, 7, 11, 2, 15, 6, 6};
LinkedHashSet<Integer> hashSet = new LinkedHashSet();
int sum = 0;
for (int num : numbers) {
hashSet.add(num);
}
for(int unique : hashSet){
sum += unique;
}
System.out.println(sum);
}
}
4. Find the missing number from this array {0,1,2,4,5}.
Formula: n(n+1)/2 - sum(array). Output: 3
public class FindMissingNumberUsingFormula {
public static void main(String[] args) {
int array[] = {0,1,2,4,5};
int sum_of_array =0;
for(int i=0; i< array.length; i++){
sum_of_array +=array[i];
}
int n = array.length;
int output = (n*(n+1))/2 - sum_of_array;
System.out.println(output);
}
}

5. numbers[]={1,2,2,3,3,3,4,4,4,4}. Count the occurrence of each digit:


public class FrequencyOfDigits {
public static void main(String[] args) {
int numbers[]={1,2,2,3,3,3,4,4,4,4};
HashMap<Integer,Integer> hashMap = new HashMap();
for(int n:numbers){
hashMap.put(n, hashMap.getOrDefault(n, 0)+1);
}
System.out.println(hashMap);
}
}
6. numbers[] = {1,2,3,4,4,5,6,6, 7}. Return only the repetitive digits.
Output: 4,6
public class RepetitiveDigits {
public static void main(String[] args) {
int numbers[] = {1, 2, 3, 4, 4, 5, 6, 6, 7};
for (int i = 0; i < numbers.length; i++){
for (int j = i+1; j < numbers.length; j++){
if(numbers[i]==numbers[j]){
System.out.print(numbers[i]+" ");
}
}
}
}
}

7. Input string: "abcaabbcc"


Print all unique characters and their total count.
Output:Unique characters: a, b, c , Total unique characters: 3
public class UniqueCharAndCount {
public static void main(String[] args) {
String str ="abcaabbcc";
char ch[] = str.toCharArray();
LinkedHashSet<Character> hashSet = new LinkedHashSet();
int count = 0;
for(char c:ch){
hashSet.add(c);
}
System.out.println(hashSet);
System.out.println(hashSet.size());
}
}
8. Input string: "cat", Print all possible permutations of the string and count them.
Output: Permutations: cat, cta, act, atc, tac, tca | Total permutations: 6
public class PermutationOfString {
public static void main(String[] args) {
String str = "cat";
char[] chars = str.toCharArray();
int count = 0;
// Loop for the first character position
for (int i = 0; i < chars.length; i++) {
// Loop for the second character position
for (int j = 0; j < chars.length; j++) {
if (j == i) continue; // Skip if same as
the first character
// Loop for the third character position
for (int k = 0; k < chars.length; k++) {
if (k == i || k == j) continue; // Skip if
same as first or second character

// Print the permutation


System.out.println("" + chars[i] + chars[j] +
chars[k]);
count++;
}
}
}
System.out.println("Total permutations: " + count);
}
}

9. Generate a random password with the following rules:


Must be 8 characters long, Must include at least:

(One uppercase letter, One lowercase letter, One numeric digit, One special character)
public class RandomPasswordGenerate {
public static void main(String[] args) {
String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower = "abcdefghijklmnopqrstuvwxyz";
String digits = "0123456789";
String special = "!@#$%&";

Random random = new Random();

ArrayList<Character> passwordChars = new ArrayList();

passwordChars.add(upper.charAt(random.nextInt(upper.length())));

passwordChars.add(lower.charAt(random.nextInt(lower.length())));

passwordChars.add(digits.charAt(random.nextInt(digits.length())));

passwordChars.add(special.charAt(random.nextInt(special.length())));

String allChars = upper+lower+digits+special;


for (int i=4; i<8; i++){

passwordChars.add(allChars.charAt(random.nextInt(allChars.length())));
}
Collections.shuffle(passwordChars);
StringBuilder sb = new StringBuilder();
for(char ch:passwordChars){
sb.append(ch);
}
System.out.println( sb.toString());
}
}

10. Remove all special characters from a string.


Input: "s@atur!day", Output: saturday
public class RemoveSpecialCharacters {
public static void main(String[] args) {
String str = "s@atur!day";
System.out.println("Input: "+str);
str = str.replace("@", " ");
str = str.replace("!", " ");
str = str.replace(" ", "");
System.out.println("Output: "+str);
}
}

11. Remove all vowels from a string.


Input: "I am a SQA Engineer", Output: m sq ngnr
public class RemoveVowel {
public static void main(String[] args) {
String str = "I am a SQA Engineer";
String vowel ="aeiouAEIOU";
StringBuilder sb = new StringBuilder();

for(int i =0; i<str.length(); i++){


char ch = str.charAt(i);
if(vowel.indexOf(ch)==-1){
sb.append(ch);
}
}
System.out.println(sb.toString());
}
}

12. Check if a given string is a valid binary number (only contains 0 and 1).

Example 1: "1001" → ✅ true


Example 2: "2001" → ❌ false
public class CheckBinary {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str =scanner.nextLine();
char ch[] = str.toCharArray();
boolean isBinary = true;
for(int i=0; i< ch.length; i++){
if(!(ch[i]=='0' || ch[i] =='1')){
isBinary = false;
}
}
System.out.println(isBinary);
}
}

13. Given a paragraph: A Core i7 laptop price is 85000 tk and a gaming mouse price is 2500
tk. If I buy the laptop and 1 piece of mouse, what will be my total cost after giving 15%
discount? Extract the digits and calculate the final cost after the discount.

✅ Output: 74,375 tk.


public class ExtractDigitFromString {
public static void main(String[] args){
String str = "A Core i7 laptop price is 85000 tk and a gaming
mouse price is 2500 tk. " +
"If I buy the laptop and 1 piece of mouse, what will
be my total cost after giving 15% discount?";
str = str.replaceAll("[^\\d]", " ");
str = str.trim();
str = str.replaceAll(" +", " ");

System.out.println("Extracted Digits are: " +str);

String strArray[] = str.split(" ");

int laptopPrice = Integer.parseInt(strArray[1]);


int mousePrice = Integer.parseInt(strArray[2]);
int discount = Integer.parseInt(strArray[4]);
double discountPercentage = (laptopPrice+mousePrice)*discount / 100;
System.out.println(discountPercentage);
int totalCost = laptopPrice + mousePrice;
double finalCost = totalCost - discountPercentage;
System.out.println("Total cost after 15% discount: " + finalCost +
" tk");
}
}

14. Write a program to break down a given amount into currency notes.
Available notes: [1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]

public class CountNotes {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the amount: ");
int amount = scanner.nextInt();
int[] notes = {1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};

for (int note : notes) {


if (amount >= note) {
int count = amount / note;
amount = amount % note;
System.out.println(note + " x " +count);
}
}
}
}
15. A question paper has 15 questions worth either 5 marks or 10 marks.
You need to total exactly 100 marks. Find the number of 5-mark and 10-mark
questions.
public class QuestionMarksEqual100 {
public static void main(String[] args) {
int totalQuestions = 15;
int totalMarks = 100;
int y = (totalMarks - 5 * totalQuestions) / 5;
int x = totalQuestions - y;
System.out.println("5-mark questions: " + x);
System.out.println("10-mark questions: " + y);
}
}

You might also like