I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.
How can I code this? Also, how do I display it with System.out.println();?
Okey so, here is my code so far:
import java.util.Scanner;
import java.util.StringTokenizer;
public class OddSentence {
public static void main(String[] args) {
String sentence, word, oddWord;
StringTokenizer st;
Scanner scan = new Scanner (System.in);
System.out.println("Enter sentence: ");
sentence = scan.nextLine();
sentence = sentence.substring(0, sentence.length()-1);
st = new StringTokenizer(sentence);
word = st.nextToken();
while(st.hasMoreTokens()) {
word = st.nextToken();
if(word.length() % 2 != 0)
}
System.out.println();
}
}
I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.
Based on what you've given alone, I would say use #split()
String example = "What is your deal?"
String[] spl = example.split(" ");
/*
args[0] = What
args[1] = is
args[2] = your
args[3] = deal?
*/
To display the array as a whole, use Arrays.toString(Array);
System.out.println(Arrays.toString(spl));
To read and split use String.split()
final String input = "What is your deal?";
final String[] words = input.split(" ");
To print them to e.g. command line, use a loop:
for (String s : words) {
System.out.println(s);
}
or when working with Java 8 use a Stream:
Stream.of(words).forEach(System.out::println);
I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.
String str = "This is a string";
String[] strArray = str.split(" "); //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
if((strArray[i].length() % 2) == 0) { //if there is an even number of characters in the string
System.out.println(strArray[i]); //print the string
}
}
Output:
This is string
If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)
This will give you just a as the output (the only word in the string with an odd number of characters).
Let input be your input string. Then:
String[] words = input.split(" ");
Related
This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
I'm trying to write code that receives a string as input and then counts the number of words within said string, but it returns 1 no matter the input. Surprisingly, pasting the sample code from my textbook (C. Thomas Wu - An Introduction to Object-Oriented Programming) gives the same problem and I can't figure out why.
My code is as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = scanner.next();
char BLANK = ' ';
int index = 0, wordCount = 0;
int numberOfCharacters = sentence.length();
while (index < sentence.length()){
while (index < sentence.length() && sentence.charAt(index) != BLANK){
index++;
}
while (index < sentence.length() && sentence.charAt(index) == BLANK){
index++;
}
wordCount++;
}
System.out.println(wordCount);
}
}
Thanks in advance for any help!
You have used scanner.next() which will capture only the first word of the sentence. It stops where it finds a white space. You need to use scanner.nextLine().
Also, given below is another way of doing it:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
System.out.println("Total no. of words: " + scanner.nextLine().split("\\s+").length);
}
}
A sample run:
Enter a sentence: Ram is a good boy.
Total no. of words: 5
Another sample run:
Enter a sentence: Harry is an intelligent guy.
Total no. of words: 5
In this program, we are splitting the input on space(s) using String::split function, which returns a String[] with the words of the input as its elements, and then we are printing the length of this resulting String[].
Scanner.next returns only a single "word" (for some definition of word), and every time you call it will return the next word in the input.
To get an entire line of text, with multiple words, use nextLine:
String sentence = scanner.nextLine();
Hello you can do this by using sentence.split(' ') and getting the length.
For an example:
String sentence = "I like eating apples everyday";
String[] words = sentence.split(' ');
int wordCount = words.length;
Code to check count number of words in a string:
String sentence = "I'm new user of Java!";
int word_count = 0;
for (int i = 1; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
char ch2 = sentence.charAt(i-1);
if (ch == ' ' && ch2 != ' ')
word_count++;
}
System.out.println("Word count: " + word_count);
out:
Word count: 4
java code at online compilier
You can use regex to count all types of spaces including more than 1 successive space characters, tabs & line returns:
\\s is a regex that matches space characters
.split(): split the string into different strings based on a separator/delimiter which is the \\s+ regex
String sentence = scanner.next();
String[] split= sentence.split("\\s+");
int wordCount = split.length;
System.out.println(wordCount);
public class reverserapp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter a word");
String str = scan.nextLine();
String reverse = "";
for( int i = str.length() - 1; i >= 0; i--)
reverse += str.charAt(i);
if(reverse.equalsIgnoreCase(str))
System.out.println("Palindrome");
else System.out.println("Not Palindrome");
}
}
This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.
So in the end result should be like "dontnod"
Thanks in advance for any help, complete noob at this.
Remove all non-letter characters, then put the resulting String to lower case .
str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();
You can use the replace function from StringUtils.
Example:
StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa
You can define a regex to remove punctuation and space, and perform a String replace on input, e.g.:
String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));
This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.
Question 1:
I am trying to count the frequency of a keyword, my code works except that it also counts
those words that also contain the keyword (for example, if I search "count", words like "account" will also be counted in.) Does someone know how to solve this?
Question 2:
I also wanna count the the number of unique words in a text (which means I count repeated word only once). I don't know how to achieve this either. My code only gives me the number of total words.
Here is my code:
import java.util.Scanner;
public class Text_minining {
/**
* #param args
*/
public static void main(String[] args) {
//Prompt the user for the search word
System.out.print("enter a search word: ");
//Get the user's search word input
Scanner keywordScanner = new Scanner(System.in);
String keyword = keywordScanner.nextLine();
keyword = keyword.toLowerCase();
//Prompt the user for the text
System.out.println("Enter a string of words (words separated by single spaces or tabs): ");
//Get the user's string input
Scanner userInputScanner = new Scanner(System.in);
String userInput = userInputScanner.nextLine();
userInput = userInput.toLowerCase();
int keywordCount = 0, wordCount = 0;
int lastIndex = 0;
while(lastIndex != -1){
lastIndex = userInput.indexOf(keyword,lastIndex);
if(lastIndex != -1){
keywordCount ++;
lastIndex = keyword.length() + lastIndex;
}
}
boolean wasSpace=true;
for (int i = 0; i < userInput.length(); i++)
{
if (userInput.charAt(i) == ' ') {
wasSpace=true;
}
else{
if(wasSpace == true) wordCount++;
wasSpace = false;
}
}
//Print the results to the screen
System.out.println("-------");
System.out.println("Good, \"" + keyword + "\"appears in the text and the word count is " + keywordCount);
System.out.println("The total number of unique words in the text is " + wordCount);
System.exit(0);
}
}
First: userInput.split(keyword).length - 1 will do the trick. Our use regex.
Second:
Set<String> uniqueWords = new HashSet<String>();
for (String word : userInput.split(" ")) {
uniqueWords.add(word);
}
System.out.println("Unique words count " + uniqueWords.size());
Just use string method split.
String words[] = userInput.split(keyword);
and then check and count the keyword...
for ( String w : words) {
// do check
}
Agree. Use split to create the array and then you can use
(new HashSet(Arrays.asList(yourArray))).size();
to find the count
I would suggest you this approach:
Split userInput string by white spaces: userInput.split("\\s+"). You will get an array. See String.split()
For question 1: iterate over the array comparing each string with your keyword. See String.equals() and String.equalsIgnoreCase().
For question 2: add the array to a Set. As this can't contain any duplicate item, its size will give you the answer.
Ok what I'm wanting to do is find out if the length of the word entered is divisible by two or not. If it is I want to take the middle two characters (say it was Game, I'd want 'am') and add it to another word.
import java.util.Scanner;
public class Assign33 {
public static void main(String[] args) {
System.out.println("Enter 3 words(Has to contain 4 letters)");
String word1;
String word2;
String word3;
Scanner in = new Scanner(System.in);
// Reads a single line word
// and stores into word variable
word1 = in.nextLine();
word2 = in.nextLine();
word3 = in.nextLine();
// gets each letter if the word has four letters
//this is the part I want to change
String sub0 = word1.substring(1,3)+word2.substring(1,3)+word3.substring( 1, 3 );
// Prints the new word
System.out.println("Can you pronounce: "+sub0);
}
}
If you want to find out the length of a string use .length().
That should help you figure out where the middle of the word is.
If your input can have more than one word then filter the first word from the
line.
word1 = word1.replaceAll("^\s*(\w+)\s*.*$","$1");
If your input would have only one word then trim it.
word1 = word1.trim();
Find the length.
int length1 = word1.length();
If I understand your question correctly, here is what you can do:
String myWord = "Game";
String trimmedWord = myWord.trim();
int lengthOfWord = trimmedWord.length();
boolean lengthIsDivisibleByTwo = lengthOfWord%2 == 0;
String middleSection = "";
if (lengthIsDivisibleByTwo) {
int middleLetterIndex = lengthOfWord/2;
middleSection = trimmedWord.substring(middleLetterIndex-1, middleLetterIndex+1);
}
Then the "middleSection" variable will hold your "am", or whatever the middle 2 letters are.