Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I know I'm not supposed to do this but I am a beginner and I need help on this. I am wondering what I need in each number on the bottom. I am not asking for the code but just help on what to use.
Clarification:
What the problem is asking for is to go through the String one character at a time.
A "valid" word is written backwards in between ? and &
example: valid would be encrypted as ?dilav&
The entire message of encrypted words are also in reverse order.
I hope I made it more clear
Start by thinking how you would solve this in your head.
You would start at the left and look at each character until you found a '?'. Then you would note the letters until you found a '&'. Bingo, first word. Continue until you have all the words.
Now you know how many words you have (answer #2).
Then you need to reverse the letters in each word.
Now print them in the order you found them (answer #3).
Now print them in reverse order - the last word first (answer #4).
Now print the reversed list with spaces between them (answer #5).
Sample code (please try to understand how it works and don't just copy it and hand it in - or your teacher will ask you to explain how it works):
public static void main(final String[] args){
// example provided by Jason via Stackoverflow
String message = "&*#$#?ebyam,&?siht&=asdf???od&failure???&?on?nac&the%%#?uoy&horizon!";
System.out.println("#1: " + message.length());
List<String> words = new ArrayList<String>();
int questionPos = message.indexOf("?");
while(questionPos > -1) {
message = message.substring(questionPos + 1, message.length());
int ampersandPos = message.indexOf("&");
questionPos = message.indexOf("?");
if(ampersandPos > 0 && (ampersandPos < questionPos || questionPos == -1)) {
String word = message.substring(0, ampersandPos);
StringBuilder reversedWord = new StringBuilder();
for(int i = word.length() - 1; i >= 0; i--) {
reversedWord.append(word.charAt(i));
}
words.add(reversedWord.toString());
}
}
System.out.println("#2: " + words.size());
System.out.println("#3:");
for(final String word : words) {
System.out.println(word);
}
System.out.println("#4:");
for(int i = words.size() - 1; i >= 0; i--) {
System.out.println(words.get(i));
}
System.out.print("#5: ");
for(int i = words.size() - 1; i >= 0; i--) {
if(i < words.size() - 1) {
System.out.print(" ");
}
System.out.print(words.get(i));
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 4 years ago.
Improve this question
does anyone know whats wrong with my code? it keep getting error output in java GUI
the loop 2 and loop 3 getting error after debug, and i dont know whats wrong
private void butActionPerformed(java.awt.event.ActionEvent evt) {
String input1 = txtInput.getText();
String input2 = input1.toLowerCase();
char[] word1 = new char[input2.length()];
char[] word2 = new char[26];
for (int i = 0; i < word2.length; i++) {
word2[i] = (char) (97 + i);
}
int[] x = new int[26];
for (int i = 0; i < word1.length; i++) {
input1[i] = input2.charAt(i);
}
for (int i = 0; i < word2.length; i++) {
for (int j = 0; j < word1.length; j++) {
if (word2[i])==word1[j]) {
x[i]++;
}
}
}
txtOutput1.setText(Arrays.toString(word2));
txtOutput2.setText(Arrays.toString(x));
}
The first problem:
input1 is a string, but with input1[i] = input2.charAt(i); you are treating it as an array - this is not allowed in Java.
From your logic I think the corresponding line should be
word1[i] = input2.charAt(i);
The second problem: on the line
if (word2[i])==word1[j]) {
there is a closing parenthesis to much (after word2[i]), the line should read
if (word2[i]==word1[j]) {
input1 is a String variable and therefore immutable, which means it can only be assigned a new value and can not be changed otherwise.
The following line causes a problem:
input1[i] = input2.charAt(i);
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
Hello Stack Overflow Community. I developed a simple Java program to detect whether or not a word entered by the user is an Anagram. I do not receive the expected output based on the boolean value. Any ideas or suggestions are appreciated.
Note: This code does not include any methods or class functions that would make this a rather simple solution. Please work with the code below. Thank you!
import javax.swing.*;
public class Anagram
{
public static String word = " ";
public static boolean match = false;
public static void main(String[] args)
{
//Prompt the User for a Word
word = JOptionPane.showInputDialog("Please Enter A Word");
//Break the Word into an Array
String[] anagram = new String[word.length()];
for(int i = 0; i < word.length(); i++)
{
anagram[i] = Character.toString(word.charAt(i));
JOptionPane.showMessageDialog(null, anagram[i]);
}
//Create a duplicate Array
String[] anagram2 = new String[word.length()];
for(int i = word.length() - 1; i >= 0; i--)
{
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
//Do a search on each letter
for (int i = 0; i < anagram.length && i < anagram2.length; i++)
{
if(anagram.length == anagram2.length)
{
if(anagram[i].toLowerCase() == anagram2[i].toLowerCase())
{
match = true;
}
else
{
match = false;
}
}
else
{
JOptionPane.showMessageDialog(null, "There is a mismatch");
match = false;
}
}
//Prompt the user with the result
if(match == true)
{
JOptionPane.showMessageDialog(null, "Your Word is a Anagram!");
}
else if(match == false)
{
JOptionPane.showMessageDialog(null, "Your Word is NOT a Anagram!");
}
}
}
Assuming you mean palindrome:
Your code doesn't actually reverse the String.
for(int i = word.length() - 1; i >= 0; i--) {
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
This copies anagram into anagram2 without reversing it - it does go through it from back to front, but the result will be the same.
You need to do something like
for (int i = 0; i < word.length(); i++) {
anagram2[word.length() - i - 1] = anagram[i];
}
However, there really is no need to create the anagram and anagram2 arrays in the first place, you can just iterate through the String's data itself using charAt.
boolean match = true;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
match = false;
break;
}
}
Side note, you shouldn't declare word and match as static variables, keeping them local in main() will do.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}
There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}
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 8 years ago.
Improve this question
I don't want a string with the words sorted alphabetically. I need the letters of each word arranged alphabetically, but the order of words to remain the same.
Eg: Input string: welcome to java, Output string: ceelmow ot aajv
Try this:
String str = "welcome to java";
String strs[] = str.split(" ");
char[] ch;
StringBuilder strBuilder = new StringBuilder(str.length());
for (int i=0; i<strs.length; i++) {
ch = strs[i].toCharArray();
Arrays.sort(ch);
strBuilder.append(ch);
if (i != strs.length - 1) {
strBuilder.append(" ");
}
}
System.out.println(strBuilder.toString());
This could be solved using 5 steps
1) Split the String to words using foo.split(" ")
2) Get all the characters in the String using char[] bar=foo.toCharArray()
3) Sort the array using Arrays.sort(bar)
4) Turn the characters in a String using new String(bar)
5) Put all the characters back to a sentence
Don't forget to mind that capitals will come before not-capitals
Let me know if it works (or not)
Happy coding :) -Charlie
import java.util.Arrays;
public class StackOverflowExample {
public static void main(String[] args) {
String s = "welcome to java";
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i != 0) {
sb.append(" ");
}
char[] wordCharArray = words[i].toCharArray();
Arrays.sort(wordCharArray);
sb.append(wordCharArray);
}
System.out.println(sb.toString());
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can I break a line automatically into many lines without cutting off words? And the length for each new line will be around 4 words? I have many sentences thus I cannot use \n
e.g:
If I were you I would go to the cinema with her
becomes:
If I were you
I would go to
the cinema with her
Hope see your help soon. Thanks!
I would imagine, based on what you put although I'm not sure you're considering all possible cases, a way to get the specific answer you're looking for while taking a few things for granted and not directly relying on "\n" would be...
String s = "If I were you I would go to the cinema with her";
String[] strings = s.split(" ");
for(int i = 0; i < strings.length; ++i) {
if(i % 4 == 0) {
System.out.println();
}
System.out.print(strings[i] + " ");
}
Alternatively you might consider something like this, which would handle a max width of your text field as opposed to a set number of words since some words may be very long and cause a situation which you're trying to avoid...
int MAX = 20;
int length = 0;
String s = "If I were you I would go to the cinema with her.";
String[] strings = s.split(" ");
for(int i = 0; i < strings.length; ++i) {
if((length + strings[i].length()) > MAX ) {
System.out.println();
length = 0;
}
System.out.print(strings[i] + " ");
length += strings[i].length() + 1;
}
Edit:
I did as you requested. This is what I get from the MAX option...
If I were you I
would go to the
cinema with her and
abc xyz
And this is what I get for the regular...
If I were you
I would go to
the cinema with her
and abc xyz
Not sure what's happening there, but I will say I jumped the shark on my answer. You've tagged Android and you and I both know System.out.println() is a no-no in that environment, at least if you expect to see any results. Sorry about that.
you need to count the number of spaces in a for loop here is a code to demonstrate it. please change the variables according to your application
String tv2 = tv.getText().toString(); // take a string textVIew, you can make it editView
StringBuilder sb = new StringBuilder(tv2); // add the string to stringBuilder
int howManySpaces = 0; // this for counting the spaces.
for (int i = 0; i < tv2.length(); i++)
{
if (tv2.charAt(i) == ' ') //if space found add one to howManySpaces
{
howManySpaces += 1;
Log.d("HMS", String.valueOf(howManySpaces));
}
if (howManySpaces == 4) // if howManySpaces == 4 break it to new line
{
sb.replace(i, i+1, "\n");
howManySpaces = 0;
}
}
tvNew.setText(sb.toString()); // add to the new textView the result after breaking.
I just tried it right now, with same sentences it gave me the desired result.
feel free to ask me if you didnt understand any part.
I have tried the following code, it worked fine for me, please try this and kindly let me if you have any trouble on this
// Calling the SentenceBreaker method which helps the String to split.
sentenceBreaker("If I were you I would go to the cinema with her");
// Method which spilts the Sentence
private void sentenceBreaker(int noOfWords,String inputSentence){
boolean previousCharWhiteSpace = true; // just a flag
boolean initialFlag =false;
int wordCount = 0;
int i,count =0;
for (i = 0; i < inputSentence.length(); i++) {
if (inputSentence.charAt(i) == ' ' && !previousCharWhiteSpace) {
wordCount++;
previousCharWhiteSpace = true;
if (wordCount == noOfWords) {
if(count == 0){
inputSentence = inputSentence.substring(0,wordCount)
+ "\n"
+ inputSentence.substring(wordCount,
inputSentence.length());
wordCount = 0;
count=i;
}
else{
inputSentence = inputSentence.substring(count, i)
+ "\n"
+ inputSentence.substring(i,
inputSentence.length());
wordCount = 0;
count=i;
}
}
} else if (!(inputSentence.charAt(i) == ' ')) {
previousCharWhiteSpace = false;
}
}
/*
* the for loop increments the word count if a space is encountered
* between words,for multiple spaces between words it wont update the
* counter-hence the use of the boolean flag.
*/
if (!(inputSentence.charAt(i - 1) == ' ')) {
wordCount++;
}
// just to make sure that we count the last word in the sentence as well
System.out.println("No of words-" + wordCount);
System.out.println("Sentence" + inputSentence);
}
/* Output */
Sentence If I were you
I would go to
the cinema with her**
As Per Your Requirement..Following logic will be works fine..Please Use it
String stT="If I were you I would go to the cinema with her";
String[] sT=stT.split(" ");
StringBuffer sb=new StringBuffer();
for(int i=0;i<sT.length;i++)
{
if(i%4==3)
sb.append(sT[i]+"\n");
else
sb.append(sT[i]+" ");
}
System.out.print(sb.toString());