Java - Adjacent comparing and calculating frequency of words [duplicate] - java

This question already has answers here:
Calculating frequency of each word in a sentence in java
(20 answers)
Closed 9 years ago.
I have a already sorted string array named arr and Supposing I enter the sentence
hello how hello to how me in
Desired Output is
hello 2
how 2
me 1
in 1
to 1
Here's how I am trying to count it
int counter = 1;
for(j1 = 0; j1 < arr.length; j1++){
if(j1 + 1 < arr.length){
if(arr[j1].equals(arr[j1 + 1])){
counter++;
} else {
System.out.println(arr[j1] + " " + counter);
counter = 1;
}
}
}
but this is not working , please help?

The problem is the line:
if(j1 + 1 < arr.length) {...}
You are not iterating over the whole array; the last element is left uncounted.
Without explaining to much, this could be a quick fix:
public static void main(String[] args) {
String[] arr = { "hello", "how", "hello", "to", "how", "me", "in" };
Arrays.sort(arr);
int counter = 1;
for (int j1 = 0; j1 < arr.length; j1++) {
int j2 = j1 + 1;
String next = (j2 < arr.length) ? arr[j2] : null;
if (arr[j1].equals(next)) {
counter++;
} else {
System.out.println(arr[j1] + " " + counter);
counter = 1;
}
}
}

Related

How to locate an inputted integer value in a list of an Array in Java?

this is my first "problem": Make a program to allow the user to input an integer value to be searched in list3. Your program should display whether the inputted integer value is found in list3, how many of it is in list3, and what are their locations in list3?"
It's almost done, the only problem is that I couldn't follow what is written output given in the example:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List3.
Located at: list3[4], list3[5], list3[6], list3[8]
and this is my output:
list1 : 1 3 2 5 7 8 5 6 9 4
list2 : 2 1 4 3 2 1 4 2 0 2
list3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List 3.
Located at: 4
how do i display the "located at: " like in the example?
EDITED
Sorry, I'm kinda new here and in Programming. This is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class List2Sample
{
public static void main(String[] args)
{
int list1[] = new int[10];
int list2[] = new int[10];
int list3[] = new int[10];
String input = "";
int i, x, num = 0, count = 0;
boolean found = false;
ArrayList<Integer> arr = new ArrayList<Integer>(10);
Scanner in = new Scanner(System.in);
for(i = 0; i < 10; i++)
{
list1[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 1 [" + i + "] : ");
try
{
list1[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
for(i = 0; i < 10; i++)
{
list2[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 2 [" + i + "] : ");
try
{
list2[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
System.out.print("list1 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list1[i] + "\t");
}
System.out.println();
System.out.print("list2 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list2[i] + "\t");
}
System.out.println();
System.out.print("list3 : ");
for(i = 0; i < 10; i++)
{
list3[0] = list1[0] + list2[0]; list3[1] = list1[1] + list2[1]; list3[2] = list1[2] + list2[2];
list3[3] = list1[3] + list2[3]; list3[4] = list1[4] + list2[4]; list3[5] = list1[5] + list2[5];
list3[6] = list1[6] + list2[6]; list3[7] = list1[7] + list2[7]; list3[8] = list1[8] + list2[8];
list3[9] = list1[9] + list2[9];
System.out.print(list3[i] + "\t");
}
System.out.println();
System.out.print("Input value to search in List3: ");
x = in.nextInt();
arr.add(list3[0]);
arr.add(list3[1]);
arr.add(list3[2]);
arr.add(list3[3]);
arr.add(list3[4]);
arr.add(list3[5]);
arr.add(list3[6]);
arr.add(list3[7]);
arr.add(list3[8]);
arr.add(list3[9]);
for (int n : list3)
{
if (n == x)
{
found = true;
break;
}
}
for (i = 0; i < 10; i++)
{
if (list3[i] == x)
{
count++;
}
}
for (Integer value : arr)
{}
int pos = arr.indexOf(x);
if(found)
System.out.println("The value " + x + " is in List3!");
else
System.out.println("The value " + x + " is in List3!");
System.out.println("There are " + count + " of it in List 3.");
System.out.println("Located at: " + pos);
}
}
Assuming list3 is an list of integers then using java8 streams
String locations=IntStream.range(0,list3.size())
.filter(i->list3.get(i)==userInput)
.map(index->"list3["+index+"]")
.collect(Collectors.joining(","));
Int occurences=locations.split(","). length;
if(occurences>0){System.out.println(userInput +"occurred" + occurences +" Times +" at locations "+locations);}
else{System.out.println(userInput +"Was not found");}
indexOf(ch) will only return the first appearance of the value in the array, if you want, you could supplement a second parameter to tell Java where to start looking for the character, like this: indexOf(ch, fromIndex).
However, in your case, it's much easier to just use an index based loop to loop through all elements in the array, then record the positions if you found matching characters, like this:
for(int i = 0; i < arr.length; i++){ // loop through all indices of the array, starting from 0, end at arr.length - 1
if(arr[i] == ch){ // arr[i] is each character in the array at index i, ch is the target character you're matching against
System.out.println("Character found at position " + i);
}
}

How to print a array with different conditions

I'm trying to print values by mapping one to another array. Below is my sample code.
int k;
int m=0;
int NUMBER_OF_TIME = 2; // this value will be constant won't change
int[] timeReadings = {1,2,3,4,5,6,7,8,9,10,11,12};
String array1[] = {"A, B"};
System.out.println("-----------------"+"\n");
for (k=0; k < array1.length; k++) {
inner: for (; m < timeReadings.length; m++) {
if(m==NUMBER_OF_TIME && k!=0) {
System.out.println(array1[k]+"\n");
System.out.println(timeReadings[m]+"\n");
break inner;
}else
System.out.println(array1[k]+"\n");
System.out.println(timeReadings[m]+"\n");
}System.out.println("-----------------"+"\n");
}
Expected output is:
When user NUMBER_OF_TIME =2, the output should be like this.
--------------------
A
1 2 3 4 5 6
--------------------
B
7 8 9 10 11 12
--------------------
If i correctly understood what you want, this should work :
int NUMBER_OF_TIME = 2;
int n = 1;
boolean bool = true;
int[] timeReadings = {1,2,3,4,5,6,7,8,9,10,11,12};
String array1[] = {"A", "B"};
System.out.print("-----------------"+ System.lineSeparator());
System.out.print(array1[0] + System.lineSeparator());
for(int i : timeReadings) {
System.out.print(i + " ");
if(n > (timeReadings.length / NUMBER_OF_TIME) - 1 && bool) {
System.out.println(System.lineSeparator()+"-----------------");
System.out.print(array1[1] + System.lineSeparator());
bool = false;
}
n++;
}
System.out.println(System.lineSeparator()+"-----------------");
If this doesn't work for you, please provide more output examples, as others already asked.
Edit : Modified the code to output what you expect.

Printing array elements with a for loop

This is a challenge question from my online textbook I can only get the numbers to prin forward... :(
Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline.
Ex: If courseGrades = {7, 9, 11, 10}, print:
7 9 11 10
10 11 9 7
Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.
Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]).
import java.util.Scanner;
public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;
/* Your solution goes here */
for(i=0; i<NUM_VALS; i++){
System.out.print(courseGrades[i] + " ");
}
for(i=NUM_VALS -1; i>3; i++){
System.out.print(courseGrades[i]+ " ");
}
return;
}
}
This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
for (i = 0; i < NUM_VALS; i++) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for (i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
Your two loops almost were correct. Try using this code:
for (int i=0; i < NUM_VALS; i++) {
// this if statement avoids printing a trailing space at the end.
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i]);
}
for (int i=NUM_VALS-1; i >= 0; i--) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i] + " ");
}
To print backwards you want:
for(i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");
I also have been working on the this textbook question. The issue with the above code is that i has already been assigned, so trying using int in the for loop will cause an error. Below is the code I used to successfully achieve the desired outcome.
for ( i = 0 ; i <NUM_VALS; ++i) {
if (i > 0) {
System.out.print("");
}
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for ( i = NUM_VALS -1; i >=0; --i) {
if (i > 0) {
System.out.print("");
}
System.out.print( courseGrades[i] + " ");
}
System.out.println();

Java array , print what is stored in the array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
How do I print what is stored in the array in an easy way. I have been staring at this for the past 3 hours!
import java.util.Scanner;
public class December2012 {
public static void main(String[] args) {
int[] array = new int[100];
int sum = 0;
int i = 0;
Scanner input = new Scanner(System.in);
while (sum <= 100 && i < array.length) {
System.out.print("Write in the " + (i + 1) + "th number: ");
array[i] = input.nextInt();
sum += array[i];
i++;
}
System.out.print("You added: ");
System.out.print(array[i] + " ");
System.out.println("\nsum is " + sum);
}
}
The easiest way is
System.out.println(Arrays.toString(array));
Just for the record you could also use the new for-each loop
for(int no : array ) {
System.out.println(no);
}
you can do like this
for(int j= 0 ; j<array.length;j++) {
System.out.println(array[j]);
}
or
for (int j: array) {
System.out.println(j);
}
for (int i = 0 ; i < array.length; i++){
System.out.println("Value "+i+"="+array[i]);
}
thats all my friend :)

Print out a Single count value for multiple Array items

I have this really quick question, im guessing is just staring at me but im not being able to see it. I had to count the number of occurrences of a certain name in an array. I did that using a loop as i was not allowed to use classes, hashmap etc. So i have a 93 names, for example Jake occurs 5 times, i want the out to be:
Jack - 5
instead, my program displays
Jack - 5
Jack - 5
Jack - 5
Jack - 5
Jack - 5
I just want it to be printed once, here is my loop for it:
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
int count = 0;
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
System.out.println(n + " - " + count);
}
ideal output should be:
Jack - 5
i need to print asterisks as output, so i want it to say
Jack (5) *****
Each asterisk represents a occurrence, i know how to print them, and i have put it in my code but it displays
***** Jack(5)
I was wondering how i could i fix that, any ideas?
You're cycling through each name in the list and checking it each time. Consequently, you're checking the name Jack 5 times, so you get 5 outputs.
As for some reason you're not allowed to use HashMaps, this should solve it:
String name[] = new String[]{"jack", "jack", "jack", "james", "jack", "jack", "james"};
ArrayList<String> checkedNames = new ArrayList<String>();
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
if(!checkedNames.contains(n))
{
int count = 0;
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
checkedNames.add(n);
System.out.println(n + " - " + count);
}
}
Edit: As you can't use ArrayLists but can sort the array:
String name[] = new String[]{"jack", "jack", "jack", "jack", "jack", "james"};
String lastName = "";
Arrays.sort(name);
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
if(!lastName.equals(n))
{
int count = 0;
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
System.out.println(n + " - " + count);
}
lastName = n;
}
Second edit:
Firstly, Arrays is a class built into Java, just as String is:
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
Secondly, if you want it to print asterisks, then change the System.out.println line to this:
System.out.println(n + " (" + count + ")" + new String(new char[count]).replace("\0", "*"));
Please check next code:
for (int counter = 0; counter < name.length; counter++)
{
String n = (name[counter]);
int count = 0;
boolean flag = true;
for (int i = 0; i < counter; i++){
if (name[i].equals(n)) {
flag = false;
}
}
if (flag) {
for (int i = 0; i < name.length; i++){
if (name[i].equals(n))
count++;
}
System.out.println(n + " - " + count);
}
}
Here you checked if selected name not yet in the array (from 0 to counter) than you count how many times it keeps in array and display information.
Will you try having a different array (lets say encouteredNames) which will store those names whose number of occurrence you've already counted? And then execute only the 'counting' loop only when you've determined that the name to be searched has not been searched previously (or it is still not stored in the encounteredNames array).
I'm sure there are better implementations than this, but for the meantime:
String[] names = {"Jack", "James", "Charles", "Jack", "Jack", "James"};
String[] encounteredNames = new String[names.length];
int encounteredNamesCount = 0;
for (int counter = 0; counter < names.length; counter++) {
String name = (names[counter]);
boolean nameAlreadyEncountered = false;
for (int i = 0; i < encounteredNames.length && encounteredNames[i] != null; i++) {
if (encounteredNames[i] == name) {
nameAlreadyEncountered = true;
break;
}
}
if (!nameAlreadyEncountered) {
encounteredNames[encounteredNamesCount++] = name;
int count = 0;
for (int i = 0; i < names.length; i++){
if (names[i].equals(name)) {
count++;
}
}
System.out.println(name + " - " + count);
}
}

Categories

Resources