using java.util.Stack print line of texts in reverse - java

Lines should be read from the user until the sentinel "DONE" is entered, at which point they are displayed in reverse. Do not print the word "DONE"
here is my code so far i am not sure how to get it all to work together i know i have been overthinking this but any help will be appreciated
import java.util.Scanner;
import java.util.Stack;
public class Turner_A05Q3{
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
al.add(word);
} else {
break;
}
}
for (int i=0;i<word.length();i++){
stack.push(word.substring(i,i+1));
}
String wordrev = "";
while(!stack.isEmpty()){
wordrev += stack.pop();
}
System.out.println("Reverse of the text \"" + wordrev);
}
}

Try to write your for loop like this:
for (int i = word.length(); i > 0; i--) {
stack.push(word.substring(i-1, i));
}
Input:
DONE
Output:
DONE

You are always working with the last word (done), because you don't use al you only use the last content of the variable word.
You have to iterate over al
Try:
import java.util.Scanner;
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
public class Turner_A05Q3{
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word=null;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
al.add(word);
}else {
break;
}
}
for(int j=0;j<al.size();j++){
word = al.get(j);
for (int i=0;i<word.length();i++){
stack.push(word.substring(i,i+1));
}
String wordrev = "";
while(!stack.isEmpty()){
wordrev += stack.pop();
}
System.out.println("Reverse of the text \"" + wordrev);
}
}
}
If you want to show the words in reversed order, not the characters, try:
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
String word=null;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
stack.push(word);
}else {
break;
}
}
while(!stack.isEmpty()){
System.out.println("Reverse of the text \"" + stack.pop());
}
}
Remember that a Stack is LIFO (Last In First Out)

Related

How do you read a text file and make every 4 words all capital print to the console window?

I try to print every 4 words of my text file with capital letter in console, but this code prints all of my file capital and I can't find out why?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileText {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("players.txt"));
int count = 0;
while (sc.hasNext()) {
String line = sc.next();
String[] elements = line.split(" ");
for (int i = 0; i < elements.length; i++) {
if (i/3 == 0){
System.out.println(elements[i].toUpperCase());
}
else {
System.out.println(elements[i]);
}
}
}
System.out.println("The number of capital letters are: " + count);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
finally {
sc.close();
}
}
}
There are two things going wrong:
a)
the line String[] elements = line.split(" "); does not split the line at every word. The way you use the Scanner already splits them (because the Scanner's default delimeter is a space), meaning that your line variable always only contains one word.
Fix this by using sc.useDelimeter("\n"); before the while(sc.hasNext()) loop.
b)
replace
if(i/3 == 0){
with
if(i%4 == 0){ //modulo division
here is complete code:
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("players.txt"));
int count = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] elements = line.split(" ");
for (int i = 0; i < elements.length; i++) {
if ((i+1) % 4 == 0) {
System.out.println(elements[i].toUpperCase());
} else {
System.out.println(elements[i]);
}
}
}
System.out.println("The number of capital letters are: " + count);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} finally {
sc.close();
}
}
For the file with content: w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12
output will be:
w1
w2
w3
W4
w5
w6
w7
W8
w9
w10
w11
W12

Counting white-spaces in a String in java

I have written a program which takes a String as user input and displays the count of letters, digits and white-spaces. I wrote the code using the Tokenizer-class, and it counts the letters and digits, but it leaves out the white-spaces. Any ideas?
import java.util.Scanner;
public class line {
public static void main(String[] args) {
System.out.println("Enter anything you want.");
String text;
int let = 0;
int dig = 0;
int space= 0;
Scanner sc = new Scanner(System.in);
text = sc.next();
char[]arr=text.toCharArray();
for(int i=0;i<text.length();i++) {
if (Character.isDigit(arr[i])) {
dig++;
} else if (Character.isLetter(arr[i])) {
let++;
} else if (Character.isWhitespace(arr[i])) {
space++;
}
}
System.out.println("Number of Letters : "+let);
System.out.println("Number of Digits : "+dig);
System.out.println("Number of Whitespaces : "+space);
}
}
Scanner by default breaks the input into tokens, using whitespace as the delimiter!
Simply put, it gobbles up all the whitespace!
You can change the delimiter to something else using sc.useDelimiter(/*ToDo - suitable character here - a semicolon perhaps*/).
You have got problem in
sc.next();
except it, use
sc.nextLine();
it should work.
Instead of text = sc.next(); use text = sc.nextLine();
Try using
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Line {
public static void main(String[] args) throws Exception {
String s;
System.out.println("Enter anything you want.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
int length = s.length();
int letters = 0;
int numbers = 0;
int spaces = 0;
for (int i = 0; i < length; i++) {
char ch;
ch = s.charAt(i);
if (Character.isLetter(ch)) {
letters++;
} else {
if (Character.isDigit(ch)) {
numbers++;
} else {
if (Character.isWhitespace(ch)) {
spaces++;
} else
continue;
}
}
}
System.out.println("Number of letters::" + letters);
System.out.println("Number of digits::" + numbers);
System.out.println("Number of white spaces:::" + spaces);
}
}

Program that takes a word than searches and prints out the whole string that contains the word

The basic function of this program is to take a word and search in an array of strings than search and print the string containing that word.
public static void main(String[] args) {
String[] str = {"I am Alive.", "Are you dead?", "Let's see if it works."};
String search;
int count=0;
Scanner s=new Scanner(System.in);
System.out.println("enter word");
search=s.nextLine();
for(int i=0;i<str.length;i++){
//check strings individually
if(str[i].charAt(i)=='.'||str[i].charAt(i)=='?'){ //search for dot or any sentence finisher
count++;
}
if(str[i].contains(search)){
System.out.println(str[count]);
} else {
System.out.println("Not found");
break;
}
}
}
You should not break the loop there since it is only considered not found once you went through all the sentences in the array. Something like this:
public static void main(String[] args) {
String[] str={"I am Alive.","Are you dead?","Let's see if it works."};
String search;
Scanner s=new Scanner(System.in);
System.out.println("Enter word");
search=s.nextLine();
boolean found = false;
for(int i=0;i<str.length;i++){
if(str[i].contains(search)){
System.out.println(str[i]);
found = true;
}
}
if (!found) {
System.out.println("Not found");
}
}
Watch out that break, it's executed always.
Check this:
public static void main(final String... args) {
final String[] strings = { "I am Alive.", "I am Alive...too.", "Are you dead?",
"Let's see if it works." };
int found = -1;
System.out.print("Enter search term > ");
try (final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
final String input = scanner.nextLine();
for (int i = 0; (i < strings.length) && (found < 0); i++) {
if (strings[i].contains(input) && (strings[i].contains(".") ||
strings[i].contains("?"))) {
//System.out.println(strings[i]);
found = i;
}
}
}
System.out.printf("%s%n", (found >= 0) ? strings[found] : "Not found");
}

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Program to remove a word from a sentence

How can I modify the program without using word number option?
Please give me a simplified program.
What must I do to make this program work without word number?
import java.io.*;
class Sentence
{
public static void main(String ar[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence");
StringBuffer sentence=new StringBuffer(br.readLine()+" ");
System.out.println("Enter the word to be deleted");
String word=br.readLine();
int n=0;
int wordno;
System.out.println("Enter the word number");
wordno=Integer.parseInt(br.readLine());
int count=0;
for(int i=0;i<sentence.length();i++)
{
char ch=sentence.charAt(i);
if(ch==' ')
{
String str=sentence.substring(n,i);
count=count+1;
if(str.equals(word)&&count==wordno)
{
sentence.delete(n,i);
}
n=i+1;
}
}
System.out.println("The new sentence is : "+sentence);
}
}
Here is the working program
package com.nikhil.string;
import java.io.IOException;
import java.util.Scanner;
public class demo1 {
public static void main(String[] args) throws IOException {
String[] s;
String sentence, word;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
sentence = sc.nextLine();
System.out.println("Enter the word to be deleted");
word = sc.nextLine();
String finalSentence = "";
s = sentence.split(" ");
for (int i = 0; i < s.length; i++) {
if (word.equals(s[i])) {
continue;
} else {
finalSentence += s[i] + " ";
}
}
System.out.println("final sentence is :: " + finalSentence);
sc.close();
}
}
As far as I can see you want to remove given word from a sentence. My suggestion as follows
Read sentence (say String str="hi, How are you")
Take the word you want to remove from the sentence.
(say String strToRemove="are")
Then you can try something as follows.
String str = "hi, How are you?. are you there?";
String strToRemove = "are";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
boolean status=true;
while (status){
int index=stringBuilder.indexOf(strToRemove);
if(index!=-1) {
stringBuilder.delete(index, index + strToRemove.length()+1);
// +1 will remove a space
}else {
status=false;
}
}
System.out.println(stringBuilder.toString());
public static void main(String ar[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence");
StringBuffer sentence = new StringBuffer(br.readLine() + " ");
System.out.println("Enter the word to be deleted");
String word = br.readLine();
String result = sentence.toString().replace(word, "");
System.out.println("The new sentence is : " + result);
}

Categories