I am trying to write code to count the frequency of each word in an array. I am wondering if I need to use two nested loops to keep track of both the array with integers and the array with the words. I have been fiddling with the code for hours and cannot make any progress. If you have any pointers, they would be much appreciated. I am given the input as first the number of elements in the array, then the words that I am supposed to count the frequency of, such as 4 dog cat dog fish.
import java.util.Scanner;
public class LabProgram {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int i;
int count;
int[] countArr = new int[listSize];
// need to use two arrays; one for frequency, one for words.
for (i = 0; i < countArr.length; ++i) {
if (wordsList[i].compareTo(currWord) == 0) {
countArr[i] += 1;
}
}
//check previous LAB that had same concept; then make it use a method.
return countArr[i];
}
public static void main(String[] args) {
int size;
int i;
size = scnr.nextInt();
String[] array = scnr.nextLine().split(" ");
for (i = 0; i < array.length; ++i) {
System.out.println(array[i]);
}
for (i = 0; i < array.length; ++i) {
currWord = array[i];
System.out.println(currWord + getFrequencyOfWord(array, size, currWord));
}
}
}
Can you please try below solution?:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
try (Scanner scnr = new Scanner(System.in)) {
int size = scnr.nextInt();
Map<String, Integer> wordCounts = new HashMap<>();
for (int i = 0; i < size; i++) {
String s = scnr.next();
if (wordCounts.containsKey(s)) {
int count = wordCounts.get(s);
wordCounts.put(s, ++count);
} else {
wordCounts.put(s, 1);
}
}
wordCounts.entrySet().stream().forEach(s -> System.out.println(
s.getKey() + ": " + s.getValue()));
}
}
}
Using Java 8 Streams:
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LabProgram {
public static void main(String[] args) {
try (Scanner scnr = new Scanner(System.in)) {
int size = scnr.nextInt();
String array[] = new String[size];
for (int i = 0; i < size; i++) {
array[i] = scnr.next();
}
Map<Object, Integer> data = Stream.of(array)
.collect(Collectors.groupingBy(
s -> s, Collectors.summingInt(s -> 1)));
data.entrySet().stream().forEach(s -> System.out.println(
s.getKey() + ": " + s.getValue()));
}
}
}
If your input is:
4 dog cat dog fish
Output:
cat: 1
fish: 1
dog: 2
Related
This code below throws NoSuchElementException in the function aVeryBigSum.
PS: This is task from hackerrank so I can only modify the code in function: aVeryBigSum.
This function takes the following inputs: n which is the number of elements in an array to be added, and the elements of array.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the aVeryBigSum function below.
static long aVeryBigSum(long[] ar) {
int n, sum = 0;
Scanner read = new Scanner(System.in);
n = read.nextInt();
for(int i = 0; i < n; i++)
sum += read.nextLong();
return sum;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter
= new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
long[] ar = new long[arCount];
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < arCount; i++) {
long arItem = Long.parseLong(arItems[i]);
ar[i] = arItem;
}
long result = aVeryBigSum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Output:
Why are you reading from Scanner in your aVeryBigSum method?
Just loop through ar argument and calculate sum.
static long aVeryBigSum(long[] ar) {
long _sum = 0;
for(int i=0; i < ar.length; i++)
sum += ar[i];
return _sum;
}
static long aVeryBigSum(long[] ar) {
int n;
Long sum = 0;
Scanner read = new Scanner(System.in);
n = read.nextInt();
for(int i = 0; i < n; i++)
sum += read.nextLong();
return sum;
}
its working fine for me if you change: int n;
long sum=0; in existing code and try.
output:2
1 2
5
1000000001
1000000002
1000000003
1000000004
1000000005
5000000015
I have to sort strings in an array for a school project. Our teacher won't allow us to use array,sort().
i have to use 2 sort methods but they aren't working too well.
The first one returns double of each value. ie John, jack, adam, tom will return adam,adam,jack,jack,john,john,tom,tom.
public static void sort() {
inputFileNames();//inputs list of names from a file.
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (stArr[i].compareTo(stArr[j])>0) {
temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
}
}
}
display("The names are: ");// method to display array
System.out.println("");
}
the second sort doesn' run:
public static void bubbleSort() {
inputFileNames();
for (int i = size - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (stArr[j].compareTo(stArr[j+1])>0) {
temp = stArr[j];
stArr[j] = stArr[j + 1];
stArr[j + 1] = temp;
}
}
}
display("The names are: ");
System.out.println("");
}
input and display:
static void display(String heading) {
System.out.println(heading + "\n");
for (int i = 0; i < size; i++) {
System.out.println(stArr[i]);
}
}
static void inputFileNames() {
try {
Scanner scFile = new Scanner(new File("Names.txt"));
while (scFile.hasNext()) {
stArr[size] = scFile.nextLine();
size++;
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
}
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{ Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
String[] stArr = new String[n];
for(i=0;i<n;i++)
{
stArr[i]=sc.next();
// System.out.println(stArr[i]);
}
//inputs list of names from a file.
for (i = 0; i < n ; i++) {
for (j = i+1 ; j < n; j++) {
if (stArr[i].compareTo(stArr[j])>0)
{
String temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
// System.out.println(stArr[i]);
// System.out.println(stArr[j]);
}
}
}
for(i=0;i<n;i++)
{
System.out.println(stArr[i]);
}
// your code goes here
}
}
This Is the answer for first code. I am not good in file handling so you have to use your input method. I know Scanner thats why i have used here.
In Your Second Example Your j loop is wrong it should be for ( j = 0; j <= i-1; j++). And Please Mark It as answer if your problem is solved
so my program prints an array but when it does it also includes brackets and commas and i dont want those.
here is my library
import java.util.*;
public class library2
{
public static boolean IsPrime(int p)
{
for (int i = 2; i < p; i++)
{
if (p % i == 0 && i != p)
return false;
}
return true;
}
public static List<List<Integer>> GetPrimes(int n)
{
List<Integer> arr = new ArrayList<Integer>();
for (int j = 2; j < n; j++)
{
if(IsPrime(j))
{
arr.add(j);
}
}
return Arrays.asList(arr);
}
}
here is my driver
import java.util.Scanner;
import java.util.*;
import java.util.Arrays;
public class driver2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please input an integer: ");
int n = scan.nextInt();
Boolean check = library2.IsPrime(n);
List<List<Integer>> arr = library2.GetPrimes(n);
System.out.println(Arrays.toString(arr));
}
}
ive tried the Arrays.toString(); method but i get an error when i compile. i used import java.util.Arrays; but that didnt solve anything. can someone help me out.
arr is a list and not an array.
You should iterate over and print:
Iterator<List<Integer>> arrIterator = arr.iterator();
while (arrIterator.hasNext()) {
List<Integer> l = arrIterator.next();
Iterator<Integer> lIterator = l.iterator();
while(lIterator.hasNext()){
int i = lIterator.next();
System.out.print(i + " ");
}
System.out.print("\n");
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
Write a method that returns a new array by eliminating the duplicate values in the array using this header:
public static int[] eliminateDuplicates (int[] list)
all I have so far is my main, but what I wanted to do for the other method was use a for loop to check values at each space in my array and print them if they did not equal any of the other entries. Working on it as we speak!
My output is this: The distinct numbers are: [I#4554617c
first of all this is 11 characters and at max I should be printing 10.
import java.util.Scanner;
public class EliminateDuplicates
{
public static void main(String [] Args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter ten whole numbers: ");
int[] tenNumbers = new int[10];
for (int i=0; i<10; i++)
{
tenNumbers[i] = input.nextInt();
}
System.out.println("The distinct numbers are: " + eliminateDuplicates(tenNumbers));
}
public static int[] eliminateDuplicates (int[] list)
{
int count = 0;
for (int i = 0; i > list.length; i++)
{
for (int j = i + 1; j < list.length; j++)
{
if(list[i] == list[j])
{
list[j] = -1;
}
}
}
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
count++;
}
}
int[] array2 = new int[count];
int newCount = 0;
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
array2[newCount] = list[i];
}
}
return array2;
}
}
import java.util.ArrayList;
public class EliminateDuplicates {
//This is called Generics, It'll be a little later in your studies
public static <E> ArrayList<E> eliminateDuplicates(ArrayList<E> list) {
ArrayList<E> newList = new ArrayList<>(list.size());
for (E aList : list) { // for (int i = 0; i <= list.lenght; i++){
if (!newList.contains(aList)) {
newList.add(aList);
}
}
return newList;
}
public static void main(String[] args) {
ArrayList<Integer> tenNumbers = new ArrayList<Integer>();
tenNumbers.add(14);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
ArrayList<Integer> newList = eliminateDuplicates(tenNumbers);
System.out.print("The distinct numbers are: " + newList);
}
}
import java.util.*;
public class Question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = {1,2,3,3,4,5,6,1};
int[] ne = new int[arr.length];
ArrayList<Integer> already= new ArrayList();
int i = 0;
while(i<arr.length){
if(!already.contains(arr[i]))
already.add(arr[i]);
i++;
}
System.out.println(already.toString());
}
}
I am having trouble comparing my dictionary file to the anagrams. I put a print statement at each and it is reading in the dictionary file correctly and it is also calculating all of the anagrams correctly But it won't calculate only the anagrams from the dictionary file. I'm pretty sure it's something very minor and if someone can fix it it would greatly be appreciated.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Anagram3
{
static int size;
static int count;
static char[] charArray;
static char[] words;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("Type the path of the dictionary to read from : ");
String fileName = sc.nextLine();
List<String> dictionary = new ArrayList<String>();
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(fileName));
String word;
while((word = br.readLine())!=null)
{
dictionary.add(word);
}
}
catch(IOException e)
{
e.printStackTrace();
}
String[] words = new String[dictionary.size()];
dictionary.toArray(words);
//for( int i = 0; i < words.length; i++ )
// System.out.println(words[i]);
System.out.println("\nEnter the phrase to scramble: ");
String input = sc.nextLine();
System.out.println();
size = input.length();
count = 0;
charArray = new char[size];
for (int j = 0; j < size; j++)
charArray[j] = input.charAt(j);
doAnagram(size);
}
public static void doAnagram(int newSize)
{
int limit;
if (newSize == 1) // if too small, return;
return;
// for each position,
for (int i = 0; i < newSize; i++) {
doAnagram(newSize - 1); // anagram remaining
if (newSize == 2) // if innermost,
printAnagrams();
rotate(newSize); // rotate word
}
}
public static void rotate(int newSize)
{
int i;
int position = size - newSize;
char temp = charArray[position];
for (i = position + 1; i < size; i++)
charArray[i - 1] = charArray[i];
charArray[i - 1] = temp;
}
public static void printAnagrams()
{
for (int i = 0; i < size; i++)
{
//System.out.print(charArray[i]);
if(charArray[i] == words[i])
{
System.out.print(charArray[i]);
}
}
System.out.println();
}
}
Your static variable words is not being used because you define a new String[] words before the assignment.
Use the equals method to compare Strings. 1
Another issue is that you're comparing the i'th anagram generated to the i'th element in your dictionary, when you actually (presumably) want to test if the i'th anagram is present in the dictionary at any position.
You can try using a HashSet h of strings, rather than the array, for the dictionary, and then check for validity of an anagram with h.contains(...).