Display array of words in reverse order - java

I have some of my code already done I just do not know how I would display the sentence in reverse order than what is entered.
For example; if one enters "my name is joe"
It should display in the output: Joe
is
name
my
import java.util.Scanner;
public class Sentence {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = input.nextLine();
String[] words = sentence.split(" ");
// Display the array of words in
// reverse order
}
}

If I understand your problem, you can do something like that:
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = input.nextLine();
String[] words = sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
System.out.println(words[i]);
}
}

Related

To check each word in a sentence whether they are palindrome or not

In a given sentences, reverse each word and print the reversed words in the sentences. if there is a palindrome print those words .if there is no palindrome print "No Palindrome".
this is what i wrote
import java.util.Scanner;
public class main{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
String s1=input.nextLine();
String arr[]=s1.split("\\s",s1.length());
int count=0;
String palindrome[]=new String[s1.length()];
for(int i=0;i<arr.length;i++){
String s2="";
for(int j=arr[i].length()-1;j>=0;j--){
s2=s2.concat(Character.toString(arr[i].charAt(j)));
System.out.println(arr[i].charAt(j));
}
System.out.print(" ");
if(arr[i].equals(s2)){
count++;
palindrome[i]=s2;
}
}
if(count>0){
for(String i:palindrome)
System.out.println(i);}
else
System.out.println("Not a palindrome");
}
}
But code is not giving proper output.
This should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String[] arr = s1.split(" ");
StringBuilder output = new StringBuilder();
for (String currentWord : arr) {
String reverseWord = new StringBuilder(currentWord).reverse().toString();
if (currentWord.equals(reverseWord)) {
output.append(reverseWord);
} else {
output.append("No Palindrome ");
}
}
System.out.println(output);
}
Here's a shorter way of doing this:
//prints each palindome word in a sentence
Arrays.asList(sentence.split(" ")).stream().filter(this::isPalindrome).forEach(System.out::println);
Here is a working code that you can use for checking the input string/number is palindrome or not palindrome
code:
import java.util.*;
class stackOverflow {
public static void main(String[] args) {
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome or not:");
// takes input string
original = in.nextLine();
int length = original.length(); // length of the string to do iteration on it
// check the string from the end to the start to reverse it
// read and append it with the reverse variable in backward
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
// Finally we check if the input string and reversed string
if (original.equals(reverse))
System.out.println("Is palindrome.");
else
System.out.println("Not palindrome.");
}
}
I've edited your code and now it's working fine:
import java.util.*;
class stackOverflow {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
String s1=input.nextLine();
String arr[]=s1.split("\\s",s1.length());
for(int i=0;i<arr.length;i++){
String s2="";
for(int j=arr[i].length()-1;j>=0;j--){
s2=s2.concat(Character.toString(arr[i].charAt(j)));
//System.out.println(arr[i].charAt(j));
}
//System.out.print(" ");
if(arr[i].equals(s2)){
//palindrome[i]=s2; // you are inserting the s2 value into the first element of the array,
//so the rest of the positions remains empty/null that's not a problem to solve palindrome
System.out.println("Is a palindrome");
}
else
System.out.println("Not a palindrome");
}
}
}

Storing user input in a string array

I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.

How to write a java program to accept the full name of a person and output the last name with initials?

I've written the following code. This works if only there are two initials before last name. How do i modify it to work with 3 or more initials. For example:
Input: ABC EFG IJK XYZ
Output I want is: A E I XYZ
Here is my code:
import java.util.*;
class Name{
public static void main(String[] args){
System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(name);
String[] arr = name.split(" ",3);
System.out.println(arr[0].charAt(0)+" "+arr[1].charAt(0)+" "+arr[2]);
}
}
Use a loop and don't limit the split to 3 :
{
System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(name);
String[] arr = name.split(" ");
// print all the initials
for (int i = 0; i < arr.length - 1; i++) {
System.out.print(arr[i].charAt(0) + " ");
}
// print the last name
System.out.println(arr[arr.length-1]);
}
import java.util.*;
class SName
{
public static void main(String[] args)
{
String n;
Scanner c=new Scanner(System.in);
System.out.print("Enter the user name:");
n=c.nextLine();
String [] t=n.split(" ");
int l=t.length;
System.out.print("Your Short name:");
for(int i=0;i<l-1;i++)
{
System.out.print(t[i].charAt(0)+".");
}
System.out.print(t[l-1]);
}
}
Try This code More Java Program

Concatenate User Input JAVA

This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));

JAVA: Count each word on a String, and count each letter on the words

So, I've got a java assignment in which I have a String with a phrase. I need to count each word the phrase has and then count how many letters each word has. I've been able to split the phrase into words by using the Tokenizer, and then count and print the amount of words with .countTokens(). However, I'm not being able to count the letters in each word.
Basically the output should be something like this:
"Nihil veritas est"
Words: 3
Nihil: 5 letters
Veritas: 7 letters
Est: 3 letters
Here's my code so far:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
StringTokenizer stoken = new StringTokenizer(phrase);
System.out.println("Your phrase has "+stoken.countTokens()+"words");
}
Try this:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
String[] words = phrase.split(" ");
System.out.println("The number of words is:"+words.length);
for(int i=0; i<words.length; i++){
System.out.println(words[i]+" is "+words[i].length()+" letters long.");
}
}
}
This code uses split() instead of Tokenizer. It just seemed easier to me.
Try this:
import java.util.Scanner;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("PLease enter your phrase");
String phrase = in.nextLine();
StringTokenizer st = new StringTokenizer(phrase);
System.out.println("Your phrase has " + st.countTokens() + " words");
// Loop thorough to count number of letters in each word.
while (st.hasMoreTokens()) {
String tokenName = st.nextToken();
System.out.println(tokenName + ": has " + tokenName.length() + " letters");
}
}
}
Here is my solution to your problem:
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
// get an array each having a word using split
String[]words = phrase.split(" ");
//print count of words?
System.out.println("Words: "+words.length);
//loop over the words
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i]+": "+words[i].length()+" letters");
}
}
public class wordCount
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println(" Enter a String1");
String str=sc.nextLine();
System.out.println(" Entered String : ");
System.out.println(str);
//logic
char ch[]=str.toCharArray();
str="";
int count=0;
for (int i = 0; i < ch.length; i++)
{
if(ch[i]!=' ')
{
str=str+ch[i];
count++;
}
else if(ch[i-1]!=' ')
{
/*str=str+"-->"+count +" ";*/
System.out.println(str+"--->"+count);
count=0;
str="";
}
}
System.out.println(str+"--->"+count);
sc.close();
}
}

Categories

Resources