Concatenate User Input JAVA - 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));

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");
}
}
}

Java: How do I make my program print without two extra dots?

This program needs to print a.b.c. but it prints a.b.c...
How do I eliminate the last dot in output.
The program has to work with user ending loop with "."
import java.util.Scanner;
public class dots1 {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do {
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
} while (!input.equals("."));
System.out.println(output);
}
}
Because your exit condition is "." and you add it to output and add another dot. Try following:
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input = "";
String output = "";
System.out.println("Hello! I print out an acronym. ");
while (true) {
System.out.println("Please Enter a Character");
input = s.nextLine();
if(input.equals("."))
break;
output = output + input + ".";
} ;
System.out.println(output);
}
I use a little trick using a simple check to see if its not the first read.
boolean isFirst=true;
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
if(!isFirst) output="."+output;
isFirst=false;
output = output+input;
}while(!input.equals("."));
Instead of the do... while, you should use the the while function.
while (!input.equals(".") {
}
You have to use substring function in java and remove the last character of the String.
your loop end while you enter a dot in input.
Example given below.
Try this
import java.util.Scanner;
public class dots1 {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
}while(!input.contains("."));
System.out.println(output.substring(0, output.length() - 2));
}
}
Output of Single Input
output of Multiple Inputs

Replacing a char value in a string (Java)

In my assignment I need to get this output:
Enter a word: house
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
_____________________________________________.
I got the program to work with this code, but now I need to set while loops. Here is my current code.
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replaceAll(readChar, changeChar));
System.out.println();
I need to now make my program output this:
Enter a word: house
What letter do you want to replace?: a
There is no a in house.
What letter do you want to replace?: b
There is no a in house.
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
How would my while loop look to portray this output?
After you read the word and the character you want to replace (plus the character you want to replace it with) you can use replace method from the String class.
Here is an example usage (adapt the variable names to your code)
word = word.replace(letterToReplace, replacementLetter);
So for example
String word = "aba";
word = word.replace('a', 'c');
System.out.println(word); // Prints out 'cbc'
Also here is an obligatory link to the JavaDoc for the replace method:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29
Okay this is one possible way to implement the edited second part of the question:
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
boolean done = false;
do{
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
if(word.contains(readChar)){
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
done = true;
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
}
while(!done);
}
I hope you don't mind hard interpretation,Below is the example you can follow the same.
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
print.i(r);
If you want to replace all of the letters, you can do it like this (working code):
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
This illustrates what you need to do.
import java.util.Scanner;
public class WordScrambler{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = keyboard.nextLine();
System.out.print("What letter do you want to replace?: ");
char letter = keyboard.next().charAt(0);
StringBuffer out = new StringBuffer(word);
System.out.print("With what letter do you wish to replace it? ");
char changeChar = keyboard.next().charAt(0);
for (int i=0; i<word.length(); ++i)
if(word.charAt(i) == changeChar)
out.setCharAt(i, changeChar);
System.out.println("The new word is "+out);
}
}

How would I make this loop until the user enters a blank line in java?

import java.util.Queue;
import java.util.Scanner;
import java.util.LinkedList;
class PalindromeTest
{
public static void main(String[] args)
{
System.out.print("Enter any string:");
Scanner in = new Scanner(System.in);
String inputString = in.nextLine();
Queue queue = new LinkedList();
for (int i = inputString.length()-1; i >=0; i--)
{
queue.add(inputString.charAt(i));
}
String reverseString = "";
while (!queue.isEmpty())
{
reverseString = reverseString+queue.remove();
}
if (inputString.equals(reverseString))
System.out.println("The input String is a palindrome.");
else
System.out.println("The input String is not a palindrome.");
}
}
So this code prints out if the string input is a Palindrome, but not sure how to make it so it loops and terminates when a blank line is entered. I've tried a do while loop but had no luck
Like this maybe?
System.out.print("Enter any string:");
Scanner in = new Scanner(System.in);
String inputString; //extract the inputString as a variable
while (!(inputString = in.nextLine()).equals("")) //just add this loop, the rest is same as yours
{
Queue queue = new LinkedList();
for (int i = inputString.length() - 1; i >= 0; i--)
{
queue.add(inputString.charAt(i));
}
String reverseString = "";
while (!queue.isEmpty())
{
reverseString = reverseString + queue.remove();
}
if (inputString.equalsIgnoreCase(reverseString))
{
System.out.println("The input String is a palindrome.");
}
else
{
System.out.println("The input String is not a palindrome.");
}
System.out.print("Enter any string:");
}

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