2.12. Coding Practice¶
The coding problems below are mostly about Strings, but more problems on other topics in this unit will be added in the future.
Write the code to print a random number from 1 to 100. You can use
Math.random() to get a value between 0 and not quite 1.
First multiply the output from Math.random() times 100 and then cast it to an integer. This will result in a random number from 0 to 99. Add one to make it from 1 to 100.
Answer: This is the answer to the previous question.
The following code should get the first letter of the first name, middle name, and last name and append (concatenate) them together and then return them all in lowercase. However, the code has errors. Fix the code so that it compiles and runs correctly.
The following code should print the first 3 letters of the string
message all in lowercase letters. However, the code has errors. Fix the errors so that the code runs as intended.
The following code starts with
String name1 = ALEX; and should print
substring methods to assign the variable finalName to the value Alex.
The following code should remove the word “very ” (and following space) from the message and print the new message. You can use
indexOf to find the position of a substring in your string. You can use
substring to create a new string removing the word.
The following code should replace
lol in the message with
laugh out loud and print the new message using indexOf and substring.
For more practice with Strings see problems at http://codingbat.com/java/String-1.