In: Computer Science
1.The below code has some errors, correct the errors and post the working code.
Scanner console = new Scanner(System.in);
System.out.print("Type your name: ");
String name = console.nextString();
name = toUpperCase();
System.out.println(name + "
has " + name.Length() + " letters");
Sample Ouptut:
Type your name: John
JOHN has 4 letters
2. Write a code that it reads the user's first and last name (read in the entire line as a single string), then print the last name followed by a comma and the first initial.
Sample output:
Type your name: John Smith
Smith, J.
Answer:
Question 1:
import java.util.*;
public class Test /* 'Test' class starts here */
{
public static void main(String[] args) /* main()
function starts here */
{
Scanner console = new
Scanner(System.in); /* 'console' object of type Scanner
class is created */
System.out.print("Type your
name: "); /* displays the message on the screen */
String name =
console.nextLine(); /* nextLine() is used to read the
string, and is stored in 'name' */
name = name.toUpperCase();
/* toUpperCase() is used to convert each
character of the string to uppercase */
System.out.println(name + " has " +
name.length() + " letters"); /* length() is used to find
the length of the string */
} /* End of main() */
} /* End of 'Test' class */
Output:
Question 2:
import java.util.*;
public class Test1 /* 'Test1' class starts here
*/
{
public static void main(String[] args) /* main()
function starts here */
{
Scanner console = new
Scanner(System.in); /* 'console' object of type Scanner class is
created */
System.out.print("Type your name:
"); /* displays the message on the screen */
String name = console.nextLine();
/* nextLine() is used to read the string, and is stored in 'name'
*/
String[] tokens = name.split(" ");
/* The string in 'name' is splitted at white space character and
stored in 'tokens' array */
System.out.println(tokens[1]+",
"+tokens[0].charAt(0)+"."); /* tokens[1] will be 2nd word,
tokens[0] is 1st word, charAt(0) is first character */
} /* End of main() */
} /* End of Test1 */
Output: