In: Computer Science
Question 1:
Write a program to receive a string from the user and compares the first and second half of the word and prints “First and Second Half Same” or “First and Second Half Different”. If the length of the word is odd, ignore the middle letter.
For example:
Run 1:
Enter a word: abcdabc
First and Second Half Same
Run 2:
Enter a word: abcde
First and Second Half Different
Hint: use the Math.floor() and length() to get the halves of the string and use the equals() to perform the similarity check inside if-else statement.
**********************************************************************************
Question 2:
Write a program that reads three different integers from the users and prints “all the same” if they are all equal, “all different”, if three numbers are different and “neither” for all other cases.
For example:
Enter first number: 3
Enter first number: 2
Enter first number: 6
All Different.
**********************************************************************************
Question 3:
Write a program that reads three different floating point numbers from the users and prints the largest of those three:
For example:
First number: 2.36
Second number: 2.99
Third number: 2.78
Largest: 2.99
ANSWER 1:-
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter a word:");
String str=input.nextLine();
int n=str.length();
int mid=n/2;
String half=str.substring(0,mid);
String sub;
if (str.length() % 2==0)
sub=str.substring(mid);
else
sub=str.substring(mid+1);
if (sub.equals(half))
System.out.println("First and Second Half
Same");
else
System.out.println("First and Second Half
Different");
}
}
OUTPUT:-
ANSWER 2:-
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter first number:");
int num1=input.nextInt();
System.out.print("Enter second number:");
int num2=input.nextInt();
System.out.print("Enter third number:");
int num3=input.nextInt();
if (num1 == num2 && num2 == num3)
System.out.println("all the same");
else if (num1 != num2 && num2!=num3)
System.out.println("all different");
else
System.out.println("neither");
}
}
OUTPUT
Answer 3:-
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("First number:");
float num1=input.nextFloat();
System.out.print("Second number:");
float num2=input.nextFloat();
System.out.print("Third number:");
float num3=input.nextFloat();
if (num1>num2){
if (num1>num3)
System.out.println("Largest:"+num1);
else
System.out.println("Largest:"+num3);
}
else{
if (num2>num3)
System.out.println("Largest:"+num2);
else
System.out.println("Largest:"+num3);
}
}
}
OUTPUT:-