Results
0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 1
Car : 1
null : 1
Cat : 1
null : 1
Dog : 1
null : 1
Code
import java.util.Arrays;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String w;
int count = -1;
while (str.hasMoreTokens()) {
count++;
w = str.nextToken();
word[count] = w;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int z = 0; z < 7; z++) {
if (Arrays.asList(unique).contains(word[z])) {
measure[z] += 1;
System.out.println(unique[z] + " : " + measure[z]);
}
}
}
}
There are several problems in your current code:
You're using Collection interface explicitly. This is done every time you call Arrays#asList(...). You're not fulfilling with your main requirement.
You should maintain a counter for the elements in all your arrays. In this case, you could use the same variable to hold the size of both unique and measure arrays.
Your algorithm to fill unique is wrong. You should only add the word once (since it must be unique).
You should add the counter for measure only once per every String in unique array.
This code takes into account all these recommendations.
import java.util.StringTokenizer;
public class ThirteenthMain {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
// reading the words to analyze
int wordSize = 0;
while (str.hasMoreTokens()) {
String w = str.nextToken();
word[wordSize] = w;
System.out.println(wordSize + ": " + word[wordSize]);
wordSize++;
}
System.out.println("---Frequency---");
// create unique words
int uniqueWordSize = 0;
for (int i = 0; i < wordSize; i++) {
boolean found = false;
for (int j = 0; j < uniqueWordSize; j++) {
if (word[i].equals(unique[j])) {
found = true;
break;
}
}
if (!found) {
unique[uniqueWordSize++] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int i = 0; i < uniqueWordSize; i++) {
for (int j = 0; j < wordSize; j++) {
if (unique[i].equals(word[j])) {
measure[i]++;
}
}
}
//printing results
for (int i = 0; i < uniqueWordSize; i++) {
System.out.println(unique[i] + " : " + measure[i]);
}
}
}
It prints:
0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 3
Car : 2
Cat : 1
Dog : 1
Thanks to Luiggi for the inspiration . Here is my solution, realizing I had missed something very important. The nested loops. It is just a few lines of editing to my existing code. I would love you all to look at Luiggi's code as it is more verbose (hehe).
Result
0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 3
Car : 2
Cat : 1
Dog : 1
import java.util.Arrays;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String w;
int count = -1;
while (str.hasMoreTokens()) {
count++;
w = str.nextToken();
word[count] = w;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int z = 0; z < 7; z++) {
if (unique[z] != null) {
for (int j = 0; j < 7; j++) {
if (unique[z].equals(word[j])) {
measure[z] += 1;
}
}
System.out.println(unique[z] + " : " + measure[z]);
}
}
}
}
Another solution:
String text = "Bear Car Bear Cat Car Dog Bear";
String[] allWords = text.split(" ");
String[] foundWords = new String[allWords.length];
int[] foundCount = new int[allWords.length];
int foundIndex= 0;
for (String aWord : allWords) {
int j = 0;
for (; j < foundIndex; j++) {
if (foundWords[j].equals(aWord)) { //found
foundCount[j]++;
break;
}
}
if (j == foundIndex) { //word bot found in foundWords
foundWords[foundIndex] = aWord;
foundCount[foundIndex] = 1;
foundIndex++;
}
}
// Print result
for (int i = 0; i <foundIndex ; i++) {
System.out.println(foundWords[i] + " : " + foundCount[i]);
}
The result is:
Bear : 3
Car : 2
Cat : 1
Dog : 1
Related
In this program, I want the user to type in 20 product names. from the main method. which will pass down to the method named searchProducts. But for some reason, it doesn't work. It only let me type in once, and then it prints out all 16 products.
public static void main(String[] args) {
String[] products= {"Pencil pouch", "pen", "Pencil sharpener", "High lighters", "Markers", "Erasers",
"Binder", "Notebooks", "Index cards", "Folders", "Glue", "Ruler", "Scissors", "Calculator",
"Calendar", "Backpack"};
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products, 16);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
}
private static int searchProducts(String[] products) {
Scanner sc = new Scanner(System.in);
String x = sc.nextLine();
System.out.println("Enter name of product: ");
for (int i = 0; i < products.length; i++) {
if (products[i].equals(x))
return i;
}
return -1;
}
private static void sortProducts(String products[],int n) {
for(int i = 0; i < n - 1; i++) {
int minindex = i;
String minStr = products[i];
for(int j = i + 1; j < n; j++) {
if(products[j].compareTo(minStr) < 0)
{
minStr = products[j];
minindex = j;
}
}
if(minindex != i)
{
String temp = products[minindex];
products[minindex] = products[i];
products[i] = temp;
}
}
}
private static void displayProducts(String[] products) {
for(int i = 0; i < products.length; i++){
System.out.println(products[i] + " ");
}
}
The way you pass array parameter is just good.
There are several ways to pass arrays as parameter:
(/*Other params,*/ String[] param) // this way
(String[] param /*, Other params*/) // or
(/*Other params,*/ String param[]) // this way
(String param[] /*, Other params*/) // or
// special case
// only as unique or last param of the params
// because with it you can enter several String params as individuals
(/*Other params, */ String... param)
// arrays of arrays
(String[] param[])
(String[][] param)
(String param[][] )
This is your problem:
sortProducts(products, 20);
...
private static void sortProducts(String products[],int n) {
You pass 20 although your array is 16 sized. So error.
Change this way to not depend on the size.
sortProducts(products);
....
private static void sortProducts(String products[]) { // no size passed
int n = products.length; // read the size from the array
EDIT 1 -------------
In the code below, the user to type in N products. Then the array is printed, sorted and printed. (NOT TESTED)
public static void main(String[] args) {
int N = 20;
String[] products = new String[N];
Scanner sc = new Scanner(System.in);
for(int i=0; i < N; i++) {
System.out.println("Enter name of product "+ (i+1) +" : ");
String x = sc.nextLine();
products[i] = x;
}
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
// search block
}
To search in the array, you can do something like that (NOT TESTED):
public static void main(String[] args) {
// ... previous code
// search block in main method
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
String y = sc.nextLine();
while(y != "stop") {
int index = searchProducts(products, y);
if( index == -1 )
System.out.println("Product "+ y +" is not in array");
else
System.out.println("Product "+ y +" is at position "+ index);
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
y = sc.nextLine();
}
}
private static int searchProducts(String[] products, String p) {
for (int i = 0; i < products.length; i++) {
if (products[i].equals(p))
return i;
}
return -1;
}
I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22
Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.
Here is the code:
package Project022;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class NameScore {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public NameScore(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
names = new File("Project022\\names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
String filtered = content.get(0).replaceAll("\",\"", " ");
//then remove first and last (")
filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
if (filtered.charAt(i) != ' '){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println(sortedNames[937]);
System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
NameScore name = new NameScore();
name.calculate();
System.out.println(name);
}
}
What I've ruled out as a problem:
the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.
the calculate() method, since what it does is gets the score for each name and adds to the total sum.
This works for me.
Path p = Paths.get("p022_names.txt");
try {
List<String> lines = Files.readAllLines(p); // throws java.io.IOException
System.out.println(lines.size()); // Only one line in file.
// Remove all " (double quotes) characters.
String tmp = lines.get(0).replaceAll("\"", "");
String[] names = tmp.split(",");
System.out.println(names.length);
Arrays.sort(names);
// Test against example given in problem description.
System.out.println(names[937]); // Should be COLIN
char[] lett = names[937].toCharArray();
int sigma = 0;
for (int k = 0; k < lett.length; k++) {
sigma += lett[k] - 'A' + 1; // Since only uppercase letters in file.
}
int score = sigma * (937 + 1);
System.out.println(score); // Should be 49714
// Now obtain answer, i.e. the total of all the name scores in the file.
int total = 0;
for (int i = 0; i < names.length; i++) {
char[] letters = names[i].toCharArray();
int sum = 0;
for (int j = 0; j < letters.length; j++) {
sum += letters[j] - 'A' + 1;
}
total += sum * (i + 1);
}
System.out.println(total);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
Output obtained when running above code is as follows.
1
5163
COLIN
49714
871198282
I didn't want to make too many changes to your code, so just removed your replacement of "," and instead just removed all ". Then I added ALONSO in the end after the loop.
I figure if we're all in consensus about the total score of all the names, then we're doing it right :)
It prints:
-- Where's ALONSO ?
sortedNames[145] = ALONA
sortedNames[146] = ALONSO
sortedNames[147] = ALONZO
-- Where's COLIN ?
sortedNames[936] = COLETTE
sortedNames[937] = COLIN
sortedNames[938] = COLLEEN
-- Where's MARY ?
sortedNames[3361] = MARX
sortedNames[3362] = MARY
sortedNames[3363] = MARYA
-- sortedNames.length = 5163
the score of all names is: 871198282
I also called it Project022:
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
//public class NameScore {
public class Project022 {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public Project022(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
// names = new File("Project022\\names.txt");
names = new File("resource\\p022_names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
// String filtered = content.get(0).replaceAll("\",\"", " ");
String filtered = content.get(0).replaceAll("\"", "");
// //then remove first and last (")
// filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
// if (filtered.charAt(i) != ' '){
if (filtered.charAt(i) != ','){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
allNames.add(tempName.toString().trim()); // added to include ALONSO
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println("\n -- Where's ALONSO ?");
for (int i = 145; i < 148; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's COLIN ?");
for (int i = 936; i < 939; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's MARY ?");
for (int i = 3361; i < 3364; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- sortedNames.length = " + sortedNames.length + "\n");
// System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
Project022 name = new Project022();
name.calculate();
System.out.println(name);
}
}
Hello I can't make this work, I am given a main word followed by another sub words if the word is contained in the main word the part should be deleted.
//Example
//fmrog (in.nextLine)(main word)
//4 (in.nextInt)(the amount of sub words)
//roc(in.nextLine)(not contained)
//gor(in.nextLine)(not contained)
//rog(in.nextLine)(contained)
//ogr(in.nextLine)(not contained)
//result:fm
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder mainWord = new StringBuilder(in.nextLine);
int n = in.nextInt();
StringBuilder MainWord2 = new StringBuilder(mainWord);
in.nextLine();
for (int i = 0; i < n; i++) {
String subWord = in.nextLine();
int chars = subWord.length();
if (chars> mainWord.length()){
continue;
}
for (int j = 0; j < subWord.length(); j++) {
int r = 0;
for (int k = 0; k < mainWord.length(); k++) {
r++;
if (k > MainWord2.length() - 1) {
break;
}
if (MainWord2.charAt(k) == subWord.charAt(j)) {
break;
}
}
if (r <= MainWord2.length() && MainWord2.charAt(r-1) == subWord.charAt(j)) {
MainWord2.deleteCharAt(r - 1);
if (j >= subWord.length() -1 ) {
mainWord = MainWord2;
break;
}
}
if (r > MainWord2.length()) {
MainWord2 = mainWord;
break;
}
}
}
System.out.println(mainWord);
}
}
Honestly I am stucked maybe there is an easier way to solve this. The main thing is that when I write a case like : "super 2 pe surr" At the end at "surr" the two StringBuilders start to act as one when I delete chatAt at one of them the other one changes also
No need to make it so complex.
String input = // complete user input
String[] words = String.split(input);
String mainWord = words[0];
int numWords = Integer.parseInt(words[1]); // this variable isn't needed
for(int i = 2; i < words.length; i++) {
if (mainWord contains words[i]) {
mainWord = mainWord.replace(words[i], ""); // remove subword from mainword
}
}
At the end, mainWord will be the original mainWord without any subwords that were entered later.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String[] words = new String[n];
for (int i = 0; i <n ; i++) {
words[i] = in.nextLine();
}
String mainWord = words[0];
for (int i = 1; i <words.length ; i++) {
if (mainWord.contains(words[i])){
mainWord = mainWord.replace(words[i], "");
}
}
System.out.println(mainWord);
}
}
Here but the thing is if the letters are not one next to another it doesnt remove the subword.
Given a equation :
433+4H8= 871
H can be anyside of equation. Find the value of H and replace it in given equation.
The output should be :
433+438=871
I have tried the following code but conversion of string to int does not work...
import java.util.Scanner;
import java.io.*;
class hole
{
public static void main(String[] args)
{
Scanner reader= new Scanner(System.in);
int[] nums= new int[3];
String str= reader.nextLine();
String str_1= str.replaceAll("=","+");
String[] split= str_1.split("[+]");
for (int k=0; k<split.length; k++)
{
String ex= split[k];
nums[k]= Integer.parseInt(ex);
}
}
}
4H8 isn't an integer, so parseInt won't work on it.
It seems like you still have a bit of a way to go on this, so I won't spoil your fun by giving you the code, just some ideas.
Assuming the equation is always X + Y = Z, which X, Y and Z being some integers, one of which can contain an H...
You need to have a couple of cases:
If the H is in X, you can get X by subtracting Y from Z.
If the H is in Y, you can get Y by subtracting X from Z.
If the H is in Z, you can get Z by adding X and Y.
But this still doesn't give you H. For this, you can simply find the position of the H in the string we have and extract the digit at that position in the number calculated above.
So before calling parseInt, you should look for the H and simply store the string instead if you find it.
parseInt also doesn't like spaces, so you should remove those in some way or another.
If equations aren't always in the form X + Y = Z (i.e. you can also have subtraction, multiplication, division and/or multiple terms), it gets a bit more complicated.
Why would you not just subtract the final answer minus the first number and build the third number. Splitting the string is redundant as you can just use simple math to solve for x.
871-433 = 438
h=3
public static void main(String[] args)
{
int a = 433;
int b = 871;
int c = b - a;
String s = "4H8";
char x;
int location = 0;
for(int i = 0; i < s.length(); i++)
{
char d = s.charAt(i);
if(d.isDigit()){
}
else{
location = i;
x = d;
}
}
String solve = c.toString();
System.out.println(x + "=" + solve.charAt(location) );
}
Try this (comments are self explanatory):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
int varIndex = 0;
int result = 0;
String str = reader.nextLine();
//remove spaces and split into 3 parts based on symbols
String[] components = str.replaceAll(" ", "").split("\\+|=");
for (int i = 0; i < components.length; i++) {
try {
nums[i] = Integer.parseInt(components[i]);
} catch (Exception e) {
varIndex = i; //this component contains "H"
}
}
//Calculate the value of the number which has "H"
switch (varIndex) {
case 0:
result = nums[2] - nums[1]; break;
case 1:
result = nums[2] - nums[0]; break;
case 2:
result = nums[0] + nums[1]; break;
}
nums[varIndex] = result;
//Print the output
System.out.println(nums[0] + " + " + nums[1] + " = " + nums[2]);
System.out.println("H = " + (String.valueOf(result)).charAt(components[varIndex].indexOf('H')));
}
Try below program , This works only for input a+b=c format
Below program is giving correct output
import java.util.Scanner;
public class Hole {
public static void main(String args[])
{
int hLocation = 0;
int result;
char hValue;
Scanner in=new Scanner(System.in);
String str=in.nextLine().replaceAll(" ", "");
String[] split= str.split("[+=]");
for(int i=0;i<split.length;i++){
if(split[i].contains("H")){
hLocation=i;
}
}
if(hLocation==0){
result=Integer.parseInt(split[2])-Integer.parseInt(split[1]);
}else if(hLocation==1){
result=Integer.parseInt(split[2])-Integer.parseInt(split[0]);
}
else{
result=Integer.parseInt(split[0])+Integer.parseInt(split[1]);
}
hValue= String.valueOf(result).charAt(1);
str=str.replace('H', hValue);
System.out.println(str);
}
}
Try this:
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
boolean[] isNum = new boolean[3];
String str = reader.nextLine();
// String str_1= str.replaceAll("=","+");
String[] split = str.split("[+=]");
int i = 0;
for (int k = 0; k < split.length; k++) {
try {
String s = split[k];
isNum[k] = true;
nums[i] = Integer.parseInt(s);i++;
} catch (NumberFormatException e) {
// TODO: handle exception
isNum[k] = false;
}
}
int tot ;
if(str.indexOf("H")>str.indexOf("=")){
tot = nums[1] + nums[0];
}else{
tot = nums[1] - nums[0];
}
for (int k = 0; k < split.length; k++) {
if(!isNum[k]){
int indx = split[k].indexOf("H");
String h = Integer.toString(tot).charAt(indx)+"";
h = str.replace("H",h);
System.out.println("New expression :"+h);
}
}
}
StackOverflow. I am attempting to make a program that uses a text menu to to a multitude of things to manipulate a single string. One of the methods turns the string into an array of strings. This works fine. However, all of the methods that manipulate it as an array(one prints it out, one reverses the word order, and one sorts them using an exchange sorting method) return a NullPointerException when called. I have looked all through the code and do not see where it is coming from. Here is the .Java file containing all of the code. My problem is only happening when I call the printArray(), reverse(), and sort() methods, near the bottom. Any and all help is appreciated. Sorry for the sloppy code, I have not cleaned it up yet.
Code:
/*
Computer Programming Lab 11
Jim Kimble
3 Mar 2013
Work with strings and implementing a menu.
Acknowledgements:
Uses main structure of HUTPanel as designed at UMU, 2002-2012
*/
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class HUTPanel extends JPanel
{
/***************************************************
* Class-level data members should be declared here.
***************************************************/
int numVowels;
String[] words;
String str;
String vowels;
String menuChoice;
String oString = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n"
+"When in the course of human events\n"
+"Mary had a little lamb.\n"
+"The girls' basketball team repeated as tournament champion this weekend.";
public HUTPanel(JFrame frame)
{
// Set panel background color
setBackground(Color.WHITE);
setLayout(null);
setPreferredSize(new Dimension(810, 410));
/***************************
* Now add your code below:
***************************/
// Create a frame around this panel.
frame.setTitle("Computer Programming Lab/Program # 11");
frame.getContentPane().add(this);
str = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n"
+"When in the course of human events\n"
+"Mary had a little lamb.\n"
+"The girls' basketball team repeated as tournament champion this weekend.";
System.out.println("Lab 11: Text Manipulation");
//getTheText();
System.out.println("The string is: '"+str+"'.");
handleTheMenu();
} // end of constructor
/*************************
* Add your methods here:
*************************/
// Get a text sequence from the keyboard and put it in str
public void getTheText()
{
Boolean inputDone = false;
while (!inputDone)
{
System.out.print("Enter your text: ");
inputDone = grabText();
}
}
private Boolean grabText()
{
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
menuChoice = inputReader.readLine();
return true;
}
catch(IOException e)
{
System.out.println("Error reading input. Please try again.");
}
return false;
}
public void handleTheMenu()
{
int choice = -1;
Boolean OK;
while (choice != 0)
{
choice = -1;
System.out.println("Menu:");
System.out.println();
System.out.println(" 1. Count the vowels"); //"There are ... vowels in the text."
System.out.println(" 2. Remove all letter e's"); //then print it.
System.out.println(" 3. Replace all t's with '+'"); //then print it
System.out.println(" 4. Search for a requested word (will reset the string)"); //Does 'word' exist in the text?
System.out.println(" 5. Print the words on individual lines");
System.out.println(" 6. Reset the string.");//Reset the string to the original
System.out.println(" 7. Put the words in an array"); //then print it
System.out.println(" 8. Reverse the text word order"); //then print it
System.out.println(" 9. Sort the words in an array"); //Once the words are put into an array
System.out.println();
System.out.print(" 0 to quit --> ");
OK = grabText();
if (OK)
{
try
{
choice = Integer.parseInt(menuChoice);
}
catch(NumberFormatException e)
{
System.out.println("Not a number; please try again.");
System.out.println();
}
switch(choice)
{
case 0: System.out.println();
System.out.println("Thank you.");
break;
case 1: countVowels();
break;
case 2: removeAllEs();
break;
case 3: changeTToPlus();
break;
case 4: find();
break;
case 5: listWords();
break;
case 6: reset();
break;
case 7: makeArray();
break;
case 8: reverse();
break;
case 9: sort();
break;
default: System.out.println("Not a valid choice; please try again.");
}
}
}
}
private void countVowels() {
//count the vowels in str
vowels = "aeiouAEIOU";
numVowels = 0;
for( int i = 0; i < vowels.length(); i ++) {
for(int j = 0; j < str.length(); j++) {
if (str.charAt(j) == vowels.charAt(i)) {
numVowels += 1;
}
}
}
System.out.println("The string has " + numVowels + " vowels in it.");
}
private void removeAllEs() {
String str3 = str.replace('e', ' ');
System.out.print(str3);
str = str3;
}
private void changeTToPlus() {
String str2 = str.replace('t', '+');
System.out.println(str2);
str = str2;
}
private void find() {
str = oString;
getTheText();
if(str.indexOf(menuChoice) != -1)
{
System.out.println("The word " +menuChoice+ " is at index " +str.indexOf(menuChoice));
}
else
{
System.out.println("The word " +menuChoice+ " is not in the string.");
}
}
private void listWords() {
int pos = 0;
int i = 0;
while(i > -1)
{
i = str.indexOf(' ', pos);
if (i > -1)
{
System.out.println(str.substring(pos, i));
pos = i + 1;
}
}
}
private void reset() {
str = oString;
System.out.println();
System.out.println("String reset.");
System.out.println();
}
private void makeArray() {
int n = 1;
String[] words = new String[n];
int pos = 0;
int i = 0;
int j = 0;
while(j > -1)
{
for (i = 0; i < 1000; i++)
{
n += 1;
j = str.indexOf(' ', pos);
if (j > -1)
{
words[i] = str.substring(pos, j);
pos = j + 1;
}
}
}
//printArray();
}
//***FIX***
private void printArray() {
for (int k = 0; k < words.length -1; k++){
System.out.println(words[k]);
}
}
//***FIX***
private void reverse() {
int i = 0;
int j = words.length - 1;
String temp;
while (i < j){
temp = words[i];
words[i] = words[j];
words[j] = temp;
i++;
j--;
}
}
private void sort() {
String temp = "";
for (int i = 1; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
int x = words[i].compareTo(words[j]);
if (x > 0) {
temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
for (int p = 0; p < words.length -1; p++) {
System.out.println(words[p]);
}
}
}
You Error is here:
private void makeArray() {
int n = 1;
String[] words = new String[n];//At This line you are creating local array words.The instance variable words is still null.
int pos = 0;
int i = 0;
int j = 0;
while(j > -1)
{
for (i = 0; i < 1000; i++)
{
n += 1;
j = str.indexOf(' ', pos);
if (j > -1)
{
words[i] = str.substring(pos, j);
pos = j + 1;
}
}
}
use:
words = new String[n]; instead of String[] words = new String[n];
As mentioned by Luiggi Mendoza in the comment section, the local variable words defined within makeArray method is shadowing the instance variable words defined within HUTPanel class.
As side note I want to point out the unnecessary creation of new BufferedReader objects in method grabText() each time you are calling it in getTheText(). It would be much efficient if your make inputReader an instance variable in your class , and instantiate it once within the constructor using inputReader = new BufferedReader(new InputStreamReader(System.in));. This way your grabText method becomes like this :
private Boolean grabText()
{
try {
//No more new object creation for BufferedReader for each call of this method.
menuChoice = inputReader.readLine();
return true;
}
catch(IOException e)
{
System.out.println("Error reading input. Please try again.");
}
return false;
}
Make sure you always you always start with option 7, so your words array gets initialized. This is in fact not something that the user should do. The application should handle it so that the user either can't select other options, or does it automatically.
Update: Vishal K is correct, but this is still a weak point in your application.