Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was directed from to this website from a friend. The goal is to read the first 100 strings in the txt file and count how many times those words appear and print them off.
Thank you so much in advance. I've done very well with code but this has stumped me for some reason.
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) throws FileNotFoundException {
WordAnalysis a = new WordAnalysis();
a.ReadFile();
}}
class WordAnalysis{
String[] coun = new String[1000];
int[] ana = new int[100];
void ReadFile() throws FileNotFoundException {
Scanner read = new Scanner(new File("myths.txt"));
int[] ana = new int[100];
String coun = new String();
String word=null;
while(read.hasNext()) {
word = read.next();
String[] arrWord = word.split(" ");
}
}
}
Procedure:
1: Read lines [0,99] via nextLine() from Scanner
2: Split up line with another Scanner and use next() to get each word. Alternatively, you can use split.
3: Put each word in a HashMap(String, Integer) where String is the word, and Integer is the number of times it has appeared
4: Iterate through HashMap and prints out key, value pairs
Check this, here I've used a map to keep word count.
int count = 0;
HashMap<String, Integer> wordCntMap = new HashMap();
while (read.hasNext()) {
count++;
word = read.next();
String[] arrWord = word.split(" ");
if (count == 100) {
break;
}
for (String str : arrWord) {
Integer num = wordCntMap.get(str);
if (num == null) {
wordCntMap.put(str, new Integer(1));
} else {
wordCntMap.put(str, num + 1);
}
}
}
System.out.println("Word Count " + wordCntMap);
Welcome to Stack Overflow, where no answer is too stupid and no comment too thoughtless.
It seems fairly clear however that you haven't finished writing this code. :-)
Now that you have your words in arrWord, you need to start using some sort of structure that will allow you to keep track of each word and how many times its been seen.
There are plenty of containers that let you use a string as a key and an integer as a value. For your purposes it doesn't matter which one you use.
For each word in arrWord, see if you can find it in your structure (Dictionary, Hashmap, whatever). If you can't find 'word', insert a new entry of [word, 1]. If you can find 'word' then increment the counter that you find.
When you are done, all you need to do is print out the key-value pair for each entry in your structure.
HTH!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
How would you go about adding the total number to all the integers inside an array element?
My code below is what I have and the issue is the multiple numbers are all displayed in different rows but I can't get them to add together because its all considered one integer.
This is what my output looks like.
462085
361250
351477
328955
But when I attempt to alter the numbers in any way I get something like this,
+2
462087
361252
351479
328957
When I really want to get just get the total sum of the numbers.
Desrired Output:
1503767
I attempted to use .parseInt() but that did not seem to make a difference.
import java.io.*;
import java.nio.charset.StandardCharsets;
public class babySort {
public static void main(String[] args) {
File inputFile = new File("src/babynames.txt");
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
String input;
String maleNames;
while ((input = br.readLine()) != null) {
// process the line
String[] inputSplit = input.split("\\s+");
// System.out.println(inputSplit[2]);
int maleBb = Integer.parseInt(inputSplit[2]);
System.out.println(maleBb);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You want the total. Declare a variable to compute the total with before your loop. Add the values to the total. Print it after your loop. Like,
int total = 0;
while ((input = br.readLine()) != null) {
String[] inputSplit = input.split("\\s+");
// int maleBb = Integer.parseInt(inputSplit[2]); // what is a maleBb?
total += Integer.parseInt(inputSplit[2]);
}
System.out.println(total);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am working on a Java program to iterate through two arrays and compare the first one to the second for any matches. It should return all the numbers/strings that DON'T MATCH as an array list. I am done, but I am not sure why I am getting an ArrayIndexOutOfBoundsException error. This is my code:
package test;
import java.awt.List;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayComparer {
public static ArrayList<String> ArrayComparer(String[] arrayOne, String[] arrayTwo){
// if one is bigger than start by comparing the smaller one to the bigger one
// as if it were the other way the bigger one would run out over numbers to compare
// declaring the array for holding all the non-matching telephone numbers to be returned
ArrayList<String> nonMatchingTelephoneNumbers = new ArrayList<String>();
for(int i = 0; i<arrayOne.length; i++){
int strikes = 0;
// for each value of the first one it should go through all the values of the second and compare each
for(int i2 = 0; i<arrayTwo.length; i2++){
if(arrayOne[i] != arrayTwo[i2]){
strikes++;
if(strikes == arrayTwo.length){
// meaning it has gone through ALL of arrayTwo and couldn't find a match
nonMatchingTelephoneNumbers.add(arrayOne[i]);
}
}
}
}
return nonMatchingTelephoneNumbers;
}
public static void main(String[] args) throws IOException {
// declaring the first list of telephone number
String[] ArrayListOne;
// declaring the second list of telephone numbers
String[] ArrayListTwo;
// splitting up the user input of telephone numbers by commas
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your first array of telephone numbers, split by commas");
ArrayListOne = myObj.nextLine().split(","); // Read user input
// once it has iterated through all of the telephone numbers in the first list, ask for the second list
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your second array of telephone numbers, split by commas");
ArrayListTwo = myObj2.nextLine().split(","); // Read the second user input
// once it has collected and sorted all the user input, the ArrayCOmparer method should be called
// to compare them and return the telephone numbers that DON'T MATCH
ArrayComparer(ArrayListOne, ArrayListTwo);
}
}
The error is on line 22, where it says if(arrayOne[i] != arrayTwo[i2]){.It also doesn't say there is an error on line 22 until I run it. Can someone please tell me why I am getting this:console error?
Hi i think this is causing the error
for(int i2 = 0; i<arrayTwo.length; i2++){
You should replace it with:
for(int i2 = 0; i2<arrayTwo.length; i2++){
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.
**Edit after reviewing Tormod's answer and implementing his advice.
As the title states I'm attempting to print the total number of different words after receiving a file name from command line input. I receive the following message after attempting to compile the program:
Note: Project.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Here is my code. Any help is greatly appreciated:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Project {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
Scanner s = new Scanner(file);
HashSet lib = new HashSet<>();
try (Scanner sc = new Scanner(new FileInputStream(file))) {
int count = 0;
while(sc.hasNext()) {
sc.next();
count++;
}
System.out.println("The total number of word in the file is: " + count);
}
while (s.hasNext()) {
String data = s.nextLine();
String[] pieces = data.split("\\s+");
for (int count = 0; count < pieces.length; count++)
{
if(!lib.contains(pieces[count])) {
lib.add(pieces[count]);
}
}
}
System.out.print(lib.size());
}
}
I would implement it using a HashSet Add all the words, and read out the size. If you want to make it case insensitive just manipulate all the words to uppercase or something like that. this uses some memory but...
one problem you got with the algorithm is that you do only have one "words". it only holds the words at the same line. so you only count same words at the same line.
HashSet stores strings by their hash value, and thus stores one word only one time.
construction: HashSet lib = new HashSet<>();
inside the loop: if(!lib.contains(word)){lib.add(word);}
check the word count: lib.size()
for(String s : words) {
if(s.equals(word))
count++;
}
You are comparing the words to an empty String, since it's a word it's always gonna be false.
Like Tormod said, the best would be to store the words in a HashSet, as it won't keep duplicates. Then just read out its size.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
for example....
26, 15, 37
how could i get the numbers from a Scanner , ( lets say for instance i want to add or subtract,,,?)
Take a look at String.split().
If you want to use the Scanner API:
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
for (;;) {
integers.add(scanner.nextInt());
if (scanner.hasNext(COMMA_PATTERN)) {
// Read and discard comma token, and continue parsing list.
scanner.next();
} else {
// Number is not followed by comma, stop parsing.
break;
}
}
return integers;
}
More error handling is needed, but hopefully, this example illustrates the approach.
You can also use Scanner.useDelimiter():
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter(COMMA_PATTERN);
while (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
// Reset delimiter
scanner.useDelimiter(oldDelimiter);
return integers;
}
Use Scanner.useDelimiter. It actually takes regex, so you'd want to learn some basics.
String text = "1 , 2 3, 4,5";
Scanner sc = new Scanner(text).useDelimiter("\\s*,?\\s*");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} // prints "1", "2", "3", "4","5"
See also
http://www.regular-expressions.info/ -- the best tutorial resource
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Using hasNextInt() to prevent exception is much better than Integer.parseInt and catch NumberFormatException
String.split() is OK, but StringTokenizer works everywhere and in every version of Java.
StringTokenizer st = new StringTokenizer("26, 15, 37", ", ");
int sum = 0;
while (st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}
Try to set a delimiter for your scanner object:
Scanner s = new Scanner(System.in).useDelimiter(", *");
int first = s.nextInt();
int second = s.nextInt();
...
More examples can be found in Scanner documentation.
Look at useDelimiter. You need a regex that will match either whitespace or commas.