How can i change the output from "my name is" from {2=1 4=1} to >the number of words with the length of 2 is 1 and then on the next line the amount of word with the length of 4 is 1, like the output underneath:
//You have typed the sentence: my name is
//the number of words with the length of 2 is 1
//the amount of word with the length of 4 is 1
Basically how can I change '{2=2, 4=1}' to a sentence form?
This is my code:
public static void main(String args[]) {
System.out.println("Write your sentence please:");// prints out the first instruction.
Scanner scan = new Scanner(System.in); //object initialisation.
String line=" ";//declaration for letters(String) characters.
//int max = 20; //declaration for number(int) characters.
while((line=scan.nextLine())!=null) { //scanner instruction, get a line from the key board.
String[] tokens = line.split(" ");// splits the words
Map<Integer,Integer> tokensLength = new HashMap<Integer,Integer>();
for (int i = 0; i < tokens.length; i++) {// this line of code checks for what must be true to carry on.
int length = tokens[i].length();
if (tokensLength.containsKey(length))
tokensLength.put(length, tokensLength.get(length) + 1);
else
tokensLength.put(length, 1);
}
for (Integer length : new TreeSet<Integer>(tokensLength.keySet()))
System.out.println("You have typed the sentence: " + line);//prints out what you have typed.
System.out.println("The word length frequency of the sentence is " + tokensLength);//prints out the results
}//End of scanner instruction
}//End of main
Thank you! Any help would be much appreciated!
Use that to iterate over the map and write nice sentences :)
for (Entry<Integer, Integer> entry : tokensLength.entrySet()){
System.out.println("There are "+entry.getValue()+" words of length "+entry.getKey());
}
Related
This question already has answers here:
Word frequency count Java 8
(11 answers)
Closed 3 years ago.
I want to count total number of duplicate word or repeating word in a sentence. Here I am able to print the words but not able to count those words.
import java.util.*;
public class Duplicate {
public static void main(String[] args) {
String input = "Big black bug bit a big black dog on his big black nose";
//Scanner scanner = new Scanner(System.in);
//System.out.println("Enter the sentence");
//String input = scanner.nextLine();
int count;
int counter=0;
//Converts the string into lowercase
input = input.toLowerCase();
//Split the string into words using built-in function
String words[] = input.split(" ");
System.out.println("Duplicate words in a given string : ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
//Set words[j] to 0 to avoid printing visited word
words[j] = "0";
counter=counter+1;
}
}
//Displays the duplicate word if count is greater than 1
if(count > 1 && words[i] != "0") {
System.out.println(words[i]);
}
}
System.out.println("Total Duplicate words in a given string : " +counter);
}
}
I expect output :--
Duplicate words in a given string : big black
Total Duplicate words in a given string : 2
The output is coming like :
Duplicate words in a given string : big black
Total Duplicate words in a given string : 10
Total count is showing 10 instead of 2.
Moving the increment to counter to here should work:
if (count > 1 && !words[i].equals("0")) {
counter++;
System.out.println(words[i]);
}
Instead of in the second loop. Right now counter will be incremented every time you find another occurrence of a duplicate. Moving counter below will only increment it when you've discovered that there is a duplicate word.
That said, this approach can be simplified by using a Map to count the number of times each word appears.
Try using a HashMap instead of 2 for loops as below
public static void main(String[] args) {
String input = "Big black bug bit a big black dog on his big black nose";
HashMap<String, Integer> dupCount = new HashMap<>();
//Converts the string into lowercase
input = input.toLowerCase();
//Split the string into words using built-in function
String words[] = input.split(" ");
System.out.println("Duplicate words in a given string : ");
for(int i = 0; i < words.length; i++) {
if(dupCount.containsKey(words[i])){
int cnt = dupCount.get(words[i]);
cnt = cnt + 1;
dupCount.put(words[i], cnt);
}else{
dupCount.put(words[i], 0);
}
}
for(Map.Entry<String, Integer> test : dupCount.entrySet()){
if(test.getValue() > 1) {
System.out.println("Duplicate words in a given string : " +test.getKey() + " : " + test.getValue());
}
}
}
In this case last statement will be printed each time a duplicate occurs you can modify it as per your need.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
Inside the first loop, it is not taking the first word as an input. When I'm not taking input of the string length from the user, it's working fine. See the output where its not taking input the word 0.
public class Stringinput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many words do you need to make the sentence: ");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.printf("Enter word no %d : ",i);
names[i]= in.nextLine();
}
System.out.println("The sentence you made is: ");
for (int i = 0; i < names.length; i++) {
System.out.print(names[i]+" ");
}
System.out.println("");
}
}
And this the output:
How many words do you need to make the sentence:
4
Enter word no 0 : Enter word no 1 : My
Enter word no 2 : name
Enter word no 3 : is
The sentence you made is:
My name is
BUILD SUCCESSFUL (total time: 11 seconds)
Scanner.nextInt() method does not consume the newline character of the input so it goes to the next Scanner.nextLine. It is similar if you use nextline after next() method
Just add a dummy scanner.nextLine() before the loop and keep going.
nextInt() does not consume the new line character entered after the number so your first nextLine() will, so you need to do
public class Stringinput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many words do you need to make the sentence: ");
int n = in.nextInt();
in.nextLine(); // consume leftover new line here
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.printf("Enter word no %d : ",i);
names[i]= in.nextLine();
}
System.out.println("The sentence you made is: ");
for (int i = 0; i < names.length; i++) {
System.out.print(names[i]+" ");
}
System.out.println("");
}
}
Use .next() instead of .nextLine() as you only need a single word, not a sentence because the Scanner.nextInt method does not consume the last newline character.
for (int i = 0; i < names.length; i++) {
System.out.printf("Enter word no %d : ",i);
names[i]= in.next();
}
Output:
How many words do you need to make the sentence:
4
Enter word no 0 : my
Enter word no 1 : next
Enter word no 2 : r
Enter word no 3 : t
The sentence you made is:
my next r t
I am supposed to ask the user to enter a string and I am supposed to parse the string and keep track of the number of the alphabet. So like if the user enter the string "abee"
it displays the output as :
a: 1
b: 1
c: 0
e: 2
So far I have been able to get the string and parse it and store the elements into an array. And I have been able to print out each letter at a time with a for loop. Now the problem I am facing is that when it prints out the letters along with how many of the letters exist in the phrase the numbers don't match up. For example if I enter the letters : "abccddee"
it prints out:
a: 1
b: 1
c: 1
c: 0
d: 0
d: 0
e: 0
e: 0
For testing purposes I am using my own string rather than using the scanner.
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//separate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(int i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}
}//end of main method
}//end of class
Rather than working with simple array you can work with java's Collection's HashMap.
With HashMap the main working goes around with the for loop, will check if the Character is already present in the HashMap if it is then we will get the value associated with Character and will add 1 with the existing value and if the Character is not present then we will put a Character in HashMap and will store the initial count 1 with the associated character.
HashMap<Character, Integer> lettersCount = new HashMap<>();
String phrase = "abccddee";
int length = phrase.length();
int count = 1;
for (int i = 0; i < length; i++) {
int integer = 0;
char charAt = input.charAt(i);
if (!lettersCount.containsKey(charAt)) {
lettersCount.put(charAt, 0);
}
integer = lettersCount.get(charAt);
integer = initialCount + integer;
lettersCount.put(charAt, integer);
}
System.out.println(lettersCount);
You are using array which you will be needed to intialize first at time of declaration this will create a extra memory space which will be waste if all 26 letters are not being encountered and as per the code you have provided in the question you are allocating 3 arrays so it will take much more memory, So rather this solution will require only a HashMap (HashMap will allocate memory according to the key and value inserted in HashMap)and a for loop which will just compute the occurence of Charater and to use it again further in your program will be much more easier with it.
You are printing within the for loop. You should print the frequency outside that loop.
The method which you are using is not scalable. You will have to write 52 case statements in your switch given that the phrase consists only of uppercase and lowercase English alphabets.
A better way to do the same would be to use the ASCII encoding for your purpose. You can have something on the following lines:
int frequency[] = new int[128];
for (int i = 0; i < phrase.length(); i++) {
frequency[(int) phrase.charAt(i)]++;
}
In this method frequency array is used to count the occurrences of first 128 ASCII characters in phrase string. Operation (int) phrase.charAt(i) simply converts the character into corresponding ASCII code and we increase the counter for that character by 1. At the end of the processing, frequency array will contain the number of occurrences of first 128 ASCII characters in the given phrase string. Simply print this frequency to achieve desired output.
print statement must be outside the while for loop.
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
updated:
you need to parse entire string first, then start printing.
import java.io.*;
import java.util.*;
class CountLetters {
public static void main(String[] args)
{
int i;
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//seperate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
}
for(i=0;i<5;i++)
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}//end of main method
}//end of class
Your solution with arrays is a bit complicated. By using a Map instead we can directly associate the encountered characters with the number of times they have been encountered, thus making it very straight-forward to increase the counter and to output the counter without having to look up indices in different arrays.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the phrase entered from user
char[] letters = phrase.toCharArray();
System.out.println("letters length: " + letters.length);
// Map to keep track of all encountered characters and the
// number of times we've encountered them
Map<Character, Integer> characterCounts = new HashMap<>();
for(int i=0; i<letters.length; i++)
{
Character character = letters[i];
if(characterCounts.containsKey(character))
{
// We've encountered this character before, increase the counter
characterCounts.put(character, characterCounts.get(character) + 1);
}
else
{
// This is the first time we encounter this character
characterCounts.put(lowerChar, 1);
}
}
// Iterate over all character-counter pairs and print them
for(Map.Entry<Character, Integer> entry : characterCounts.entrySet())
{
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}//end of main method
}//end of class
HashMap - Stores keys and values in an unordered way and contains only unique keys.
TreeMap - Stores keys and values in a naturally ordered way and contains only unique keys.
LinkedHashMap - Stores keys and values in the order of keys insertions and contains only unique keys.
The appropriate data structure for such requirement will be a Map. If you want to maintain the order of letters in which they appeared in the String, you can use LinkedHashMap, if the order of letters in not a concern then you can you a HashMap. I am using LinkedHashMap for my example.
public class Test {
public static void main(String[] args) {
//Taking the input from the user
System.out.println("Enter the String"); //I am entering "abccddee" for your example
Scanner sc = new Scanner(System.in);
String input = sc.next();
//LinkedhashMap preserves the order in which input was supplied
LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>();
for(int i=0; i<input.length(); i++){
//method get will return null if the letter is not available at the given index else it will return the count
Integer j = lhm.get(input.charAt(i));
//If the chracter was not present in the String
if(j==null)
lhm.put(input.charAt(i),1);
//If the character was present in the String
else
lhm.put(input.charAt(i),j+1);
}
for(Character c : lhm.keySet())
System.out.println(c+": "+lhm.get(c)+" ");
}
}
The output will be:
a: 1
b: 1
c: 2
d: 2
e: 2
I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:
The first line of input contains a single integer N, indicating the
number of lines in the input. This is followed by N lines of input
text.
I wrote the following code:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String lines[] = new String[n];
for(int i = 0; i < n; i++){
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
}
And an interaction with the program:
5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
What's the problem? I can't input 0th line.
Suggest a better method to input n numbers of lines where n is user provided to a string array.
The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.
Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.
Start paying attention to style and code formatting. It promotes readability and understanding.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
I don't know what you would consider better:
Try changing
System.out.println("Enter " + i + "th line");
to
System.out.print("Enter " + i + "th line:");
Makes it look better.
A better way of inputting lines would be to keep reading input lines until you see a special termination char.
Use an ArrayList to store the lines then you don't need to declare the size beforehand