Create a program that uses a dialog box to ask “Enter a sentence.”, take the user input, and then store the user input in a string variable.
Use the “split()” method to break the address into an array of String type. Then, use a “for..in” (also known as “for..each”)loop to display every word in a one-word-per-line manner in one dialog box.
Then, use: (1) the “toUpperCase()” method to convert every character to uppercase, (2) the toCharArray() method to break the same string literal to an array of char type, and (3) a “for” loop to display every element of the char array in a one-character-per-line manner in another dialog box.
import javax.swing.JOptionPane;
public class MyProg {
public static void main(String[] args) {
String sentence = JOptionPane.showInputDialog(null, "Enter a sentence: ");
//use split method to split words
String str[] = sentence.split(" ");
// create string to display in Messagedialog box
String words = "";
//for each loop to str array
for (String str1 : str) {
words += str1 + "\n"; // \n to display per line
}
// display words per line
JOptionPane.showMessageDialog(null,words);
// convert each character to Uppercase
sentence = sentence.toUpperCase();
// convert each word to character array
char[]ch = sentence.toCharArray();
String chars = "";
// appends character to chars string to display in dialog box
for (int i = 0; i < ch.length; i++) {
chars += ch[i]+"\n";
}
JOptionPane.showMessageDialog(null,chars);
}
}
Comments
Leave a comment