ReverseString program [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to make a ReverseString program. It's only returning one word only. I would like a full sentence.
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = input.next();
String reverse = "";
for (int i = word.length() - 1; i >= 0; i--)
reverse += word.charAt(i);
System.out.println(reverse);
}
}

You can use the reverse method of the StringBuilder/StringBuffer class.
Something like :
String reversedString = new StringBuilder(input.nextLine()).reverse().toString();
Or if you want a more low-level approach you could use a Stack push every character in it and pop it one by one to get the reversal of it.
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
stringBuilder.append(stack.pop());
}
return stringBuilder.toString();
}

Related

Command line arguments output issue Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
starting java coder here. I've been fighting with this issue for a while now(couple of hours) and finally decided to ask for help.
Desired output is "random arg random arg random arg!" - so the point is to add "!" after final arg.
Public class Cmdtest {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++)
System.out.print(args[i]+ "!");
}
}
Been trying this, but it adds "!" after every arg instead of last one. Any tips or ideas?
do like this:
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
}
System.out.println("!");
}
actually you were printing '!' in loop so it was being printed after every args
because you want it to be displayed at the end, you can use conditional operator(? :) to check the last iteration, try this one
public static void main(String[] args) {
for(int i = 0; i < args.length; i++)
System.out.print(i==args.length-1? args[i]+ "!":args[i]+ " ");
}

How to parse tokens from a mathematical equation? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a question on parser, whenever a user enters the expression like (a+b*c(d-e), He forgot to enter the other closing brace, and the program should give an error like It's a wrong Expression. Please help me out in doing this program, I have no idea how to start.
Use a stack data structure to validate the parenthesis matching.
If the character is '(','{','[' push the character onto the stack if the character is ')','}',']' respectively for the matching opening bracket then pop. Continue this till the stack is empty.
Code:
import java.util.*;
class ParenthesisMatching
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Stack<Integer> stk = new Stack<Integer>();
System.out.println("Enter expression");
String exp = scan.next();
if(isValid(exp))
System.out.println("matched");
else System.out.println("unmatched");
}
public static boolean isValid(String s) {
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();
}
}

Getting Ljava.lang.String;# in my output while iterating through a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
so I have to write a program for an assignment, and for that i have to accept a string, make sure it's got the right number of sentences and print the frequency of each word. I've got this almost completely right, but at the end, when I print the words (which I've stored in an array), each word is preceeded by Ljava.lang.String; #xyznumber. I have no idea why this is happening and I can't find a solution on the net. Here's my code:
import java.util.Arrays;
import java.io.*;
class frequency
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of sentences");
int cS = Integer.parseInt(br.readLine());
System.out.println("Enter sentences");
String s = br.readLine();
int cS1 = 0;
int cW = 0;
for(int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (ch=='.'||ch=='?')
{
cW++;
cS1++;
}
if (ch==' ')
{
cW++;
}
}
if (cS1!=cS)
{
System.out.println("You have entered the wrong number of sentences. Please try again.");
}
else
{
int c = 0;
int d = 0;
String a[] = new String[cW];
System.out.println("Total Number of words: "+cW);
for (int i= 0;i<s.length();i++)
{
char ch=s.charAt(i);
if (ch==' '||ch=='?'||ch=='.')
{
a[c++]=a+s.substring(d,i);
d = i+1;
}
}
int length=0;
firstFor: for(int i=0;i<a.length;i++)
{
for(int j=0;j<i;j++)
{
if (a[j].equalsIgnoreCase(a[i]))
{
continue firstFor;
}
else
{
length++;
}
}
}
String words[] = new String[length];
int counts[] = new int[length];
int k=0;
secondFor: for (int i =0;i<a.length;i++)
{
for(int j = 0; j<i;j++)
{
if (a[j].equalsIgnoreCase(a[i]))
{
continue secondFor;
}
}
words[k]=a[i];
int counter = 0;
for (int j =0;j<a.length;j++)
{
if(a[j].equalsIgnoreCase(a[i]))
{
counter++;
}
}
counts[k]=counter;
k++;
}
for (int i=0;i<words.length;i++)
{
System.out.println(words[i]+"\n"+(counts[i]));
}
}
}
}
The problem stems from this line here:
a[c++]=a+s.substring(d,i);
Since a is a String array, what this does is assigns one of the elements in a to be equal to the String representation of the entire array, plus a substring of s. Arrays don't have a very useful String representation though, which is where the Ljava.lang.String;#xyznumber you see is coming from.
Depending on what you want the first part of a[c] to be, either use an index into the array, or convert the array to a String

How to find substring without String methods using char arrays? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
You are not allowed to use any inbuilt functions like indexOf(), contains() or matches() of String class.
Find string apple in string webapple using given char arrays?
String webapple ="webapple";
String apple="apple";
char[] webappleArray=webapple.toCharArray();
char[] appleArray = apple.toCharArray();
write a function
public boolean isPresent(char[] apple ,char[] webapple ){
//your code here
}
I add it here in case someone really need it or want to study from it:
public static void main(String[] args) {
String webapple = "webapple";
String apple = "apple";
char[] webappleArray = webapple.toCharArray();
char[] appleArray = apple.toCharArray();
System.out.println(isPresent(appleArray, webappleArray));
}
public static boolean isPresent(char[] apple, char[] webapple) {
for (int i = 0; i < webapple.length - apple.length+1; i++) {
for (int j = 0; j < apple.length; j++) {
if (webapple[i + j] == apple[j]) {
if (j == apple.length - 1) {
return true;
}
} else {
break;
}
}
}
return false;
}

How to reverse words in string in java without using split and stringtokenizer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to reverse words in string of java without using split method and StringTokenizer.
For example, How are you must be printed in you are How.
I tried but I failed to do it.
Any help will be appreciated.
Try below code snippet
import java.util.ArrayList;
public class ReverseString
{
public static void main(String args[])
{
String myName = "Here we go";
ArrayList al = new ArrayList();
al = recursiveReverseMethod(myName,al);
al.trimToSize();
StringBuilder sb = new StringBuilder();
for(int i = al.size()-1; i>=0;i--)
{
sb.append(al.get(i)+" ");
}
System.out.println(sb);
}
public static ArrayList recursiveReverseMethod(String myName,ArrayList al)
{
int index = myName.indexOf(" ");
al.add(myName.substring(0, index));
myName = myName.substring(index+1);
if(myName.indexOf(" ")==-1)
{
al.add(myName.substring(0));
return al;
}
return recursiveReverseMethod(myName,al);
}
}
Here is another flavor based on the old time logic of String reversal in 'C'., from this thread.,
class testers {
public static void main(String[] args) {
String testStr="LongString";
testers u= new testers();
u.reverseStr(testStr);
}
public void reverseStr(String testStr){
char[] d= testStr.toCharArray();
int i;
int length=d.length;
int last_pos;
last_pos=d.length-1;
for (i=0;i<length/2;i++){
char tmp=d[i];
d[i]=d[last_pos-i];
d[last_pos-i]=tmp;
}
System.out.println(d);
}
}
I would do this:
public static String reverseWordsWithoutSplit(String sentence){
if (sentence == null || sentence.isEmpty()) return sentence;
int nextSpaceIndex = 0;
int wordStartIndex = 0;
int length = sentence.length();
StringBuilder reversedSentence = new StringBuilder();
while (nextSpaceIndex > -1){
nextSpaceIndex = sentence.indexOf(' ', wordStartIndex);
if (nextSpaceIndex > -1) reversedSentence.insert(0, sentence.substring(wordStartIndex, nextSpaceIndex)).insert(0, ' ');
else reversedSentence.insert(0, sentence.subSequence(wordStartIndex, length));
wordStartIndex = nextSpaceIndex + 1;
}
return reversedSentence.toString();
}

Categories

Resources