Exercise 1 Revision String
1.
public class StringExercise {
public static void main (String[] args) {
String college = new String ("College of Arts and Sciences");
String town = new String (" UUM Sintok") ; // part (a)
int stringLength;
String change1, change2, change3;
stringLength=college.length(); // part (b)
System.out.println (college + " contains " + stringLength + " characters.");
change1 = college.toUpperCase(); // part (c)
System.out.println ("The string is all in upper case: " + change1);
change2 = change1.replaceAll("O","*"); // part (d)
System.out.println ("All capital O's are replaced with the asterisk character: " + change2);
change3 = college.concat (town) ; // part (e)
System.out.println ("The final string is " + change3);
}
}
2. import java.util.Scanner;
public class FunnyStringExc{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String color, food, animal, firstName;
System.out.print("Enter your favourite colour: ");
color = sc.next();
System.out.print("Enter your favourite food: ");
food = sc.next();
System.out.print("Enter your favourite animal: ");
animal = sc.next();
System.out.print("Enter your friend first name: ");
firstName = sc.next();
String output1 = "I had a dream that ".concat(firstName);
String output2 = output1.concat(" ate a ");
String output3 = output2.concat (color + " ");
String output4 = output3.concat(animal);
String output5 = output4.concat(" and said it taste like a ");
String output6 = output5.concat(food);
String output7 = output6.concat("!");
System.out.println(output7);
}
}




Comments