I need to know why my counter variable is looping [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 3 months ago.
Improve this question
So I have a method that receives a String[][] and a String(word).The method has to look for the word from the 2dArray and should display one of the other words in the same row. Also I need to ignore(not display) and count(++) the empty spots that are in the same row. I want to know why my counter is looping and it wont let me ignore those empty spaces.
public static void main(String[] args) {
String[][] array2d = {{"joe", "slim", "ed", "george"},
{"soto", "", "", "" },
{"billy", "sanchez", "carlos", "fernando"}};
sort(array2d, "soto");
}
public static void sort(String[][] matrix, String word) {
int counterForArrayLength = 0;
boolean random = true;
boolean exit = true;
String optionFromUser = "";
do {
random = true;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j].equals(word)) {
for (int k = 0; k < matrix[0].length; k++) {
while (random) {
String randomWord = matrix[i][(int) (Math.random() * matrix[0].length)];
String testRandom = "" + randomWord;
if (randomWord.equals(word)) {
random = true;
} else {
if (randomWord.equals("")) {
counterForArrayLength++;
System.out.println("" + counterForArrayLength);
} else {
JOptionPane.showMessageDialog(null, randomWord);
optionFromUser = JOptionPane.showInputDialog("Desea obtener otro sinonimo? si/no \n Digite salir si asi lo desea.");
optionFromUser = optionFromUser.toLowerCase();
if (optionFromUser.equals("si") || optionFromUser.equals("s")) {
random = true;
} else {
random = false;
}
}
}
}
}
}
}
}
if (optionFromUser.equals("salir")) {
exit = false;
} else {
word = JOptionPane.showInputDialog("Digite otra palabra");
}
} while (exit);
}
run:
1
2
3
4
5
6
7
8
9
10
etc.

Your code sample missing essential information. However, the internal loop:
while(random)
{
// . . .
}
can run forever because you don't guarantee to have random variable to be set to false.
It will work only if you call the method with a word that isn't part of the array.
Also if you call it with word = "soto" then a chance is 100% that never leave the loop since out of 4 words there is one that you found and other 3 are empty.

Related

Trying to create a gridgenerator in java: [closed]

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 2 years ago.
Improve this question
I'm trying to create a program as described in the image linked below. I'm finding trouble with how to print the characters on the same line so that I can get 20 across and how to go to a new line after the first 20 characters have printed. Can you help me figure out a way to print the randomly selected characters into a 20 by 7 grid? Thank you for the help! Below is what I have so far but it's printing every new character on its own line and for gridArray[3] the forward-slash has to have two quotes otherwise it says that it's not a valid string. Does anyone know how I could solve these problems?
Link to Problem Directions
package edu.skidmore.cs106.lab09.problem14;
import java.util.Random;
public class GridGenorator {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] gridArray = new String[6];
gridArray[0] = "+";
gridArray[1] = "-";
gridArray[2] = "/";
gridArray[3] = "\"";
gridArray[4] = "|";
gridArray[5] = "_";
for (int elementx = 0; elementx < 7; elementx++) {
for(int elementy = 0; elementy<20; elementy++) {
Random rand = new Random();
int randomNum = rand.nextInt(6);
System.out.println(gridArray[randomNum]);
}
}
}
}
System.out.println prints a new line which you do not want to do every time, only after a group of 20, so try
for (int elementx = 0; elementx < 7; elementx++) {
for(int elementy = 0; elementy<20; elementy++) {
Random rand = new Random();
int randomNum = rand.nextInt(6);
System.out.print(gridArray[randomNum]);
}
System.out.println(); // now you want to print a newline
}

Java Anagram - Simple Challenge [closed]

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.

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

Breaking line - Android [closed]

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());

Get the longest substring from a string which is passed in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I want to pass in a string into a method e.g. "abbcccdef" and want it to return the longest substring. in this case it would be "ccc". Someone please help me with code that would help me solve this issue. I would like something basic that would allow a beginner to understand easily. This is what i have so far but it doesnt seem to work:
Many Thanks
public String getLongestSubstring(String s) {
int [] length = new int [s.length()];
String longestString = "";
if (s.length() > 0) {
char c = s.charAt(0);
for (int i=0;i<s.length();i++) {
for (int j=0;j<s.length();j++) {
if (c==s.charAt(j)) {
length [i]++;
} else {
c = s.charAt(j);
i++;
}
}
}
return longestString;
}
else
return null;
}
Follow the bellow mentioned algorithm sub-string sequence
I haven't tested this and I found and fixed one error already, but I think I've covered all the bases now. One limitation you didn't elaborate on in your question was the case in which there are two substrings of equal, longest length. i.e. abbbcccdef, I just return the first.
public String getLongestSubstring(String s)
{
if (s.length() == 0) return null;
//We need some data to start with.
char currentChar = s.charAt(0);
String longestString = "" + currentChar;
String runningString = "" + currentChar;
int currentLongestLength = 1;
for (int i = 1; i < s.length(); i++)
{
//Check the current char, is it the same?
if (s.charAt(i) == currentChar)
{
runningString = runningString + currentChar;
//Have we beaten our previous record.
if (runningString.length() > longestString.length())
{
//Increase the record.
currentLongestLength++;
longestString = runningString;
}
}
else
{
runningString = "" + s.charAt(i);
}
}
return longestString;
}
Here is how I implemented to find a longest SubString from a String.
public class LongestString {
public static void main (String[] args) throws java.lang.Exception {
System.out.println("Longest Substring is " + getLongestSubstring("abbcccdf"));
}
public static String getLongestSubstring(String s) {
int length = 1;
String longestString = "";
for (int i = 0; i < s.length(); i++) {
StringBuilder str = new StringBuilder();
str.append(s.charAt(i));
for (int j = i + 1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
str.append(s.charAt(j));
} else {
break;
}
}
if (length < str.length()) {
length = str.length();
longestString = str.toString();
}
}
return longestString;
}
}
Test it: http://ideone.com/JM904Y
public String getLongestSubString(String source) {
StringBuilder longestStringBuilder = new StringBuilder(source.length());
String longestString = "";
for(int i=0; i<source.length(); i++) {
if(longestStringBuilder.toString().contains(String.valueOf(source.charAt(i)))) {
if(longestString.length() < longestStringBuilder.toString().length()) {
longestString = longestStringBuilder.toString();
}
longestStringBuilder.setLength(0);
}
longestStringBuilder.append(source.charAt(i));
}
if(longestString.length() < longestStringBuilder.toString().length()) {
longestString = longestStringBuilder.toString();
}
return longestString;
}

Categories

Resources