I'm trying to read a sentence in Java and to know how many words are in there. This is what I've done:
public class TestWords {
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr=new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
int TotalSizeOfPhrase = Phrase.length();
double number;
for (int i=0; i < TotalSizeOfPhrase; i++)
{
if (Phrase[i] != number && Character.isWhitespace(s.charAt(i)))
{
TotalWords = TotalWords + 1;
}
}
}
}
And I'd like to know how to code this:
if (Phrase[i]!= 'of an **arbitrary** number && white space')
then:
TotalWords = TotalWords + 1;
Because it marks a mistake when I type this:
Character.isWhitespace(s.charAt(i))
There are couple of mistakes
System.out.println("Give your phrase : ");
Scanner scan = new Scanner(System.in);
String Phrase;
Phrase = scan.nextLine();
System.out.println("Enter age : ");
int number = scan.nextInt();
// replace the number with empty string mean nothing
Phrase = Phrase.replace(String.valueOf(number), "");
Phrase = Phrase.concat(" "); // add space at end for loop calculation
int TotalSizeOfPhrase = 0; // set tot =0
int count=0; // a count variable to keep track of the word length
for (int i=0; i<Phrase.length(); i++)
{
count++;
if(Character.isWhitespace(Phrase.charAt(i)))
{
if(count-1>1){ // if size of word ( -1 is there for space size)
// is greater than 1 than increment count
TotalSizeOfPhrase=TotalSizeOfPhrase+1;
}
count=0;
}
}
System.out.println(TotalSizeOfPhrase);
scan.close();// don't forget
Inuput :
Hello i'm 20 and I'm a beginner
20
output :
5
The way i would do it, is to split the line by white spaces (getting the words), adding them to array and then getting this array length which would be equal to word count.
Phrase = Phrase.trim(); //make sure there is no spaces at start or end of the line
String[] words = Phrase.split(" "); //get the words
int word_count = words.length; //get the word count in line
if you want to get the number of words in the sentence , you could use this code :
int numberOfWords = Phrase.trim().isEmpty() ? 0 : trim.split("\\s+").length;
You can use this code:
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr = new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
String[] words = Phrase.trim().split(" ");
System.out.println("Totals Number Of Words: " + words.length);
for (String word : words) {
System.out.println(word.trim());
}
}
Related
I'm searching for word(s) in a string array and if found I want to return their line.
I have tried to divide the searched input in an array and then search it in the paragraph array line by line. Which does not really work.
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
Assuming I can search for at most 10 words at a time.
Lets say user enters : "Hello name the up"
I want the answer : At line 1
At line 1
At line 2
At line 3
If I ask for a word in the 2nd or the 3rd index of the paragraph it does not work I dont understand why (getting no error messages)
Here is a working code compare it to yours and figure out the issue:
public static void main(String[] args)
{
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
String toBeSearched;
String curSearch;
boolean intIndex = false ;
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word+ "found at line: "+ y);
}
}
}
}
For example lets say you have the string "greg". The program prompts you to enter which character to remove and you say "g", the program then prompts "Enter the g you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.)" and you enter "2". The program then outputs the new sentence which is "gre". This is a piece of my program for my CSCI class and I know how to do it using replace(), but my professors says we can only use loops and these string methods length, concat, +, charAt, substring, and equals (or equalsIgnoreCase). I can't seem to figure it out any help would be appreciated. Thank you!
As pointed out in comments, you need to maintain count for number of occurrences and build a new string skipping nth occurence(Strings are immutable in Java):
public static String removeNthCharacter(String input, char ch, int occurence) {
StringBuilder sb = new StringBuilder();
int totalOccurences = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
totalOccurences++;
if (totalOccurences == occurence) {
// Skip This character
continue;
}
}
sb.append(input.charAt(i));
}
return sb.toString();
}
I tested this and it seems to generate expected output:
public static void main(String[] args) {
System.out.println(removeNthCharacter("greg", 'g', 2));
System.out.println(removeNthCharacter("greggggeegeegggg", 'g', 6));
}
This produces this output:
src : $ java RemoveChar
gre
greggggeeeegggg
public static void main(String[] args) {
System.out.print("Enter a String : ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.print("Enter character to be removed : ");
scanner = new Scanner(System.in);
char character = scanner.next().charAt(0);
System.out.println("Possible positions of "+character+" : ");
// find all occurrences forward
for (int i = -1; (i = input.indexOf(character, i + 1)) != -1; i++) {
System.out.println(i);
}
System.out.print("Select any above index to remove : ");
scanner = new Scanner(System.in);
int index = scanner.nextInt();
System.out.println("Result : "+input.substring(0, index)+input.substring(index+1, input.length()));
}
output
Enter a String : greg
Enter character to be removed : g
Possible positions of g :
0
3
Select any above index to remove : 0
Result : reg
output
Enter a String : greg
Enter character to be removed : g
Possible positions of g :
0
3
Select any above index to remove : 3
Result : gre
I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}
I want to the longest name for 5 given names. I think I should use compareTo() method or length()?
Output must be like this :
enter 5 names :
Joey
Mark
Catherine
Zachery
Foster
Longest name is Catherine.
What method should I use and how? This is my code so far:
Scanner x = new Scanner(System.in);
String name = ""
System.out.print("Enter 5 names");
name = x.nextLine();
name2 = x.nextLine();
name3 = x.nextLine();
name4 = x.nextLine();
name5 = x.nextLine();
if(name.compareTo(name2)>0) //is this method right?
.compareTo tells you which string comes first in lexicographic order (<0 if s1 < s2, 0 if s1==s2, >0 if s1>s2)
String s1 = "abc";
String s2 = "def";
s1.compareTo(s2) < 0;
.length() returns the length of a string
s1.length()==3;
In your case, you need to compare based on length, so you need the latter. If it's only 5 names, you can take the first and assume it's the longest, and then read the others one by one by keeping the "longest so far" saved and comparing them as they come. After all, you only care about the longest.
If you wanted them to be sorted by length, while still keeping them all, you'd need to store them in some sort of collection (list, array), then sort it based on length.
The problem is easy enough, so I won't provide directly the code, try to grok it yourself, you can do it :)
import java.util.Scanner;
public class LenghtyName {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
/*
Instead of declaring 5 different String variable
just use String array with size = 5
*/
String[] names = new String[5];
System.out.print("Enter 5 names :");
names[0] = x.nextLine();
names[1] = x.nextLine();
names[2] = x.nextLine();
names[4] = x.nextLine();
names[5] = x.nextLine();
//Assume lenthyName as empty String
String lengthyName = "";
/*
Iterate over String array using for-each loop
*/
for (String name : names) {
/*
-Check null to avoid NullPointerException
-Trim the left and right blank space in name by #trim()
-Compare current name length with lengthyName if greater
replace the lengthyName by current name.
*/
if (name != null && name.trim().length() > lengthyName.length()) {
lengthyName = name;
}
}
/*
Print length name
*/
System.out.println("Longest name is " + lengthyName);
}
}
What about this?
Scanner in = new Scanner(System.in);
// no need to have 5 all over the code.
// Define it once to avoid "magic nubmers"
int namesCount = 5;
// fun fact: shortest name is always "". We don't have to use null
String longestName = "";
System.out.print("Enter " + nameCount + " names:");
for (int i=0; i< nameCount; i++){
// store new name from user
String candidate = in.readLine();
// is this one longer than the current longest?
if (longestName.length() < candidate.length()){
// found a longer name
longestName = candidate;
}
}
System.out.println("Longest name is " + longestName);
This gives up storing the names, as it seems you only use the longest one anyway. It also generalizes the number of names to iterate, and most importantly the variable names are meaningful names.
Here's a solution that should work:
public class LongestWord {
public static String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
}
public static void main(String[] args) {
String[] toppings = {"Cheeddddddddddse", "Pepperoni", "Black Olivesddd"};
String longestString = getLongestString(toppings);
System.out.format("longest string: '%s'\n", longestString);
}
}
An easy way would be a for loop to read 5 names and find the length for largest name. Using the for loop avoids the creation of 5 deterrent string variables.
If you want to use those names later you can go for String array.
public static void main(String[] args) throws IOException {
Scanner x = new Scanner(System.in);
String name = "";
String maxName = "";
int maxLength = 0;
System.out.println("enter 5 name :");
for (int i = 0; i < 5; i++) { // read 5 names
name = x.nextLine();
if (maxLength < name.length()) { // check longest name
maxLength = name.length();
maxName = name; // store in temp variable to show
}
}
System.out.println("Longest name is " + maxName); // print largest name
}
Output:
enter 5 name :
raj
sita
gita
mukherjee
rita
Longest name is mukherjee
Here's a solution that should work with any number of entries:
Scanner x = new Scanner(System.in);
String name = "", temp="";
while (x.hasNextLine()){
temp = x.nextLine();
if (temp.length() > name.length()) name = temp;
}
System.out.println("Longest is " + name);
You'll need to Ctrl + Z to end the inputStream on Windows
this is my code for comparing 3 input strings by their length:
public static void main(String[] args) {
String string1 , string2 , string3;
Scanner input = new Scanner(System.in);
System.out.println("Enter three string names to compare");
string1 = input.nextLine();
string2 = input.nextLine();
string3 = input.nextLine();
if (string1.length()>string2.length()) {
if (string1.length() > string3.length())
System.out.println("String 1 has the longest length , length = "+string1.length());
}
if (string2.length()>string1.length()){
if(string2.length()>string3.length())
System.out.println("String 2 has the longest length , length = "+string2.length());
}
if (string3.length()>string1.length()) {
if (string3.length() > string2.length())
System.out.println("String 3 has the longest length , length = " + string3.length());
}
}
//SIMPLE JAVA SOLUTION
class GFG
{
String longest(String names[], int n)
{
String res="";
for(int i=0;i<n;i++)
{
if(res.length()<names[i].length())
{
res=names[i];
}
}
return res;
}
}
So, I've got a java assignment in which I have a String with a phrase. I need to count each word the phrase has and then count how many letters each word has. I've been able to split the phrase into words by using the Tokenizer, and then count and print the amount of words with .countTokens(). However, I'm not being able to count the letters in each word.
Basically the output should be something like this:
"Nihil veritas est"
Words: 3
Nihil: 5 letters
Veritas: 7 letters
Est: 3 letters
Here's my code so far:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
StringTokenizer stoken = new StringTokenizer(phrase);
System.out.println("Your phrase has "+stoken.countTokens()+"words");
}
Try this:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
String[] words = phrase.split(" ");
System.out.println("The number of words is:"+words.length);
for(int i=0; i<words.length; i++){
System.out.println(words[i]+" is "+words[i].length()+" letters long.");
}
}
}
This code uses split() instead of Tokenizer. It just seemed easier to me.
Try this:
import java.util.Scanner;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("PLease enter your phrase");
String phrase = in.nextLine();
StringTokenizer st = new StringTokenizer(phrase);
System.out.println("Your phrase has " + st.countTokens() + " words");
// Loop thorough to count number of letters in each word.
while (st.hasMoreTokens()) {
String tokenName = st.nextToken();
System.out.println(tokenName + ": has " + tokenName.length() + " letters");
}
}
}
Here is my solution to your problem:
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
// get an array each having a word using split
String[]words = phrase.split(" ");
//print count of words?
System.out.println("Words: "+words.length);
//loop over the words
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i]+": "+words[i].length()+" letters");
}
}
public class wordCount
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println(" Enter a String1");
String str=sc.nextLine();
System.out.println(" Entered String : ");
System.out.println(str);
//logic
char ch[]=str.toCharArray();
str="";
int count=0;
for (int i = 0; i < ch.length; i++)
{
if(ch[i]!=' ')
{
str=str+ch[i];
count++;
}
else if(ch[i-1]!=' ')
{
/*str=str+"-->"+count +" ";*/
System.out.println(str+"--->"+count);
count=0;
str="";
}
}
System.out.println(str+"--->"+count);
sc.close();
}
}