Write a method called countWords that accepts an ArrayList of String as argument and
prints out the number of words (i.e. Strings) that start with ―A‖ or ―a‖ and prints all words longer than 5 characters on one line.
My solution is like
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
while(input.hasNext()) {
String st1=input.next();
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("a")||array.get(i).startsWith("A")) {
count++;
}
}
for(int j=0; j<array.size(); j++) {
if(array.get(j).length()>5)
st[j]=array.get(j);
}
System.out.println(count);
System.out.println(st);
}
but there will be no end for typing in Strings
As the last line of your question said
but there will be no end for typing in Strings
Well That is because you did not provided any way to end the while loop.
while(input.hasNext())
Will run forever and ever waiting for next user input. You have to break the while loop once the inputting is done.
AFTERWARDS
As the question said "prints out the number of words that start with A or a and prints all words longer than 5 characters on one line."
For this you can loop through the ArrayList and check for
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")) count++;
if(array.get(i).length()>5) System.out.print(array.get(i)+" ");
and print the number of A or a Occurrence after the loop
System.out.println("\n Number of word with A or a:"+count);
Here is a working implementation of your code
public static void main(String[] args) {
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
//System.out.println(input.hasNext());
while(input.hasNext()) {
String st1=input.next();
//System.out.println((int) st1.charAt(0));
if(st1.equals("exit")) break;
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")){
count++;
}
if(array.get(i).length()>5) {
System.out.print(array.get(i)+" ");
}
}
System.out.println("\nNumber of word with A or a:"+count);
}
to end the loop you have to type exit.
Here is a solution to your problem..
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String... args){
// Sample String sentence
String sentence = "This is the sentence with 5 words starting with
all like allwords alltogether also Allnotout allother and allofus.";
// Splitting above sentence to get each word separately and storing them into List
List<String> strings = Arrays.asList(sentence.split("\\s+"));
// calling a method named countWord() as per your assignment question.
Test.countWords(strings);
}
// implementing that method
static void countWords(List<String> input){
long count = input.stream().filter(word -> word.startsWith("all") || word.startsWith("All")).count();
System.out.print("Total words starting with all/All are : "+ count +"\t");
input.stream().filter(word -> word.length() > 5).forEach( word -> System.out.print(word + "\t"));
}
}
Related
I'm actually new in java and don't know the methods very well and I'm wonder how can I find a messed up word in a string like:
the string is : deadline is Deadline, so try not to extend DeaDLINE!!!
and the word I'm looking for is "liNedeAd"
yeah it's messed up and I wanna the program Ignore case too!
String str, word;
int count= 0;
str=in.nextLine();word=in.nextLine();
String a[] = str.split(" ");
for(int i = 0;i<a.length;i++) {
// what should I do here?
if (word.equals(a[i]))
count++;
}
System.out.println(count);
Really appreciate tell me the methods that I can use.
String#equalsIgnoreCase
Use this to compares a String to another ignoring case considerations.
There are many ways to solve your problem. I have listed a few of them and I suggest you to try some more ways once you have understood these ones.
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String str = in.nextLine();
System.out.print("Enter the word: ");
String word = in.nextLine();
long count = 0;
// Using Stream API
count = Arrays.stream(str.split("\\s+|\\p{Punct}")).filter(w -> w.equalsIgnoreCase(word)).count();
System.out.println(count);
// Pre-Java8 way
count = 0;
for (String w : str.split("\\s+|\\p{Punct}")) {
if (w.equalsIgnoreCase(word)) {
count++;
}
}
System.out.println(count);
// Using regex
count = 0;
Matcher matcher = Pattern.compile("(?i)\\b" + word + "\\b").matcher(str);
while (matcher.find()) {
count++;
}
System.out.println(count);
}
}
A sample run:
Enter the sentence: deadline is Deadline, so try not to extend DeaDLINE!!!
Enter the word: deadline
3
3
3
The regex, \s+|\p{Punct} means one or more whitespace characters or a punctuation character
(?i) in the beginning of a regex pattern makes it case-insensitive.
\b specifies a word boundary.
If you are looking to match anagrams, you can define a function to find if the two words are anagram and the rest of the processing will be same as above.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String str = in.nextLine();
System.out.print("Enter the word: ");
String word = in.nextLine();
long count = 0;
// Using Stream API
count = Arrays.stream(str.split("\\s+|\\p{Punct}")).filter(w -> anagrams(w, word)).count();
System.out.println(count);
// Pre-Java8 way
count = 0;
for (String w : str.split("\\s+|\\p{Punct}")) {
if (anagrams(w, word)) {
count++;
}
}
System.out.println(count);
}
static boolean anagrams(String str1, String str2) {
if (str1.length() == str1.length()) {
// Get the char[] from strings after converting them to the same case
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return (Arrays.equals(arr1, arr2));
}
return false;
}
}
Output:
Enter the sentence: deadline is Deadline, so try not to extend DeaDLINE!!!
Enter the word: liNedeAd
3
3
Important links:
Lesson: Regular Expressions
Reference - What does this regex mean?
Processing Data with Java SE 8 Streams, Part 1
If you want to ignore cases, this would probably be the best option:
if(word.equalsIgnoreCase(a[i])
count++;
Another, less efficient way of doing it would be to use the toLowerCase() method on both strings.
I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.
QUES Write a java program that queries the user for a series of words. The program exits when the user enters quit. Before the program exit, it should display all the list of words being entered.
I have tried solving this ques but when the list of the word is displayed the spaces left for the array is also printed. Am new in java programming so please help me.
import java.util.Scanner;
class ques1
{
public static void main(String[] args)
{
String [] str=new String[20];
Scanner sc=new Scanner(System.in);
System.out.println("enter series of words and to exit write quit");
int i=0;
while(true){
str[i]=sc.nextLine();
if(str[i].equals("quit") || str[i].equals("QUIT"))
break;
else
i++;
}
System.out.println();
System.out.println("----------------------------");
for (int j=0;j<str.length;j++)
{
System.out.println(str[j]);
}
}
}
Arrays have fixed space allocated (in your case is 20) filled with null and will will produce ArrayIndexOutOfBounds if the user enter more than 20 words.
Expect that, since you are storing the index of the last inserted array element you can simple loop from 0 to i that are the only filled spaces of the array:
for (int j=0; j <= i; j++) {
System.out.println(str[j]);
}
use ArrayList<String> it's a dynamic array and is more suitable for this functionality
ArrayList<String> words = new ArrayList<>();
while(true){
String word = sc.nextLine();
if (!word.toLowerCase().equals("quit"))
word.add(word);
else
break;
}
for(String word : words)
System.out.println(word);
I want to count the number of times "the" shows up in an array of tokens I made from user input and store it in a variable named "theCount". I'm iterating through the array with a for loop and checking for "the" with an if statement.
I am not allowed to use regular expressions.
This is what I have so far:
import java.util.*;
public class theCount
{
public static void main (String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = userInput.nextLine();
String[] input = sentence.split(" the");
int theCount = 0;
for (String token : input) {
if (token == "the")
theCount++;
System.out.print("\n" + theCount); //I want it printed after
//iteration.
}
}
}
There are couple of problems:
split(" the") uses " the" as delimiter and gives rest of the words. Best is to split using whitespace.
Use token.equals("the") instead of ==.
if you want to count number of occurrence use this sample code:
import java.util.*;
public class theCount {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = userInput.nextLine();
int theCount = sentence.length() - sentence.replace("the", "").length();
System.out.print("Number of occurrence: " + theCount);
}
}
You can add the input to a arraylist and then can play around with it.
One way is to get the count from frequency method.
List<String> arrayList = new ArrayList<String>();
arrayList.add("String"); //add all the words.
Collections.frequency(arrayList, "the");
Second way is to get the count from map.
Map<String, Integer> map = new HashMap<String, Integer>();
for(String s : arrayList){
Integer count = map.get(s);
map.put(s, count==null?1:count+1);
}
//the below will give you the count of any word.
map.get("the");
As of Java 8 you could you stream api to solve this. That will be more concise. Take the following code as example
public static void main(String[] args) {
String str = "The is the for THE and the the the the The The";
long count = Stream.of(str.split(" "))
.filter(i -> i.equalsIgnoreCase("the"))
.count();
System.out.println(count);
}
=== Update ===
public static void main(String[] args) {
String str = " there these theology";
long count = Stream.of(str.split(" "))
.map(String ::toLowerCase)
.filter(i -> i.contains("the"))
.count();
System.out.println(count);
}
=== Update ===
This solution will work even there are multiple same sub strings in a string.
public static void main(String[] args) {
String str = " thesethefajfskfjthetheasdfjasdkfjthe";
String findStr = "the";
int count = 0;
for (String s : str.split(" ")) {
count += s.toLowerCase()
.split(findStr, -1).length - 1 ;
}
System.out.println(count);
}
This SO post will help you to understand, how to find all sub string in a single string.
import java.util.Scanner;
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
for(int i=0; i<w.length();i++)
System.out.println(w.charAt(i));
}
}
This is what I have so far and I can't figure how to make it so that if the word is 5 letters or longer to print it one letter per line and if not to just print the word. So far it'll just print any word with one letter per line.
You are very close. The only thing missing is an if-else conditional statement, to check whether the word has a length of five. Without this check, you will always print the string one character per line, regardless of its length.
import java.util.Scanner;
public class SeperateLetters {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w = scan.nextLine();
if (w.length() >= 5) { // print one char per line if length is 5
for (int i = 0; i < w.length(); i++)
System.out.println(w.charAt(i));
} else {
System.out.println(w); // otherwise, print the whole string
}
}
}
Use an if-else statment to check if w.length() == 5 or not.
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
if( w.length() > 5)
{
for(int i=0; i<w.length();i++)
{
System.out.println(w.charAt(i));
}
}
}
}