Write a program that manipulates two strings. The program inputs two strings (
string1
andstring2
) and a character (char1
) and an integer (position
) to represent a character position within a string. The program will display the following:
- Whether
string1
is less, greater or equal tostring2
string1
in upper casestring2
in lower case- The number of characters in
string1
- The first character in
string2
- The number of occurrences that
char1
is contained instring1
. Hint: use afor
loop andcharAt
- The character that is in the position of string1. Turn in a run of the program that uses your first and last names as the strings. Use at least two methods with the following headers:
int countOccurrences(String s, char c) // to answer #6 char
showChar(String s, int pos) // to answer #7
import java.util.Scanner;
public class Hwk5A {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your First Name: ");
String string1 = keyboard.nextLine();
System.out.print("Enter your Last Name: ");
String string2 = keyboard.nextLine();
System.out.print("Enter a character: ");
char char1 = keyboard.next().charAt(0);
System.out.print("Enter an number: ");
int position = keyboard.nextInt();
//Question 1
if(string1.compareTo(string2)>0){
System.out.println("First name is greater than Last name");
}
else if (string1.compareTo(string2)==0) {
System.out.println("First name is equal to Last Name");
}
else {
System.out.println("First name is less than Last name");
}
//Question #2:
System.out.println("\nstring1 uppercase:" + string1.toUpperCase());
//Question #3:
System.out.println("string2 lowercase:" + string2.toLowerCase());
//Question #4:
System.out.println("number of characters in string1: " + string1.length());
//Question #5:
System.out.println("first character in string2: " + string2.charAt(0));
//Question #6:
System.out.println("# of occurrences that char1 is contained for string1: "
+ countOccurrences(string1, char1));
//Question #7:
System.out.println("the character in string 1 from inputted position # is: "
+ showChar(string1, position));
}
public static int countOccurrences(String s, char c) {
int countOccurrences = 0;
int totalOccurrences = 0;
for(int i = 0; i <= s.length()-1; i++){
if(s.charAt(i) == c) {
countOccurrences = 1;
totalOccurrences += countOccurrences;
}
}
return totalOccurrences;
}
public static char showChar(String s, int pos) {
return s.charAt(pos);
}
}