Java returning a string from a stack - java

I am supposed to reverse the individual words in a sentence using a helper method that takes a string as a parameter and returns a string. The stack is supposed to be in the helper method. So my program works in that it reverses the words correctly. But reverse isnt actually getting returned, i think its just printing the stack. Can anyone help me return and print the string variable 'reverse'.
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.print("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
System.out.println("Reversed:" + PrintStack(sentence));
}
private static String PrintStack(String sentence)
{
String reverse = "";
String next = "";
Stack<String> stack= new Stack<String>();
String words[] = sentence.split(" ");
for(int j = 1; j<words.length +1; j++)
{
String newWord = words[words.length - j]; // Single word
for(int i = 0; i < newWord.length(); i++)
{
next = newWord.substring(i,i+1);
stack.push(next);
}
stack.push(" ");
}
while(!stack.isEmpty())
{
reverse += stack.pop();
}
return reverse;
}
}

You are reversing twice and ending up with the same order. Your Stack gives reverse order, but you are adding the words in reverse order, so the order is unchanged.
If you used a debugger it should be obvious to you what the issues is.
BTW You can make the code much shorter.
private static String printStack(String sentence) {
Stack<String> stack= new Stack<String>();
for(String word: sentence.split(" ")
stack.push(word);
String line = stack.pop();
while(!stack.isEmpty())
line += " " + stack.pop();
return line;
}

Related

How properly convert char to String and pass String in method?

I need to pass the String in the end of method in order to print String directly in main method, but when I did below, I receive just this one
[Ljava.lang.String;#135fbaa4
public static String businessLogic(String[] words) {
for (String word : words) {
char[] arrayWordInChar = word.toCharArray();
int wordLength = word.length();
for (int i = 0, j = wordLength - 1; i < j; ) {
if (!Character.isAlphabetic(arrayWordInChar[i]))
i++;
else if (!Character.isAlphabetic(arrayWordInChar[j]))
j--;
else
swapLetters(arrayWordInChar, i++, j--);
}
arrayWordInChar.toString();
}
return Arrays.toString(words);
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().split(" ");
businessLogic(words);
System.out.println(words);
}
}
I have been confused with this question for almost 2 days, what's the problem?
You get "[Ljava.lang.String;#135fbaa4" because words is String[], you can change the code as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().split(" ");
//businessLogic(words);
System.out.println(businessLogic(words));
}
Arrays.toString(str)
String Constructor
String.valueOf() or String.copyValueOf()
First, add assignment to words array by words = businessLogic(words);
To print your arraylist elements, you can do one of the following :
System.out.println(Arrays.toString(words));
or
for(String word : words){
System.out.println(word);
}
businessLogic method returns a string but you are not assigning it to any String variable and in your System.out you are printing array words as a string.
System.out.println(businessLogic(words));
above line will print your desired output.

Create array with reversed words from user string

I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is.
I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
char[] entryToChar = userEntry.toCharArray();
System.out.println(Arrays.toString(entryToChar));
String[] splitInput = userEntry.split(" ");
String reverseWord = "";
int temp;
String[] reverseString = new String[splitInput.length];
for (int i = 0; i < splitInput.length; i++)
{
String word = splitInput[i];
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
for (int k = 0; k < splitInput.length; k++) {
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
}
} System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);
I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below:
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word, reverseWord;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
userEntry: I love you
String[] splitInput = userEntry.split(" ");
splitInput: [I, love, you]
for (int i = 0; i < splitInput.length; i++)
{
word = splitInput[i];
reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
splitInput[i] = reverseWord;
}
splitInput: [I, evol, uoy]
System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
}
}
Your string with words spelled backwards is: I evol uoy
Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String.
The other problem is variable j is outside its block scope from where you are trying to access.
Make your logic clear before writing code to achieve correct result.
A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. I would suggest to use the class StringBuilder, which has a method for reversing the string. Your program could look like this:
while in.hasNext() {
StringBuilder sb = in.next();
sb.reverse();
System.out.println(sb.toString());
}
If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse().
Please know that String in Java is an immutable object. You cannot modify it directly. You can have modified copies returned.
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above.
You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice.
class Testarray{
public static void main(String args[]){
String str = "I am Engineer";
String[] spArray = str.split(" ");
String farr[] = new String[spArray.length];
for(int i=0;i<spArray.length;i++){
String split = spArray[i];
farr[i]=reverseString(split);
}
for(int i=0;i<farr.length;i++){
System.out.println(farr[i]);
}
}
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
There are a few things going on here, and I think in some places you're mixing up between strings and arrays.
Let's try to break this problem down into smaller problems.
First, we need to reverse a single word. Your first inner loop (the one that uses j) does that, so let's extract it into its own method:
public static String reverseWord(String word) {
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
return reverseWord;
}
Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable):
public static String reverseWord(String word) {
StringBuilder reverseWord = new StringBuilder(word.length());
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord.append(word.charAt(j));
}
return reverseWord.toString();
}
Once you have that, you can split the input string (like you did), revere each word, and join them back together:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
for (int i = 0; i < splitInput.length; i++) {
splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " +
String.join(" ", splitInput));
All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse:
public static void main(String... args) {
String str = getSentenceFromConsole();
System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}
private static String getSentenceFromConsole() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter a string to see it in reverse: ");
return scan.nextLine();
}
}
private static String reversLettersInWords(String str) {
return Arrays.stream(str.split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
i try with your code
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitInput.length; i++) {
String word = splitInput[i];
for (int j = word.length() - 1; j >= 0; j--) {
sb.append(word.charAt(j));
}
sb.append(" ");
}
System.out.println("Your sttring with words spelled backwards is " + sb.toString());
here i remove all access line of code....
String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);
You can use this implementation to try to reverse the string elements in the array.

How can I make a java program that takes an input of words, finds certain words, replaces them and then prints out everything again?

I am not sure what to do, I have found all this online and I am trying to change it to do what I explained above but I am stuck. Basically what I want to do is copy and paste an essay into the code somewhere, the have it look through the essay for any words i tell it to look for, and if it finds them then to replace it with the word or words I want it to.
/**
*
import java.util.Arrays;
public class Main {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String words = "test words tesing";
String[] arr = wordList(words);
for(words i=0; i<words.length; i++)
for (String s: arr)
System.out.println(s);
}
}
*/
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
To read from the keyboard use
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (isr);
String cadena = br.readLine();
And all the words you introduced form the keyboard will be in "cadena".
To separte all the words you introduced you could use the method split from String.class.
String[] words = cadena.split(" ");
To find a specific word you could use a method and the code would be in your method would be:
String yourWord = "";
for(int i = 0; i < words.length; i++)
{
if(words[i].equals("your word"))
{
yourWord = words[i];
break;
}
}
To replece a word use the method replce(theWord, "the replacement")
You can prints all the words using a loop for with System.out.println(yourWord);

Determining the highest word alphabetically without arrays in java

I have been trying to write a program that does 2 things, finds the longest word in a user generated string and finding the highest word in alphabetical order. I have the longest word working fine, but I cant figure out the alphabetical problem to save my life. the problem I'm running into is how it is comparing the words running in the for loops. Any help would be appreciated!
/*
CSC 190
Hw7
Ryan Burchfield
10/19/17
Purpose: Take a string and return both the Longest and largest words in the String.
*/
package hw7;
import java.util.Scanner;
class MyString{
String s;
MyString( String s1 ){
s=s1;
}
void setString(String s1){
s=s1;
}
String getLongest(String s1){
s1 = s1 +" ";
int length = s1.length();
String temp="", longestw="";
char ltr;
int templ, longest=0;
for(int i=0; i<length;i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp=temp+ltr;
}
else{
templ=temp.length();
if(templ>longest){
longest=templ;
longestw=temp;
}
temp="";
}
}
return longestw;
}
String getLargest(String s1){
s1= s1 + " ";
String temp="", curWord="",largestW="";
char ltr;
for(int i=0; i<s1.length(); i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp= temp + ltr;
}else{
char ltr1;
for(int j=0; j<s1.length(); j++){
ltr1 = s1.charAt(j);
if(ltr1!=' ' && ltr1!=',' && ltr1!='.'){
curWord= curWord + ltr1;
}
else{
int largest = temp.compareToIgnoreCase(curWord);
System.out.println(temp+","+curWord+","+temp.compareToIgnoreCase(curWord));
System.out.println(largest);
if(largest > 0){
largestW=curWord;
}else{
largestW=temp;
}
curWord="";
temp="";
}
}
}
}
return largestW;
}
}
public class Hw7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String s = in.nextLine();
MyString s1 = new MyString(s);
System.out.println("The longest word is: " + s1.getLongest(s));
System.out.println("The largest word is: " + s1.getLargest(s));
}
}
if(largest > 0){
largestW=curWord;
}else{
largestW=temp;
}
This is where the program goes wrong. You did not compare currWord / temp with largestW
A better way to write getLargest() is to use the same way as getLongest(), i.e. using one loop, and compare largestW with temp every time (if largestW is empty then just set largestW = temp)
I would solve this with a single method that takes a Comparator<String> and the input String; construct a Scanner using the Scanner(String) constructor and modify the delimiter using Scanner#useDelimiter(String) to consume white space, commas, and literal '.'. Then use the supplied Comparator to compare the tokens available through the Scanner. Like,
static String findWord(Comparator<String> comp, String s1) {
Scanner sc = new Scanner(s1);
sc.useDelimiter("[\\s,\\.]+");
String max = null;
while (sc.hasNext()) {
String token = sc.next();
if (max == null || comp.compare(max, token) < 0) {
max = token;
}
}
return max;
}
Then, assuming you're using Java 8+, main can be written using Comparators already available like -
Comparator<String> stringLengthComparator = Comparator.comparingInt(
String::length);
Comparator<String> stringAlphaComparator = Comparator.naturalOrder();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String sentence = in.nextLine();
System.out.printf("Longest: %s%n", findWord(stringLengthComparator, sentence));
System.out.printf("Lexically: %s%n", findWord(stringAlphaComparator, sentence));
But, if you're using an earlier version - or you want to better understand what it does, the exact same code will work if you replace the two Comparators with equivalent code - like
Comparator<String> stringLengthComparator = new Comparator<String>() {
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
Comparator<String> stringAlphaComparator = new Comparator<String>() {
public int compare(String a, String b) {
return a.compareTo(b);
}
};
There's a lot of code there, nearly all of which is unnecessary.
Try this:
String longest = Arrays.stream(s.split(" +")).sort(comparing(String::length).reversed()).findFirst().get();
String highest = Arrays.stream(s.split(" +")).sort().reduce((a,b) -> b).get();
Note: Read and understand the code well before you submit your assignment.
Disclaimer: Code may not compile or even work as it was thumbed in on my phone (but there's a reasonable chance it will work)
As your post you can get the longest word. I will show you how to get the highest letter in alphabetical order of the longest word.
There is a method call toCharArray() you can use this method to make letter array of given word.
Than you can use casting to get integer value of the given char value
Then you can compare that integer value to get the highest integer value
Once you have the highest integer value cast that int value to char to take the letter
Following links to more information
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()
http://javaseeeedu.blogspot.com/2015/12/casting-part-1.html
I have change your code try it
import java.util.Scanner;
class MyString{
String s;
MyString( String s1 ){
s=s1;
}
void setString(String s1){
s=s1;
}
String getLongest(String s1){
s1 = s1 +" ";
int length = s1.length();
String temp="", longestw="";
char ltr;
int templ, longest=0;
for(int i=0; i<length;i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp=temp+ltr;
}
else{
templ=temp.length();
if(templ>longest){
longest=templ;
longestw=temp;
}
temp="";
}
}
return longestw;
}
char getLargest(String s1){
int max = 0;
char []arr = s1.toCharArray();
int temp[] = new int[arr.length];
for(int i=0;i<arr.length;i++){
temp[i] = (int)arr[i];
if(i!=0){
if(temp[i-1] < temp[i]){
max = temp[i];
}else{
max = temp[i-1];
}
}
}
return (char)max;
}
}
class Demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String s = in.nextLine();
MyString s1 = new MyString(s);
System.out.println("The longest word is: " + s1.getLongest(s));
System.out.println("The largest letter is: " + s1.getLargest(s1.getLongest(s)));
}
}

Reversing characters in each word in a sentence - Stack Implementation

This code is inside the main function:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty() function:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence I am getting this output: lpmaxe. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
I am trying to achieve this:
This is a sentence ---> sihT si a ecnetnes
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
The simplest way to do this, I think, is to make use of the String split function, iterate through the words, and reverse their orders.
String[] words = sentence.split(" "); // splits on the space between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.print(reverseWord(word));
if (i < words.length-1) {
System.out.print(" "); // space after all words but the last
}
}
Where the method reverseWord is defined as:
public String reverseWord(String word) {
for( int i = 0; i < word.length(); i++) {
stk.push(word.charAt(i));
}
return stk.empty();
}
And where the empty method has been changed to:
public String empty() {
String stackWord = "";
while (this.first != null)
stackWord += this.pop();
return stackWord;
}
Original response
The original question indicated that the OP wanted to completely reverse the sentence.
You've got a double-looping construct where you don't really need it.
Consider this logic:
Read each character from the input string and push that character to the stack
When the input string is empty, pop each character from the stack and print it to screen.
So:
for( int i = 0; i < sentence.length(); i++) {
stk.push(sentence.charAt(i));
}
stk.empty();
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence you want it to output elpmaxe ecnetnes not ecnetnes elpmaxe.
The reason that you see lpmaxe instead of elpmaxe is because your inner while-loop doesn't process the last character of the string since you have i < sentence.length() - 1 instead of i < sentence.length(). The reason that you only see a single word is because your sentence variable consists only of the first token of the input. This is what the method Scanner.next() does; it reads the next (by default) space-delimited token.
If you want to input a whole sentence, wrap up System.in as follows:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine().
Hope this helps.
Assuming you've already got your input in sentence and the Stack object is called stk, here's an idea:
char[] tokens = sentence.toCharArray();
for (char c : tokens) {
if (c == ' ') {
stk.empty();
System.out.print(c);
} else {
stk.add(c);
}
}
Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change if (c == ' ') { to something like if (c == ' ' || c == '.' || c == ',') { and so on.)
As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
String s1 = "Hello World";
s1 = reverseSentence(s1);
System.out.println(s1);
s1 = reverseWord(s1);
System.out.println(s1);
}
private static String reverseSentence(String s1){
String s2 = "";
for(int i=s1.length()-1;i>=0;i--){
s2 += s1.charAt(i);
}
return s2;
}
private static String reverseWord(String s1){
String s2 = "";
StringTokenizer st = new StringTokenizer(s1);
while (st.hasMoreTokens()) {
s2 += reverseSentence(st.nextToken());
s2 += " ";
}
return s2;
}
}
public class ReverseofeachWordinaSentance {
/**
* #param args
*/
public static void main(String[] args) {
String source = "Welcome to the word reversing program";
for (String str : source.split(" ")) {
System.out.print(new StringBuilder(str).reverse().toString());
System.out.print(" ");
}
System.out.println("");
System.out.println("------------------------------------ ");
String original = "Welcome to the word reversing program";
wordReverse(original);
System.out.println("Orginal Sentence :::: "+original);
System.out.println("Reverse Sentence :::: "+wordReverse(original));
}
public static String wordReverse(String original){
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
return result.toString();
}
}
public class reverseStr {
public static void main(String[] args) {
String testsa[] = { "", " ", " ", "a ", " a", " aa bd cs " };
for (String tests : testsa) {
System.out.println(tests + "|" + reverseWords2(tests) + "|");
}
}
public static String reverseWords2(String s) {
String[] sa;
String out = "";
sa = s.split(" ");
for (int i = 0; i < sa.length; i++) {
String word = sa[sa.length - 1 - i];
// exclude "" in splited array
if (!word.equals("")) {
//add space between two words
out += word + " ";
}
}
//exclude the last space and return when string is void
int n = out.length();
if (n > 0) {
return out.substring(0, out.length() - 1);
} else {
return "";
}
}
}
This can pass in leetcode

Categories

Resources