176k views
5 votes
Problem 1: you must write a method for this problem called sentenceAnalyzer Write a program that reads a sentence from the keyboard. Depending on the last character of the sentence, generate output identifying the sentence as declarative (ends with a period), interrogative (ends with a question mark), exclamatory (ends with an exclamation point), or unknown.

1 Answer

6 votes

Answer:

static void sentenceAnalyzer(String sentence){

int lenOfString = sentence.length()-1;

if(sentence.charAt(lenOfString)=='.'){

System.out.println("Declarative");

}

else if(sentence.charAt(lenOfString)=='?'){

System.out.println("Interrogative");

}

else if(sentence.charAt(lenOfString)=='!'){

System.out.println("Exclamation");

}

else{

System.out.println("Unknown");

}

}

Step-by-step explanation:

Using Java programming language

Create the method as required

Obtain the index of the last element using the string length method

Use if and else statements to check if the character at the last index is equal to any of the characters given and print the expected output

see a complete code with the main method below

import java.util.Scanner;

public class num11 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

//Receiving User input

System.out.println("Enter a sentence");

String sentence = in.nextLine();

// Calling the method

sentenceAnalyzer(sentence);

}

static void sentenceAnalyzer(String sentence){

int lenOfString = sentence.length()-1;

if(sentence.charAt(lenOfString)=='.'){

System.out.println("Declarative");

}

else if(sentence.charAt(lenOfString)=='?'){

System.out.println("Interrogative");

}

else if(sentence.charAt(lenOfString)=='!'){

System.out.println("Exclamation");

}

else{

System.out.println("Unknown");

}

}

}

User Justidude
by
4.1k points