Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to count the number of words in a String, find the length of each word in a String and then determine the largest word in the String using only the String class. I can't use arrays. Does anyone know a way to extract each word from the string?
int indexOfSpace = 0;
int nextIndexOfSpace = 0;
String sentence = "This is a sentence";
int lastIndexOfSpace = sentence.lastIndexOf(" ");
while(indexOfSpace != lastIndexOfSpace){
nextIndexOfSpace = sentence.indexOf(" ",indexOfSpace);
String word = sentence.subString(indexOfSpace,nextIndexOfSpace);
System.out.println("Word: " + word + " Length: " + word.length());
indexOfSpace = nextIndexOfSpace;
}
String lastWord = sentence.subString(lastIndexOfSpace);
System.out.println("Word: " + lastWord + " Length: " + lastWord.length());
You need to do something along the above lines. Since your question seems like a homework question, I am not going to put an effort into debugging this. This is as far as I can go into answering what seems like a homework question.
Debug it, use it.
Use StringTokenizer
String sentence = "This is a sentence";
StringTokenizer t = new StringTokenizer(sentence);
String word ="";
while(t.hasMoreTokens())
{
word = t.nextToken();
System.out.println(word);
}
The Output should be
This
is
a
sentence
Scanner s= new Scanner("Put your string here");
while(s.hasNext()){
String word= s.next();
}
Edit using only String:
String myString = "hello world how are you";
for (int i = 0, //start of word
j = 0; //end of word
i < myString.length(); //make sure we're in bounds
i = j + 1) { //Start from where we left off plus one
//to get rid of space we just found
j = myString.indexOf(" ", i); //find the next space
if (j == -1) { //-1 means no more spaces so we're done
break;
}
String word = myString.substring(i, j); //here is your word
}
This can be done using the split(" ")//which splits the string(maybe a sentence) by spaces into words and use array list to store List words = Arrays.asList(sentence.split(" "));
A raw version, probably efficient, could be something like this. This assumes that there are single spaces between the words including in the end which can easily be tweaked make it perfect.
int wordCount = 0;
int maxWordLen = 0;
String longestWord = null;
if(input != null){//given word
int currentWordStart = 0;
for(int i = 0; i < input.length(); i++){
char currentChar = input.charAt(i);
if(' ' == currentChar){
wordCount++;
String currentWord = input.substring(currentWordStart, i);
int currentWordLen = i - currentWordStart;
System.out.println("Word: " + currentWord + ", Length: " + currentWordLen);
currentWordStart = i + 1;
if(maxWordLen < currentWordLen){
maxWordLen = currentWordLen;
longestWord = currentWord;
}
}
}
}
System.out.println("Word count: " + wordCount);
System.out.println("Longest word: " + longestWord + ", Length: " + maxWordLen);
Related
I am working on a simple program where the goal is to print the i'th character of each i'th word that the user inputs. I have the number of words set to 5 as an example, and so the user needs to enter 5 words. However, the program returns the i'th character of just one of the i'th words (I have "i" set to 2). How would I fix this so that it prints the i'th character for each i'th word, instead of just one of the i'th words?
Here is my code for reference:
import java.util.Scanner;
public class Words {
public static void main(String[] args) {
int numWords = 5;
Scanner keyboard = new Scanner(System.in);
String[] words = new String[numWords];
System.out.print("Enter " + numWords + " words: ");
for (int i = 0;i<numWords;i++) {
String word = keyboard.next();
words[i] = word;
}
keyboard.close();
int iVal = 2;
int length = words[iVal].length();
if (iVal >= (length - 1)) {
System.out.print(words[iVal].charAt(length-1));
}
else {
System.out.print(words[iVal].charAt(iVal));
}
}
}
This is the output I get as an example:
Enter 5 words: one two three four five
r
The loop may be implemented similar to what has already been implemented:
for (int i = 0; i < numWords; i++) {
String word = words[i];
if (i < word.length()) {
System.out.println("char #" + i + " = " + word.charAt(i));
} else {
System.out.println("Word + " + word + " is too short to get char #" + i);
}
}
This simply splits the string on spaces and the prints the ith-1 character of the ith word (so the first word would be character at 0, the second word would be character at 1 and so forth). If the word is too short, it is skipped.
String str = "A is for apple and E is for Encyclopedia";
int i = 0;
for (String s : str.split("\\s+")) {
if (i < s.length()) {
System.out.println(s + " --> " + s.charAt(i));
}
i++;
}
Prints
A --> A
is --> s
for --> r
apple --> l
Encyclopedia --> e
This question already has answers here:
Simple way to count character occurrences in a string [duplicate]
(15 answers)
Closed 4 years ago.
String sentence = JOptionPane.showInputDialog (null, "Write a sentence.");
String letter = JOptionPane.showInputDialog(null, "Write a letter");
while (true) {
if (letter.equals("Stop"))
System.exit(0);
//to calculate number of specific character
else {
int countLetter = 0;
int L = letter.length();
for (int i = 0; i < L; i++) {
if ((letter.charAt(i) = .....))
countLetter++;
}
}
}
Is it possible to replace the dots to make the program count how many times the given letter occures in the sentence written in the first string?
Since Java 8, there is an elegant solution to this.
int count = letter.chars().filter(ch -> ch == 'e').count();
This will return the number of occurences of letter 'e'.
if your String letter contains a one character use this letter.charAt(0) and then replace dots with this. Also remember to use == instead of = here. = means you are just asigning and == uses to compare two values.
If you have to use a for loop and want to stick to the old fashioned way, try this:
String sentence = "This is a really basic sentence, just for example purpose.";
char letter = 'a';
int occurrenceOfChar = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == letter) {
occurrenceOfChar++;
}
}
System.out.println("The letter '" + letter
+ "' occurs " + occurrenceOfChar
+ " times in the sentence \""
+ sentence + "\"");
The sentence and the letter are just examples, you have to read the user input.
You can use Guava Lib to perform this operation faster without iterating string.
CharMatcher.is('e').countIn("Write a letter");
Will return 3
So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}
I believe you meant to use isLetter, not isAlphabetic.
Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?
I'm trying to make a program that count the number of words, lines, sentences, and also the number of articles 'a', 'and','the'.
So far I got the words, lines, sentences. But I have no idea who I am going to count the articles. How can a program make the difference between 'a' and 'and'.
This my code so far.
public static void main(String[]args) throws FileNotFoundException, IOException
{
FileInputStream file= new FileInputStream("C:\\Users\\nlstudent\\Downloads\\text.txt");
Scanner sfile = new Scanner(new File("C:\\Users\\nlstudent\\Downloads\\text.txt"));
int ch,sentence=0,words = 0,chars = 0,lines = 0;
while((ch=file.read())!=-1)
{
if(ch=='?'||ch=='!'|| ch=='.')
sentence++;
}
while(sfile.hasNextLine()) {
lines++;
String line = sfile.nextLine();
chars += line.length();
words += new StringTokenizer(line, " ,").countTokens();
}
System.out.println("Number of words: " + words);
System.out.println("Number of sentence: " + sentence);
System.out.println("Number of lines: " + lines);
System.out.println("Number of characters: " + chars);
}
}
How can a program make the difference between 'a' and 'and'.
You can use regex for this:
String input = "A and Andy then the are a";
Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(and)|(the))\\b").matcher(input);
int count = 0;
while(m.find()){
count++;
}
//count == 4
'\b' is a word boundary, '|' is OR, '(?i)' — ignore case flag. All list of patterns you can find here and probably you should learn about regex.
The tokenizer will split each line into tokens. You can evaluate each token (a whole word) to see if it matches a string you expect. Here is an example to count a, and, the.
int a = 0, and = 0, the = 0, forCount = 0;
while (sfile.hasNextLine()) {
lines++;
String line = sfile.nextLine();
chars += line.length();
StringTokenizer tokenizer = new StringTokenizer(line, " ,");
words += tokenizer.countTokens();
while (tokenizer.hasMoreTokens()) {
String element = (String) tokenizer.nextElement();
if ("a".equals(element)) {
a++;
} else if ("and".equals(element)) {
and++;
} else if ("for".equals(element)) {
forCount++;
} else if ("the".equals(element)) {
the++;
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to make a program that accepts a word then displays the word diagonally. So far I've only gotten it to display vertically.
The scanner accepts "zip", then outputs:
z
i
p
How do i make it go like this:
z
i
p
Here is my code:
import java.util.Scanner;
public class exercise_4
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your words");
String word = scan.nextLine();
for (char ch: word.toCharArray())
{
System.out.println(ch);
}
}
}
You can try something like this:-
String s = "ZIP";
String spaces = "";
for (int i = 0; i < s.length(); i++) {
System.out.println(spaces + s.charAt(i));
spaces += " ";
}
You can do
String spaces = ""; // initialize spaces to blank first
for (int i = 0; i < word.length(); i++) { // loop till the length of word
spaces = spaces + " "; //
// increment spaces variable
// for first iteration, spaces = ""
// for second iteration, spaces = " "
// for third iteration, spaces = " "
// for fourth iteration, spaces = " " and so on
System.out.println(spaces + word.charAt(i));
// this will just print the spaces and the character of your word.
}
Try this
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your words");
String word = scan.nextLine();
String i = new String();
for (char ch : word.toCharArray()) {
System.out.println(i+ch);
i=i+" ";
}
I would prefer a StringBuilder for concatenation.
String s = "ZIP";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
System.out.println(sb.toString()+ s.charAt(i));
spaces.append(" ");
}
With StringUtils from commons-lang:
int indent = 0;
for (final char c : "ZIP".toCharArray()) {
System.out.println(StringUtils.repeat(" ", indent) + c);
indent++;
}