Need help counting characters in an arrayList - java

import java.io.* ;
import java.util.ArrayList ;
public class WordSearchPuzzle;
{
private char[][] puzzle ;
private ArrayList<String> puzzleWords ;
private int letterCount = 0 ;
private int gridDimensions;
public WordSearchPuzzle(ArrayList<String> userSpecifiedWords)
{
this.puzzleWords = userSpecifiedWords ;
}
private void createPuzzleGrid()
{
int i;
for(i = 0; i < puzzleWords.size(i).length ; i++){
letterCount = puzzleWords + letterCount ;
}
}
gridDimensions = letterCount * 1.5;
puzzle[gridDimensions][gridDimensions];
}
public WordSearchPuzzle(String wordFile, int wordCount,
int shortest, int longest)
{
// puzzle generation using words from a file
// The user supplies the filename. In the file
// the words should appear one per line.
// The wordCount specifies the number of words
// to (randomly) select from the file for use in
// the puzzle.
// shortest and longest specify the shortest
// word length to be used and longest specifies
// the longest word length to be used.
// SO, using the words in the file randomly select
// wordCount words with lengths between shortest
// and longest.
}
private ArrayList<String> loadWordsFromFile(String filename, int shortest, int longest)
{
// BasicEnglish.txt - the 850 words of Basic English
// BNCwords.txt - "the 6,318 words with more than 800 occurrences in
//the whole 100M-word BNC"
try {
FileReader aFileReader = new FileReader(filename);
BufferedReader aBufferReader = new BufferedReader(aFileReader);
String lineFromFile;
int len ;
ArrayList<String> words = new ArrayList<String>();
lineFromFile = aBufferReader.readLine() ;
while (lineFromFile != null) {
len = lineFromFile.length() ;
if(len >= shortest && len <= longest) {
words.add(lineFromFile.toUpperCase());
}
lineFromFile = aBufferReader.readLine() ;
}
aBufferReader.close();
aFileReader.close();
return words ;
}
catch(IOException x)
{
return null ;
}
}
// The dimensions of the puzzle grid should be set
// by summing the lengths of the words being used in the
// puzzle and multiplying the sum by 1.5 or 1.75
// or some other (appropriate) scaling factor to
// ensure that the grid will have enough additional
// characters to obscure the puzzle words. Once
// you have calculated how many characters you are
// going to have in the grid you can calculate the
// grid dimensions by getting the square root (rounded up)
// of the character total.
}
Hi, small Java project I have to do here for college. Here is what I have so far. I don't understand why it's not compiling. I have code written for generating the grid; the grid dimensions are set by the input words (sum of letters of all input words * 1.5). I am not sure of the part which sums all the elements of the Array List together.
What's going on? Thanks in advance :)

I can see multiple problems:
In the class declaration line there should be no semi-colon.
public class WordSearchPuzzle
As Nettogrof has shown, you have too many }'s in the createPuzzleGrid method.
The loop within createPuzzleGrid uses methods that do not exist.
There is no size method that takes a parameter for array lists. Also it does not find the length of the string at that point
Your loop in createPuzzleGrid should be:
for (int i = 0; i < puzzleWords.size; i++) {
String item = puzzleWords.get(i);
int itemLength = item.length();
letterCount = letterCount + itemLength;
}
As an extra note, the last line of that method accesses the puzzle array but does not do anything, so this line could be removed. In fact no methods use the puzzle variable so it could be completely removed.

remove the semi-colon here.... public class WordSearchPuzzle;
this isn't a statement. puzzle[gridDimensions][gridDimensions];
puzzleWords.size(i).length in the for loop is giving issues. If you're wanting the number of elements in the list, puzzleWords.size() will work. And then letterCount = puzzleWords + letterCount ;
, you have incompatible types, ArrayList + int, are you meaning to use puzzleWords.size() instead of puzzleWords?

In your createPuzzleGrid, there's two } in your For-loop
The correctec version:
private void createPuzzleGrid()
{
int i;
for(i = 0; i < puzzleWords.size(i).length ; i++){
letterCount = puzzleWords + letterCount ;
}
gridDimensions = letterCount * 1.5;
puzzle[gridDimensions][gridDimensions];
}

Related

Making java output a specific number of characters, depending on the input in the console

I need to write a program that let's the user write 3 words in the console, then the program reprints those 3 words (one in each line) but also fills out the remaining spaces in each line with dots (".") so the total number of characters in each lines becomes a total of 30 characters.
Example:
Input:
Hello
Me
Overflow
Output:
.........................Hello
............................Me
......................Overflow
This is the code that I currently have which generates an error. I have been given the code (at the bottom) as part of my assignment and need to write the repeatChar method to make it work.
The first thing I did was to add the following commands in the code, in order to save the 3 words into the array threeWord.
threeWord[1] = wordOne;
threeWord[2] = wordTwo;
threeWord[3] = wordThree;
Next, I had to write the method repeatChar, and I decided to use a for-loop to make it repeat dots for each individual line, but I'm having a hard time making it fit with the rest of the code. Any guidance would be much appreciated, thanks.
import java.util.*;
public class FillDots {
private static int LineLength = 30;
public static void main(String[] arg) {
String[] threeWord = new String [3]; // Defines 3 locations to place strings in the array "threeWord"
Scanner console = new Scanner(System.in);
System.out.println("Type in three words:");
String wordOne = console.next();
threeWord[1] = wordOne; // Saves first word to array "threeWord"
String wordTwo = console.next();
threeWord[2] = wordTwo; // Saves second word to array "threeWord"
String wordThree = console.next();
threeWord[3] = wordThree; // Saves third word to array "threeWord"
for(int i = 0; i < threeWord.length; i++) {
System.out.println(repeatChar('.', LineLength - threeWord[i].length()) + threeWord[i]);
}
}
public static String repeatChar(String LineLength) {
for(int j = 0; j < LineLength; j++) {
System.out.print(".");
}
}
}
Besides the index starts from 0, you need return the dots in the repeatChar method:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
You can use existing library for doing padding
for(String temp:threeWord)
system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") );
this might simplify your code

How to reverse a String after a comma and then print the 1st half of the String Java

For example String grdwe,erwd becomes dwregrdwe
I have most of the code I just have trouble accessing all of ch1 and ch2 in my code after my for loop in my method I think I have to add all the elements to ch1 and ch2 into two separate arrays of characters but I wouldn't know what to initially initialize the array to it only reads 1 element I want to access all elements and then concat them. I'm stumped.
And I'd prefer to avoid Stringbuilder if possible
public class reverseStringAfterAComma{
public void reverseMethod(String word){
char ch1 = ' ';
char ch2 = ' ';
for(int a=0; a<word.length(); a++)
{
if(word.charAt(a)==',')
{
for(int i=word.length()-1; i>a; i--)
{
ch1 = word.charAt(i);
System.out.print(ch1);
}
for (int j=0; j<a; j++)
{
ch2 = word.charAt(j);
System.out.print(ch2);
}
}
}
//System.out.print("\n"+ch1);
//System.out.print("\n"+ch2);
}
public static void main(String []args){
reverseStringAfterAComma rsac = new reverseStringAfterAComma();
String str="grdwe,erwd";
rsac.reverseMethod(str);
}
}
You can use string builder as described here:
First split the string using:
String[] splitString = yourString.split(",");
Then reverse the second part of the string using this:
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
then append the two sections like so:
String final = splitString[1] + splitString[0];
And if you want to print it just do:
System.out.print(final);
The final code would be:
String[] splitString = yourString.split(",");
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
String final = splitString[1] + splitString[0];
System.out.print(final);
Then, since you are using stringbuilder all you need to do extra, is import it by putting this at the top of your code:
import java.lang.StringBuilder;
It appears you currently have working code, but are looking to print/save the value outside of the for loops. Just set a variable before you enter the loops, and concatenate the chars in each loop:
String result = "";
for (int a = 0; a < word.length(); a++) {
if (word.charAt(a) == ',') {
for (int i = word.length() - 1; i > a; i--) {
ch1 = word.charAt(i);
result += ch1;
}
for (int j = 0; j < a; j++) {
ch2 = word.charAt(j);
result += ch2;
}
}
}
System.out.println(result);
Demo
Let propose a solution that doesn't use a StringBuilder
You should knoz there is no correct reason not to use that class since this is well tested
The first step would be to split your String on the first comma found (I assumed, in case there is more than one, that the rest are part of the text to reverse). To do that, we can you String.split(String regex, int limit).
The limit is define like this
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n and the array's last entry will contain all input beyond the last matched delimiter.
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example :
"foobar".split(",", 2) // {"foobar"}
"foo,bar".split(",", 2) // {"foo", "bar"}
"foo,bar,far".split(",", 2) // {"foo", "bar,far"}
So this could be used at our advantage here :
String text = "Jake, ma I ,dlrow olleh";
String[] splittedText = text.split( ",", 2 ); //will give a maximum of a 2 length array
Know, we just need to reverse the second array if it exists, using the simplest algorithm.
String result;
if ( splittedText.length == 2 ) { //A comma was found
char[] toReverse = splittedText[1].toCharArray(); //get the char array to revese
int start = 0;
int end = toReverse.length - 1;
while ( start < end ) { //iterate until needed
char tmp = toReverse[start];
toReverse[start] = toReverse[end];
toReverse[end] = tmp;
start++; //step forward
end--; //step back
}
result = new String( toReverse ) + splittedText[0];
}
This was the part that should be done with a StringBuilder using
if ( splittedText.length == 2 ){
result = new StringBuilder(splittedText[1]).reverse().toString() + splittedText[0];
}
And if there is only one cell, the result is the same as the original text
else { //No comma found, just take the original text
result = text;
}
Then we just need to print the result
System.out.println( result );
hello world, I am Jake

Scrambling characters of String

public class WordScrambleEx1 {
public static void main(String[] args) {
String[] strArr = {"CHANGE", "LOVE", "HOPE", "VIEW"};
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question :" + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
String i = strArr[(int)Math.random()*4];
return i;
}
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
}
I am very new to Java and was given a question where I am given four letters of words and my method needs to pick one of them randomly using Math.random and scramble the characters of that string.
My code finds a String from the given array but does not scramble the string. Can anyone tell me what I am doing wrong?
Understanding constructor and scope is really hard.
first mistake:
(int) Math.random() * i
will always return 0, because Math.random() returns a float between 0 and 1, so it will always be zero when you cast it to int (int doesnt round, it just cuts off the numbers after the comma).
you can fix this by using this:
(int) (Math.random() * i)
now we are first multiplying the float result of Math.random() with i which results in a float because the first number is a float. then we are casting this float to an int.
second mistake:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
each iteration you create a new char array with a length of 0 and then you set question1 to it, which is always an empty string because the java array has nothing in it.
i would do it as follows:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = new String();
ArrayList<Character> chars = new ArrayList<Character>(); //an arraylist is an array wich dynamically changes its size depending on the amount of its elements
for (int i = 0; i < character.length; i++) {// first we put all characters of the word into that arraylist
chars.add(character[i]);
}
while(chars.size()>0){//then we iterate over the arraylist as long as it has more than 0 elements
int index = (int)(Math.random() * chars.size());//we create a random index in the range of 0 and the arraylists size
question1 += chars.get(index);// we add the letter at the index we generated to the scrambled word variable
chars.remove(index);// then we remove the character we just added to the scrambled word, from the arraylist, so it cant be in there twice
}// thus the size decreases by 1 each iteration until every element of the arrraylist is somewhere in the scrambled word
return question1;
}
There are some mistakes in your code. The way you generate random integers is misleading. Let's look at the statement (int)Math.random() * 4 for an explanation. Math.random() does:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Now, in Java a type cast has precedence over +, -, * and /, so what actually happens is ((int)Math.random()) * 4. Math.random() returns a floating point number between 0.0 and 1.0 exclusive, so roughly [0.0, 0.999999...]. A cast to int will truncate all decimal places and you will always get 0. Your statement then simplifies to 0 * 4 = 0. Overall, you always get the first word.
I recommend you to use the Random class instead. It provides a method nextInt(int n), which returns a random integer between 0 inclusive and n exclusive, so [0, n - 1].
Since there are a lot of errors in your code, I would like to provide you this solution:
import java.util.Random;
public class WordScrambleEx1 {
private static Random random;
public static void main(String[] args) {
// Create object of class (initializes the
// random generator with a default seed)
random = new Random();
String[] strArr = { "CHANGE", "LOVE", "HOPE", "VIEW" };
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
// Chooses a random index in [0, strArr.length - 1]
int index = random.nextInt(strArr.length);
String i = strArr[index];
return i;
}
public static String getScrambledWord(String str) {
String remaining = str;
String scrambled = "";
// Loop over the string, each time choose a random letter
// and add it to the scrambled word, then remove that letter
// from the remaining word. Repeat until all letters are gone.
for (int i = str.length(); i > 0; i--) {
// Choose the index of a letter in the remaining string
int index = random.nextInt(remaining.length());
// Add the letter at the random index to your scambled word
scrambled += remaining.charAt(index);
// Remove the chosen character from the remaining sequence
remaining = remaining.substring(0, index) + remaining.substring(index + 1);
}
return scrambled;
}
}

Partially Filled Array Null Values

so i've been brainstorming for a while now, im on my last and final step of homework. i think im actually done, it's just i need help getting rid of these null values:
here's the code:
public static char[] readArray(char[] words){
char[] letters = new char[words.length];
letters = myInput(); //get input message
for ( int i = 0 ; i < letters.length ; i++)
letters[i] = words[i] ; //store message to array of words
return words;
}
public static char[] myInput(){
// method to take message from user
String myMessage;
System.out.print("Input message: ");
Scanner myIn = new Scanner(System.in);
myMessage = myIn.nextLine();// Read a line of message
return myMessage.toCharArray();
}
public static void printOneInLine(char[] words){
//for every word, print them in a line
for (int i = 0 ; i < words.length ; i++){
if (words[i] == ' ') // words separated by space creates a new line
System.out.println();
else
System.out.print(words[i]); //print the word
}
}
test case:
input = hello world
output =
hello
world NUL NUL NUL NUL ...
i know the array is partially filled and because of i < words.length the system tries to display values of the array from 0 - 256. Any suggestions would be gladly appreciated. PS: new to java
It's time to simplify this: get rid of the readArray method, which does not add value on top of myInput, and use myInput instead. If you do this in the main(), it will work fine:
char[] words = myInput();
printOneInLine(words);
The rest of your code is fine as it is - no other changes are necessary (demo).
The instruction says, method readArray should return number of characters stored in the array.
You need to change your readArray method as follows:
public static int readArray(char[] words){
char[] letters = new char[words.length];
letters = myInput(); //get input message
for ( int i = 0 ; i < letters.length ; i++)
words[i] = letters[i] ; //store message to array of words
return letters.length;
}
Now your printOneInLine would need to change as well - it needs to take the length on the side, and use it in place of words.length to know when to stop:
public static void printOneInLine(char[] words, int len) {
//for every word, print them in a line
for (int i = 0 ; i < len ; i++){
if (words[i] == ' ') // words separated by space creates a new line
System.out.println();
else
System.out.print(words[i]); //print the character
}
}

Find longest strings

I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}

Categories

Resources