Java Crossword 2d Array - java

package assignment2;
import java.util.Random;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
int wordAmount = wordAmount();
String[] words = wordArray(wordAmount);
displayWords(words, wordAmount);
char[][] puzzleGrid = generatePuzzleGrid(words, wordAmount);
//System.out.println(Arrays.deepToString(puzzleGrid)); //just using this to test
printPuzzleGrid(puzzleGrid, wordAmount);
}
public static int wordAmount(){
Scanner input = new Scanner(System.in);
System.out.print("How many words would you like in the word search(5-15): ");
int wordAmount = input.nextInt();
while(wordAmount < 5 || wordAmount > 20){
System.out.println("The number you've requested is either to large or to small.");
System.out.print("How many words would you like in the word search(5-20): ");
wordAmount = input.nextInt();
}
return wordAmount;
}
public static String[] wordArray(int wordAmount){
String[] words = new String[wordAmount];
Scanner input = new Scanner(System.in);
for(int i = 0; i < wordAmount; i++){
System.out.print("Enter a word: ");
words[i] = (input.nextLine().toUpperCase());
for(int j = 0; j < wordAmount; j++){
if(j == i) break;
while(words[i].contains(words[j])){
System.out.print("The word you entered has already been entered, enter a new word: ");
words[i] = (input.nextLine().toUpperCase());
}
}
while(words[i].length() > 10 || words[i].length() <= 2 || words[i].contains(" ")){
System.out.print("The word you entered has been rejected, enter a new word: ");
words[i] = (input.nextLine().toUpperCase());
}
}
return words;
}
public static void displayWords(String[] words, int wordAmount){
System.out.print("The words you must find are: ");
for(int w = 0; w < wordAmount; w++){
System.out.print(words[w] + " ");
}
System.out.println("");
}
public static char[][] generatePuzzleGrid(String[] words, int wordAmount){
char[][] puzzleGrid = new char[wordAmount][wordAmount];
Random rand = new Random();
for(int across = 0; across < wordAmount; across++){
for(int down = 0; down < words[across].length(); down++){
puzzleGrid[across][down] = words[across].charAt(down);
for(int filler = wordAmount; filler >= words[across].length(); filler--){
puzzleGrid[across][filler] = (char)(rand.nextInt(26) + 'A'); //this is the line with the problem
}
}
}
return puzzleGrid;
}
public static void printPuzzleGrid(char[][] puzzleGrid, int wordAmount){
for(int across = 0; across < wordAmount; across++){
for(int down = 0; down < wordAmount; down++){
System.out.print(" " + puzzleGrid[down][across]);
}
System.out.println("");
}
}
}
It seems my last problem has worked itself out, but now I face a new problem.
Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at assignment2.test2.generatePuzzleGrid(test2.java:63)
at assignment2.test2.main(test2.java:10)
C:\Users\Higle\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 9 seconds)

It seams application runs without any issue only concern is that what will happen if the user provide wordAmount( number of characters in grid ) greater than the word he provided. So it's better to add validation on wordAmount with word length as show on below.
public static char[][] generatePuzzleGrid(String[] words, int wordAmount) {
if(wordAmount>words.length){
wordAmount = words.length;
}
char[][] puzzleGrid = new char[wordAmount][wordAmount];
for (int across = 0; across < wordAmount; across++) {
for (int down = 0; down < words[across].length(); down++) {
puzzleGrid[across][down] = words[across].charAt(down);/////////////////
}
}
return puzzleGrid;
}

It looks like you're calling charAt(5) on a string of less than 5 characters. You can do something like
if(words[across].length() < (down-1)){
continue;
}
to make sure you don't get that particular error... Also, you may like to know charAt() returns the index of a char from 0->length()-1

Related

How to insert a value in 2D array in java

How can I fill a 3x3 matrix using a 2D array such that the user picks what
position of the array they want to input their String value?
The position format is: (Row Number, Column Number)
For example:
Person 1, please pick where to place an X: (0,1)
Person 2, please pick where to place an O: (0,2)
This is what I have:
import java.util.Scanner;
public class idk {
public static void main(String[] args)
{
int i;
int j;
int arr[][] = new int[3][3];
// Getting user input
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr[i][j] = input.nextInt();
}
}
// Outputting the user input
System.out.println("The output is: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.printf("%d ", arr[i][j]);
}
}
}
}
Something like the following has most of the parts you would want, except for error handling. Input is number, space (or any whitespace), finally followed by another number. Input numbers are 1 to 3 inclusive, which is what a normal person would expect.
import java.util.Scanner;
public class TicTacToe {
char board[][] = new char[][]{{'-','-','-'},{'-','-','-'},{'-','-','-'}};
public static void main(String[] args) {
TicTacToe ttt = new TicTacToe();
ttt.run();
}
public void run() {
Scanner input = new Scanner(System.in);
int row = -1, col = -1;//just to initialize
char symbol = 'o';
while (true) {
symbol = (symbol == 'x')?'o':'x';
boolean error = false;
System.out.println("Enter a number: ");
if (input.hasNext()) {
row = input.nextInt();
System.out.println("row: " + row);
} else {
error = true;
}
if (input.hasNext()) {
col = input.nextInt();
System.out.println("col: " + col);
} else {
error = true;
}
if (!error) {
board[row - 1][col - 1] = symbol;
}else{
System.out.println("an error has occurred");
}
input.reset();
this.drawBoard();
}
}
public void drawBoard() {
System.out.println("The output is: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf("%c ", board[i][j]);
}
System.out.println();
}
System.out.println();
}
}
If you look up Scanner you will see an example to parse using a regex, I like that method better since with a regex you can validate the whole string at once but since that was not in the questions code I didn't use that method.
Simply
arr[Row Number][Column Number]=X;
eg
arr[0][1]=X;
or
arr[1][0]=O;
but because it is an int array you cannot place String i.e "O" and "X" in it.
Try making it an String array

How to print even and odd position characters of an array of strings in Java?

Question
Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line.
Assume input starts at index position 0(which is considered even)
Input
The first line contains an integer, T (the number of test cases).
Each line i of the T subsequent lines contain a String, S.
Output
For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.
Sample Input
2
Hacker
Rank
Sample Output
Hce akr
Rn ak
The Code I Wrote
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for(int i=0 ; i<T ; i++)
{
String myString = scan.nextLine();
int evn = 0,
odd = 0,
len = myString.length();
char strE[] = new char[50],
strO[] = new char[50];
for(int j=0 ; j<len ; j++)
{
if(j%2 == 0)
{
strE[evn] = myString.charAt(j);
evn++;
}
if(j%2 == 1)
{
strO[odd] = myString.charAt(j);
odd++;
}
}
System.out.print(strE);
System.out.print(" ");
System.out.println(strO);
}
}
My Output
Hce akr
Rn ak
The Problem
As you can see, my program successfully meets the test case, and other test cases (using custom input) but every time the HackerRank compiler tells me that my program did not meet the test case.
Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.
Could anyone please tell me where I am making a mistake?
Further Modifications
I then decided to change the last 3 lines of print statements into one statement as follows:
System.out.println(strE + " " + strO);
However, this time the program did not produce the desired output and rather printed some garbage values as follows:
[C#5c3f3b9b [C#3b626c6d
[C#3abc8690 [C#2f267610
My Doubts
1. In the first case, when I was printing the two strings separately using 2 print statements, I was getting a correct output everytime but the HackerRank compiler rejected it. Why?
2. In the second case, when I modified the program by using one print statement instead of 3 to get the desired result, the program gave a completely different output and rather printed garbage values! Why?
Here is a link to the HackerRank problem for more info:
hackerrank.com/challenges/30-review-loop
All help and guidance is greatly appreciated and thanks a lot in advance!
Try to submit this:
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for (int i = 0; i < T; i++) {
String myString = scan.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < myString.length(); j++) {
if (j % 2 == 0) {
even += myString.charAt(j);
} else {
odd += myString.charAt(j);
}
}
System.out.println(even + " " + odd);
}
i get the right output and it should meet all the requirements. i think your code fails because its not a real string you print in the end and you have empty spots in your arrays
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the no.of test-cases:");
int t = scanner.nextInt();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String(s)");
for (int i = 0; i < t; i++) {
String myString = br.readLine();
String even = "";
String odd = "";
for (int j = 0; j < myString.length(); j++) {
if (j % 2 == 0) {
even += myString.charAt(j);
} else {
odd += myString.charAt(j);
}
}
System.out.println(even);
System.out.println(odd);
}
scanner.close();
int T = scan.nextInt();
This reads quantity of test cases, which we're going to process.
String string[] = new String[T];
for(int i = 0; i<T; i++){
string[i] = scan.next();
}
Next we're creating an array named "string" (BTW, this a bad name for variables/objects) which has size T and in the for loop reading test cases from the input T times and saving them in the array.
for(int temp = 0; temp<T; temp++){
Now, for each of test cases we do the following...
for(int j = 0; j<string[temp].length(); j = j+2)
{
System.out.print(string[temp].charAt(j));
}
We create a local variable j, which is visible only in this for loop. j holds index of the string (=string[temp]), which we're processing. So, we're printing a character on position j (by using standard method "charAt" of String class, which returns character of given index of the string) and then increasing it by 2. So, this code will print every even character. For string "example", it will print "eape" (j=0, j=2, j=4, j=6).
System.out.print(" ");
Separating sequences with a space.
for(int j = 1; j<string[temp].length(); j = j+2){
System.out.print(string[temp].charAt(j));
}
System.out.println();
We're doing the same (creating index j, running though all characters of the string), but starting from "1", so it will print all odd characters of the string. For string "example", it will give you "xml" (j=1, j=3, j=5). and After this, it will end the string. I hope, it will help you to understand. :)
I can solve your the second question:
---> System.out.print(strE);-->At the bottom, the method is called( public void print(char s[]));
-->System.out.println(strE + " " + strO);-->At the bottom, the method is called (public void println(String x) )
For your first answer I am unable to answer you as I have no idea about how the compiler works, but I can answer your second question.
The reason why System.out.print(strE); System.out.print(" "); System.out.println(strO); works is because System.out.print(char[]) and System.out.println(char[]) automatically turn the char arrays into a readable string before printing it.
However, in the second case System.out.println(strE + " " + strO);, what you are doing is directly turning the char array into strings, which just prints the class and the hash code of the array object because the toString() method is not overriden in the array class. What you want to do is System.out.println(new String(strE) + " " + new String(strO));. It will give you the result you want.
import java.io.*;
import java.util.*;
public class Solution {
private static void f(String s) {
// TODO Auto-generated method stub
char c[]=s.toCharArray();
int i,j;
for (i = 0; i <c.length;i++){
System.out.print(c[i]);
i+=1;
}
System.out.print(" ");
for (j = 1; j<c.length;j++){
System.out.print(c[j]);
j+=1;
}
}
public static void main(String[] args){
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int s=sc.nextInt();
while(hasNext()){
//for loop for multiple strings as per the input
for(int m=0;m<= s;m++){
String s1=sc.next();
f(s1);
System.out.println();
}
}
}
}
I've solved this question in 2 ways & both are producing correct output.
Have a look & let me know if you've any problem.
Instead of using char array, you can use String
//char[] even = new char[10000];
String even = "";
Let's look at the code
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String s = scanner.next();
char[] array = s.toCharArray();
int count=0;
//char[] even = new char[10000];
//char[] odd = new char[10000];
String even = "";
String odd = "";
for(char ch : array){
if(count%2 == 0){
even = even + ch;
}else{
odd = odd + ch;
}
count++;
}
count = 0;
System.out.println(even + " " + odd);
}
Output:
hacker
hce akr
No need of extra char[] or String to store even & odd position characters, we can directly print them using appropriate condition.
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
String s = scanner.next();
char[] array = s.toCharArray();
int count=0;
for(char ch : array){
if(count%2 == 0){
System.out.print(ch);
}
count++;
}
count = 0;
System.out.print(" ");
for(char ch : array){
if(count%2 != 0){
System.out.print(ch);
}
count++;
}
count = 0;
}
Output:
hacker
hce akr
Try this:
public static void main(String[] args) {
System.out.println("Enter string to check:");
Scanner scan = new Scanner(System.in);
String T = scan.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < T.length(); j++) {
if (j % 2 == 0) { //check the position of the alphabet by dividing it by 0
even += T.charAt(j);
} else {
odd += T.charAt(j);
}
}
System.out.println(even + " " + odd);
scan.close();
}
** JavaScript version **
function processData(input) {
for (let i = 1; i < input.length; i++) {
printOutput(input[i]);
}
}
function printOutput(input) {
var result = [];
input.length % 2 == 0 ? result[input.length / 2] = ' ': result[Math.ceil(input.length / 2)] = ' ';
for (let i = 0; i < input.length; i++) {
if (i % 2 == 0) {
result[i / 2] = input[i];
}
else {
result[Math.ceil(input.length / 2) + Math.ceil(i / 2)] = input[i];
}
}
console.log(result.join(''));
}
process.stdin.on("end", function () {
processData(_input.split('\n'));
});
import java.io. * ;
import java.util. * ;
public class Solution {
String myString;
public Solution(String myString) {
this.myString = myString;
int len = myString.length();
for (int j = 0; j < len; j++) {
if (j % 2 == 0) {
System.out.print(myString.charAt(j));
}
}
System.out.print(" ");
for (int j = 0; j < len; j++) {
if (j % 2 == 1) {
System.out.print(myString.charAt(j));
}
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System. in );
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
String word = sc.next();
Solution sol = new Solution(word);
System.out.println();
}
sc.close();
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int T;
T = s.nextInt();
String[] str = new String[T];
int i;
for(i=0;i<T;i++) {
str[i] = s.next();
}
for(i=0;i<T;i++) {
char[] even = new char[5000];
char[] odd = new char[5000];
int ev =0,od=0;
for(int j= 0;j< str[i].length();j++) {
if(j%2== 0) {
even[ev] = str[i].charAt(j);
ev++;
}else {
odd[od] = str[i].charAt(j);
od++;
}
}
String strEven = new String(even);
String strOdd = new String(odd);
System.out.print(strEven.trim());
System.out.print(" ");
System.out.println(strOdd.trim());
}
s.close();
}
}
I am sure that this will work You've forgotten to convert it to a string and also increase the size of the character array
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
int n= scan.nextInt();
for(int i=0;i<n;i++){
String s= scan.next();
int len= s.length();
StringBuffer str_e= new StringBuffer();
StringBuffer str_o= new StringBuffer();
for(int j=0;j<len;j++){
if(j%2==0)
str_e= str_e.append(s.charAt(j));
if(j%2==1)
str_o= str_o.append(s.charAt(j));
}
System.out.println(str_e+" "+str_o);
}
}
}
Try this:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner pp=new Scanner(System.in);
int n=pp.nextInt();
for(int i=0; i<n; i++)
{
String ip=pp.next();
String re1="",
re2="";
for(int j=0; j<ip.length(); j++)
{
if(j%2 == 0)
{
re1+= ip.charAt(j);
}
if(j%2 == 1)
{
re2+= ip.charAt(j);
}
}
System.out.print(re1+" "+re2);
System.out.println("");
}
}
}
public class PrintCharacters{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int noOfTestCases = sc.nextInt();
sc.nextLine();
String []inputStrings= new String[noOfTestCases];
for(int i=0;i<noOfTestCases;i++) {
inputStrings[i]=sc.nextLine();
}
for(String str: inputStrings) {
String even ="";
String odd ="";
for(int i=0;i<str.length();i++) {
if(i%2==0) {
even+=str.charAt(i);
}else {
odd+=str.charAt(i);
}
}
System.out.println(even+" "+odd);
}
sc.close();
}
}
Input:
2
Hacker
Rank
Output:
Hce akr
Rn ak
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
while(n>0) {
String str=scan.next();
for(int i=0;i<str.length();i++) {
if(i%2==0) {
System.out.print(str.charAt(i));
}
}
System.out.print(" ");
for(int i=0;i<str.length();i++) {
if(i%2==1) {
System.out.print(str.charAt(i));
}
}
n--;
System.out.println();
}
}
}

Not sure where to insert a for loop

I need to code a program that asks the user for the number of spaces between symbols.For eg,
& & &
& & &
& & &
The user will enter an integer and the spacing between the symbols should change.
I have the following code uptil now:
import java.util.Scanner;
public class Spacing
{
public static void main(String[]args)
{
Scanner c=new Scanner(System.in);
System.out.println("Enter spaces between stars: ");
int l=c.nextInt();
String a="*";
String b=" ";
for(int i=0;i<5;i++)
{
for(int j=0;j<l;j++)
{
System.out.print(a+b);
}
System.out.println();
}
}
}
I know how to change the number of symbols and the number of lines.But the problem is how to change the number of spaces.I feel as if there's going to be a for loop involved but I have no clue how to put one in.
Any help would be appreciated.
Here's something that improves readability and introduces some modularity in your code:
import java.util.Scanner;
public class Spacing {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter spaces between stars: ");
int numSpaces =scanner.nextInt();
String charToDisplay = "*";
String spaces = buildNSpaces(numSpaces);
int numberOfRows = 3;
int numberOfCharactersPerRow = 3;
for(int i = 0; i < numberOfRows; i++) {
for(int j=0; j < numberOfCharactersPerRow; j++) {
System.out.print(charToDisplay+spaces);
}
System.out.println();
}
}
private static String buildNSpaces(final int numSpaces) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < numSpaces; i++) {
builder.append(" ");
}
return builder.toString();
}
}
for(int i = 0;i < l;i++)
{
System.out.print(" ");
}
code above will print the number of spaces you input.
so you can use it like:
for(int i = 0; i < 3; i++)
{
System.out.print("&");
for(int j = 0; j < l; j++)
System.out.print(" ");
}
this will print out
& & & (there's 3 spaces after the last & also)
if you input 3 in l.
you need another variable and another for loop
try this one
public class Spacing
{
public static void main(String[]args)
{
Scanner c=new Scanner(System.in);
System.out.println("Enter spaces between stars: ");
int l=c.nextInt();
String a="*";
String b=" ";
for(int i=0;i<5;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(a);
for(int k=0;k<l;k++)
{
System.out.print(b);
}
}
System.out.println();
}
}
}

How do I create a method that displays how many elements are in the array?

I'm fairly new to Java, but here's my problem.
I've created an array method that holds a block of 10 integers, which the user will input. They will enter -1 when they are finished, however the -1 will be stored. Here's my code for that:
public static int [] inputGrades()
{
Scanner kb = new Scanner (System.in);
int [] iGrades = new int [10];
System.out.print("\nInput test scores, enter -1 when you're finished.\n");
for (int i =0; i<iGrades.length;i++)
{
if (iGrades[i]>=-1)
{
iGrades[i]=kb.nextInt();
break;
}
}
return iGrades;
}
After that I'm to create a method that is supposed to count how many number values there are up to the -1. So say, the user entered 5 numbers and -1, I'd display 6. Here's what I have for that:
public static int countArrayElements(int[] array)
{
int iCount = 0;
for (int i = 0; i < array.length; i ++)
{
if (array[i] != 0)
{
iCount ++;
}
System.out.print ("\nThere are " + iCount + "numbers in the array.");
}
return iCount;
}
All it's returning is 10 ones though. A nudge in the right direction would be greatly appreciated, thanks.
There are problems with both of your methods, Change them to the following, First initialize your array:
public static int [] inputGrades(){
System.out.print("\nInput test scores, enter -1 when you're finished.\n");
Scanner kb = new Scanner (System.in);
int [] iGrades = new int [10];
for (int i =0; i<iGrades.length;i++){
iGrades[i] = Integer.MIN_VALUE;
}
for (int i =0; i<iGrades.length;i++){
iGrades[i]=kb.nextInt();
if (iGrades[i] ==-1)
break;
}
kb.close(); // Don't forget to close the scanner
return iGrades;
}
public static int countArrayElements(int[] array){
int iCount = 0;
for (int i = 0; i < array.length; i ++)
{
if(array[i] > -1){
iCount++;
}
}
System.out.print ("\nThere are " + iCount + " numbers in the array.");
return iCount;
}
Each component of the one-dimensional array is initialized to its default value. So for int it's 0, that your method return array's length. Check specification
May be you need to use, if else condition to break the loop..
for (int i =0; i<iGrades.length;i++)
{
if (iGrades[i]==-1)
{
break;
}
else{
iGrades[i]=kb.nextInt();
}
}
This loop accepts 10 elements , and it the user enters only -1 it will break.
public static int countArrayElements(int[] array)
{
int iCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] != -1)
{
iCount ++;
}
}
System.out.print ("\nThere are " + (iCount+1) + "numbers in the array.");
return iCount;
}
Here printing of (iCount+1) is to count -1 also.
Instead of two methods, it can be possible in single method as i did using ArrayList
public static int inputGrades()
{
Scanner scanner = new Scanner (System.in);
int GRADE_SIZE = 10;
List<Integer> iGrades = new ArrayList<>();
System.out.print("\nInput test scores, enter -1 when you're finished.\n");
for (int idx = 0; idx < GRADE_SIZE; idx++)
{
int inputNum = scanner.nextInt();
iGrades.add(inputNum);
if(inputNum == -1){
break;
}
}
return iGrades.size();
}
Main
public static void main(String[] args) {
System.out.println("Grade Size :: "+inputGrades());
}

How can my syntax error be fixed?

I am a beginner with weak understanding of java. Please could you help me correct the error saying:
// [line 45] Syntax error on token " (", ; expected
On the line:
private static int countWords(String str) {
This error appears twice on this line. I've tried experimenting with adding and deleting brackets and I've tried adding ';' to my code but it only makes the code display more errors. Underneath there is my code to help identify the error better:
import java.util.*;
public class HDtest9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) { // have created infinite loop
System.out.print("Enter text: ");
String sentence = in.nextLine();
System.out.println("You have entered: " + sentence); // to Print string
System.out.println("The total number of characters is " + sentence.length()); // to print Entered string's length
System.out.println("This piece of text has " + countWords(sentence) + " words.");
if (sentence.equals("quit")) { // if enterd value is "quit" than it comes out of loop
break;
} else {
String[] words = sentence.split(" "); // get the individual words
int maxWordLength = 0;
int wordLength = 0;
for (int i = 0; i < array.length; i++) {
wordLength = array[i].length();
if (wordLength > maxWordLength) {
maxWordLength = wordLength;
}
int[] intArray = new int[maxWordLength + 1];
for (int i = 0; i < array.length; i++) {
intArray[array[i].length()]++;
for (int i = 1; i < intArray.length; i++) {
out.printf("%d word(s) of length %d<br>", intArray[i], i);
}
}
for (int i = 0; i < words.length; i++)
System.out.println( "word " + i + ": " + words[i] + " = " + words[i].length() + " characters");
}
}
in.close();
}
private static int countWords(String str) {
String words[] = str.split(" ");
int count = words.length;
return count;
}
}
}
Thank you very much for any help, it's much appreciated!
You are trying to declare your countWords() method inside your main() method, which isn't legal in Java, so the compiler is choking trying to parse your method signature.
If you move it outside where it belongs, you will only have the other 8 or so undeclared and duplicate variable errors left to deal with.
Please use proper indentation and naming in your code. It will help you (and others) read it, and prevent this sort of mistake.
On the line:
for (int i = 0; i < words.length; i++)
You have no opening curly brace
Change to:
for (int i = 0; i < words.length; i++) {
Also, please fix your indentation, it is very hard to read and see if there are any more bugs.
Corrected and working code
import java.util.*;
public class HDtest9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) { // have created infinite loop
System.out.print("Enter text: ");
String sentence = in.nextLine();
System.out.println("You have entered: " + sentence); // to Print string
System.out.println("The total number of characters is " + sentence.length()); // to print Entered string's length
System.out.println("This piece of text has " + countWords(sentence) + " words.");
if (sentence.equals("quit")) { // if enterd value is "quit" than it comes out of loop
break;
} else {
String[] words = sentence.split(" "); // get the individual words
int maxWordLength = 0;
int wordLength = 0;
for (int i = 0; i < words.length; i++) {
wordLength = words[i].length();
if (wordLength > maxWordLength) {
maxWordLength = wordLength;
}
}
int[] intArray = new int[maxWordLength + 1];
for (int i = 0; i < words.length; i++) {
intArray[words[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) {
System.out.printf("%d word(s) of length %d<br>", intArray[i], i);
}
for (int i = 0; i < words.length; i++) {
System.out.println("word " + i + ": " + words[i] + " = " + words[i].length() + " characters");
}
}
}
in.close();
}
private static int countWords(String str) {
String words[] = str.split(" ");
int count = words.length;
return count;
}
}

Categories