Read Time:58 Second
Write a program to input and display the sentence “I love candies“
import java.util.Scanner; public class DisplaySentence { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a sentence: "); String sentence = scanner.nextLine(); System.out.println("You entered: " + sentence); } }
Output:
Enter a sentence: I love candies You entered: I love candies
Explanation:
- We start by importing the
Scanner
class from thejava.util
package. This will allow us to read input from the user. - Next, we define a
main
method which is the entry point of the program. - Inside the
main
method, we create aScanner
object namedscanner
which will be used to read input from the user. - We then prompt the user to enter a sentence by calling the
System.out.print
method to print the message “Enter a sentence: ” to the console. - We then use the
scanner.nextLine()
method to read a line of text from the user, which is stored in thesentence
variable. - Finally, we print the sentence back to the console using the
System.out.println
method, along with a message indicating that the user entered that sentence.
Average Rating