Use a Scanner object and its method nextLine() to get an entire line of text as
ID: 3939784 • Letter: U
Question
Use a Scanner object and its method nextLine() to get an entire line of text as input and assign it to a String variable line1. Print line1 On one line, print every other character of line1 and then print a new line. Print line1 from the second character to the end and tack on the first character at the end of the output. For example, if the input is "Java is good", the output would be "ava is goodJ". Print line1 in all uppercase using a String method toUpperCase(). Using the Scanner object, get another line of text called line2. Using the String method compareTo(), print the two lines in alphabetical order.Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class LinePrint {
public static void main(String[] args) {
// creating an Scanner Object
Scanner sc = new Scanner(System.in);
//1 getting line1 test
String line1 = sc.nextLine();
// 2. print line1
System.out.println(line1);
// 3 print each character of line1 on separate line
for(int i=0; i<line1.length(); i = i+2)
System.out.print(line1.charAt(i));
System.out.println();
// 4 print from second character and print first character at last
for(int i=1; i<line1.length(); i++)
System.out.print(line1.charAt(i));
System.out.println(line1.charAt(0)); // printing first character at last
// 5 print all character of line1 in uppercase
System.out.println(line1.toUpperCase());
// 6 getting another line
String line2 = sc.nextLine();
if(line1.compareTo(line2) > 0){// line1 > line2
System.out.println(line2);
System.out.println(line1);
}
else{ // line1 <= line2
System.out.println(line1);
System.out.println(line2);
}
}
}
/*
Sample run:
The rain in Spain
The rain in Spain
Teri nSan
he rain in SpainT
THE RAIN IN SPAIN
Stays mainly in the plain
Stays mainly in the plain
The rain in Spain
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.