I am having problem in my code and I cannot figure out why?
I am trying to compare strings to find common characters. I am missing the first character of first letter.
package findEquals;
import java.io.*;
class charequals {
public String name1, name2;
int l1, l2, m;
void getInputs() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter First Name(Enter \"1\" for \"AMITABH BACHCHAN\")\n");
name1 = br.readLine();
if (name1.equals("1"))
name1 = "AMITABH BACHCHAN";
System.out
.println("Enter Second Name(Enter \"1\" for \"RAJNIKANTH\")\n");
name2 = br.readLine();
if (name2.equals("1"))
name2 = "RAJNIKANTH";
} catch (IOException e) {
e.printStackTrace();
}
}
void findEquals() {
getInputs();
l1 = name1.length();
l2 = name2.length();
for (int i = 0; i < l1; i++) {
for (int j = 0; j < i; j++) {
if (name1.charAt(i) == name1.charAt(j)) {
m = 0;
break;
}
}
if (m == 0) {
m = 1;
continue;
}
for (int k = 0; k < l2; k++) {
if (name2.charAt(k) == name1.charAt(i)) {
System.out.println(name1.charAt(i) + " ");
break;
}
}
}
}
public static void main(String[] args) {
charequals a = new charequals();
a.findEquals();
}
}
OUTPUT(for default values): I T H N
It should be : A I T H N
Why am I missing the first letter?
This is what you need:
import java.io.*;
class charequals {
public String name1, name2;
int l1, l2, m;
void getInputs() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter First Name(Enter \"1\" for \"AMITABH BACHCHAN\")\n");
name1 = br.readLine();
if (name1.equals("1"))
name1 = "AMITABH BACHCHAN";
System.out
.println("Enter Second Name(Enter \"1\" for \"RAJNIKANTH\")\n");
name2 = br.readLine();
if (name2.equals("1"))
name2 = "RAJNIKANTH";
} catch (IOException e) {
e.printStackTrace();
}
}
void findEquals() {
getInputs();
l1 = name1.length();
l2 = name2.length();
for (int i = 0; i < l1; i++) {
for (int j = 0; j < l2; j++) {
if ( name1.charAt(i) == name2.charAt(j) ) {
System.out.print(name2.charAt(j) + " " );
char[] chars = name2.toCharArray();
chars[j] = '&';
name2 = new String(chars);
break;
}
}
}
}
public static void main(String[] args) {
charequals a = new charequals();
a.findEquals();
}
}
The changes are in findEquals(), i dind't understands very well your code but i guees this may help you to solve your problem. This work on ideone
Related
All words having the given length wordLength in the string sentence must be replaced with the word myWord. All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.
Here is my source code:
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String sentence = "";
int wordLength = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLength = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
Text myText = new Text(myWord, sentence, wordLength);
myText.changeSentence();
System.out.println("New string" + myText.getSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getSentence() {
return newSentence;
}
public void changeSentence() {
int firstPos = 0;
int i;
for (i = 0; i < mySentence.length(); i++) {
if (mySentence.charAt(i) == ' ') {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
} else if (i == mySentence.length() - 1) {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
}
}
}
}
I changed your code a little bit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String sentence = "";
int wordLenght = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
try {
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLenght = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Text myText = new Text(myWord, sentence, wordLenght);
System.out.println(myText.getChangeSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getChangeSentence() {
String[] words = mySentence.split(" ");
for(int i = 0 ; i < words.length ; i++) {
if(words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
for (String word : words) {
newSentence += word + " ";
}
return newSentence;
}
}
Input : This is a test
word length : 2
word to replace : ii
output: This ii a test
As I can see the only separator of words that is currently considered to appear in the input text is a single white space " ". If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.
Examples if you want to try with loops
public void changeSentence() {
final String[] words = mySentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
newSentence = String.join(" ", words);
}
or with regular expressions
public void changeSentence() {
String regex = "\\b\\w{" + charNumber+ "}\\b";
newSentence = mySentence.replaceAll(regex, wordToChange);
}
or with the stream API
public void changeSentence() {
newSentence = Arrays.stream(mySentence.split(" "))
.map(s -> s.length() == charNumber ? wordToChange : s)
.collect(Collectors.joining(" "));
}
I wrote a code for hangman, and i want to pass the randomly guessed word(randomly guessed from a text file), to be passed to a function hangman() where i can get the length of the word. a random word will be guessed from the getRandomWord(String path) function and I have passed value obtained to function() But cannot seem to pass the and get the result.
public class Main {
public static void main(String[] args) throws IOException {
Main ma = new Main();
String stm= null;
loadWords();
//hangman(w);
function();
}
public static String[] loadWords() {
System.out.println("Loading words from file :");
try {
File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNext()) {
String data = myReader.nextLine().toLowerCase();
String[] spl = data.split(" ");
System.out.println(spl.length + " words loaded");
return spl;
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return null;
// TODO: Fill in your code here
}
public static String getRandomWord(String path) throws IOException {
List<String> words = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
String[] wordline = line.split("\\s+");
for (String word : wordline) {
words.add(word);
}
}
}
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
public static List< String> getRemainingLetters(ArrayList< String> lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha1 = alpha.split("");
ArrayList< String> alpha2 = new ArrayList<>(Arrays.asList(alpha1));
for (int i = 0; i < lettersGuessed.size(); i++) {
for (int j = 0; j < alpha2.size(); j++) {
if (alpha2.get(j).equals(lettersGuessed.get(i))) {
alpha2.remove(j);
break;
}
}
}
return alpha2;
}
public static void function() throws IOException {
int numGuesses = 5;
String w = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
String[] word = w.split("");
ArrayList< String> wList = new ArrayList<>(Arrays.asList(word));
ArrayList< String> wAnswer = new ArrayList< String>(wList.size());
for (int i = 0; i < wList.size(); i++) {
wAnswer.add("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner(System.in);
boolean notDone = true;
ArrayList< String> lettersGuessed = new ArrayList< String>();
while (notDone) {
System.out.println();
String sOut = "";
List< String> lettersLeft = getRemainingLetters(lettersGuessed);
for (String s : lettersLeft) {
sOut += s + " ";
}
System.out.println("Letters Left: " + sOut);
sOut = "";
for (int i = 0; i < wList.size(); i++) {
sOut += wAnswer.get(i);
}
System.out.println(sOut + " Guesses left:" + numGuesses);
System.out.print("Enter a letter(* exit): ");
String sIn = scanner.next();
numGuesses--;
if (sIn.equals("*")) {
break;
}
lettersGuessed.add(sIn);
for (int i = 0; i < wList.size(); i++) {
if (sIn.equals(wList.get(i))) {
wAnswer.set(i, sIn);
left--;
}
}
if (left == 0) {
System.out.println("Congradulations you guessed it!");
break;
}
if (numGuesses == 0) {
StringBuilder sb = new StringBuilder();
for (String string : wList) {
sb.append(string);
}
String stm = sb.toString();
System.out.println("Sorry you ran out of guesses, the word was: " + stm);
break;
}
}
}
public static void hangman(String word) {
System.out.println("Welcome to Hangman Ultimate Edition");
System.out.println("I am thinking of a word that is " + word.length() + " letters long");
System.out.println("-------------");
}
}
Problems in your code:
Not passing the random word to the methods, hangman and function.
Instead of re-using the random word obtained from the method, getRandomWord in main, you have called getRandomWord again in the method, hangman which will give you a different random word causing incosistency.
Given below is the corrected program with a sample run:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String word = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
hangman(word);
function(word);
}
public static String getRandomWord(String path) throws IOException {
List<String> words = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
String[] wordline = line.split("\\s+");
for (String word : wordline) {
words.add(word);
}
}
}
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
public static List<String> getRemainingLetters(ArrayList<String> lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha1 = alpha.split("");
ArrayList<String> alpha2 = new ArrayList<>(Arrays.asList(alpha1));
for (int i = 0; i < lettersGuessed.size(); i++) {
for (int j = 0; j < alpha2.size(); j++) {
if (alpha2.get(j).equals(lettersGuessed.get(i))) {
alpha2.remove(j);
break;
}
}
}
return alpha2;
}
public static void function(String w) throws IOException {
// The available number of guesses = length of the random word
int numGuesses = w.length();
// Split the random word into letters
String[] word = w.split("");
ArrayList<String> wList = new ArrayList<>(Arrays.asList(word));
ArrayList<String> wAnswer = new ArrayList<String>(wList.size());
for (int i = 0; i < wList.size(); i++) {
wAnswer.add("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner(System.in);
boolean notDone = true;
ArrayList<String> lettersGuessed = new ArrayList<String>();
while (notDone) {
System.out.println();
String sOut = "";
List<String> lettersLeft = getRemainingLetters(lettersGuessed);
for (String s : lettersLeft) {
sOut += s + " ";
}
System.out.println("Letters Left: " + sOut);
sOut = "";
for (int i = 0; i < wList.size(); i++) {
sOut += wAnswer.get(i);
}
System.out.println(sOut + " Guesses left:" + numGuesses);
System.out.print("Enter a letter(* exit): ");
String sIn = scanner.next();
numGuesses--;
if (sIn.equals("*")) {
break;
}
lettersGuessed.add(sIn);
for (int i = 0; i < wList.size(); i++) {
if (sIn.equals(wList.get(i))) {
wAnswer.set(i, sIn);
left--;
}
}
if (left == 0) {
System.out.println("Congradulations you guessed it!");
break;
}
if (numGuesses == 0) {
StringBuilder sb = new StringBuilder();
for (String string : wList) {
sb.append(string);
}
String stm = sb.toString();
System.out.println("Sorry you ran out of guesses, the word was: " + stm);
break;
}
}
}
public static void hangman(String word) {
System.out.println("Welcome to Hangman Ultimate Edition");
System.out.println("I am thinking of a word that is " + word.length() + " letters long");
System.out.println("-------------");
}
}
A sample run:
Welcome to Hangman Ultimate Edition
I am thinking of a word that is 3 letters long
-------------
Letters Left: a b c d e f g h i j k l m n o p q r s t u v w x y z
_ _ _ Guesses left:3
Enter a letter(* exit): c
Letters Left: a b d e f g h i j k l m n o p q r s t u v w x y z
_ _ _ Guesses left:2
Enter a letter(* exit): a
Letters Left: b d e f g h i j k l m n o p q r s t u v w x y z
_ _ _ Guesses left:1
Enter a letter(* exit): t
Sorry you ran out of guesses, the word was: fox
To make your existing code run, you should just clean up the main method:
remove unused code:
Main ma = new Main(); // no need to create an instance, you use only static methods
String stm= null; // not used anywhere
loadWords(); // not used, entire method may be removed:
// it reads words only in the first line
fix method function to have a String w parameter, move getting the random word out of this method.
Thus, resulting changes should be:
public static void main(String[] args) throws IOException {
String word = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
hangman(word);
function(word);
}
public static void function(String w) throws IOException {
int numGuesses = 5;
String[] word = w.split("");
// ... the rest of this method remains as is
}
I am working on implementing a generic code to solve left recursion problem in a grammar using java so my code is working as follows I am reading an input like this as each line goes to the next line:
E
E+T|T
T
T*F|F
F
(E)|id|number
and the required output is supposed to be like this one :
E->[TE']
T->[FT']
F->[(E), id, number]
E'->[+TE', !]
T'->[*FT', !]
I wrote that code which is storing input in Arraylists to iterate over them and produce the output:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class IleftRecursion {
//storing each line in its corresponding Arraylist
static ArrayList<String> leftRules = new ArrayList<>();
static ArrayList<String> rightRules = new ArrayList<>();
public static void read_file(String file) throws IOException {
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
leftRules.add(line);
rightRules.add(br.readLine());
}
br.close();
}
public static void ss() {
for (int i = 0; i < leftRules.size(); i++) {
for (int j = 1; j <= i - 1; j++) {
//splitting inputs on bars "|" to iterate through them
for (String x : rightRules.get(i).split("\\|")) {
if (x.contains(leftRules.get(j))) {
String f = "";
String ff = "";
for (int k=0; k<rightRules.get(k).split("\\|").length;k++) {
f = x;
f = f.replaceAll(leftRules.get(i), rightRules.get(k).split("\\|")[k]);
ff += f;
}
rightRules.remove(i);
rightRules.add(i, ff);
}
}
}
//Recursive or Not boolean
boolean isRec = false;
for (String z : rightRules.get(i).split("\\|")) {
if (z.startsWith(leftRules.get(i))) {
isRec = true;
break;
}
}
if (isRec) {
String a = "";
String b = "";
for (String s : rightRules.get(i).split("\\|")) {
if (s.startsWith(leftRules.get(i))) {
b += s.replaceAll(leftRules.get(i), "") + leftRules.get(i) + "',";
} else {
a += s + leftRules.get(i) + "'";
}
}
b += "!";
if(a.length()>=1)
a.substring(1, a.length() - 1);
rightRules.add(i, a);
rightRules.add(i + 1, b);
leftRules.add(leftRules.get(i) + "'");
}
}
}
public static void main(String[] args) throws IOException {
read_file("Sample.in");
ss();
for (int i=0;i<leftRules.size();i++)
{
System.out.print(leftRules.get(i)+"->");
System.out.println("["+rightRules.get(i)+"]");
}
}
}
I debugged the code many times trying to figure out why Am I getting output like this
E->[TE']
T->[+TE',!]
F->[T]
E'->[T*F]
Which is missing One rule and also not all the new productions generated in the right way but I couldn't fix could anyone help me through that ?
My code reads a file called sort.txt, in which there are lexicon words ordered alphabetically and by length. There is one word in each line. The program works fine and please don't comment how it is written. The user then inputs a word he is searching for, e.g. "C**", and program returns all possible matches (Car, Cat, Cam, etc.). My question is how to search the array using binary search to speed things up. But the binary search would only be used if the first or first two or first 3 characters were input by the user, for instance "Ca*" or "Mou**". If the user inputs "***se" for instance, then the program would skip the binary search and would search the entire array.
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class main{
public static void main(String[] args) {
String izbira;
int dolzina=0;
Scanner in = new Scanner(System.in);
String vnos;
Scanner input = new Scanner(System.in);
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
ArrayList list3 = new ArrayList();
ArrayList list4 = new ArrayList();
ArrayList list5 = new ArrayList();
ArrayList list6 = new ArrayList();
ArrayList list7 = new ArrayList();
ArrayList list8 = new ArrayList();
ArrayList list9 = new ArrayList();
ArrayList list10plus = new ArrayList();
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 1) {
list1.add(vrstica);
}
if (vrstica.length() == 2) {
list2.add(vrstica);
}
if (vrstica.length() == 3) {
list3.add(vrstica);
}
if (vrstica.length() == 4) {
list4.add(vrstica);
}
if (vrstica.length() == 5) {
list5.add(vrstica);
}
if (vrstica.length() == 6) {
list6.add(vrstica);
}
if (vrstica.length() == 7) {
list7.add(vrstica);
}
if (vrstica.length() == 8) {
list8.add(vrstica);
}
if (vrstica.length() == 9) {
list9.add(vrstica);
}
if (vrstica.length() > 9) {
list10plus.add(vrstica);
}
}
do{
do {
System.out.println("Vnesi dožino besede, ki jo iščeš:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Napačen vnos! Poskusi ponovno:%n ",
in.nextLine());
}
} while (dolzina <= 0);
System.out.println("Vnesi besedo za neznano črko vpiši * :");
vnos = input.nextLine();
vnos = vnos.replace("*", ".");
if (dolzina == 1) {
for (int i = 0; i < list1.size(); i++) {
String s = (String) list1.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 2) {
for (int i = 0; i < list2.size(); i++) {
String s = (String) list2.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 3) {
for (int i = 0; i < list3.size(); i++) {
String s = (String) list3.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 4) {
for (int i = 0; i < list4.size(); i++) {
String s = (String) list4.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 5) {
for (int i = 0; i < list5.size(); i++) {
String s = (String) list5.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 6) {
for (int i = 0; i < list6.size(); i++) {
String s = (String) list6.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 7) {
for (int i = 0; i < list7.size(); i++) {
String s = (String) list7.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 8) {
for (int i = 0; i < list8.size(); i++) {
String s = (String) list8.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 9) {
for (int i = 0; i < list9.size(); i++) {
String s = (String) list9.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina > 9) {
for (int i = 0; i < list10plus.size(); i++) {
String s = (String) list10plus.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
This won't give you a complete answer, but just puts in that direction.
You need to check if the first char is not *, then do a binary search otherwise iterate over all the strings and do String.endsWith().
if(vnos.charAt(0) != '*') {
//do binary search with the substring
} else {
//iterate and check if the string endsWith given suffix.
}
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
Not sure why it gives me the NullPointerException. Please help.
I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.
import java.util.;
import java.io.;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName) + "\n");
System.out.println("Word-frequency statistics");
lengthFrequency(words);
System.out.println();
System.out.println("Wordlist dump:");
wordFrequency(words,fileName);
}
public static void wordFrequency(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
int [] array = new int [words.length];
while(s.hasNext()) {
String w = s.next();
if(w!=null){
for(int i = 0; i < words.length; i++){
if(w.equals(words[i])){
array[i]++;
}
}
for(int i = 0; i < words.length; i++){
System.out.println(words[i] + ":" + array[i]);
}
}
}
}
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int[10];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(w!=null){
if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}
}
for(int j = 0; j < 10; j++) {
System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
}
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}
There are two problems with this code
1.You didn't do null check,although the array contains null values
2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.
Your code should be like that
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w) //This one added for null check
{
/* if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}*/
//Don't need to check like that ...u can do like below
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w)
{
lengthTimes[i] =w.length();
}
}
}
//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}
}
Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception.
`
Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.
int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)
for(int i = 0; i < 10; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
When you declare:
String[] words = new String[MAX_WORDS];
You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:
if(w.length() >= 10) { // if w is null this would throw Npe
To fix it you may use a List instead:
List<String> words = new ArrayList<String>();
...
words.add( aWord );
Or perhaps you can use a Set if you don't want to have repeated words.