Count words in a given String [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have two approach to determine number of words in String, But the result is 1 forever!
public static void main(String[] args) {
System.out.println("Enter your String:");
String string = in.next();
System.out.println("Number of Words are:" + countWords(string));
System.out.println("Number of Words are:" + countWords2(string));
}
public static int countWords(String str) {
String[] splited2 = str.split(" ");
return splited2.length;
}
public static int countWords2(String str) {
String trimed = str.trim();
return trimed.split("\\s+").length;
}
Why?

Scanner#next() method, which is what I assume you are using, reads the next token, and by default it doesn't consider whitespaces as a part of token. So, it really reads the input till it finds the first whitespace.
So, your input contains just a single word, and hence the result. Try using Scanner#nextLine() method, and you will get the expected result.

Replace in.next() by scanner.nextLine() because next() will give you the next token not all the line
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:");
String sentence = scanner.nextLine();
System.out.println("Number of Words are:" + countWords(sentence));
Or you can use BufferedReader as it is faster in reading whole line
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String sentence = br.readLine();
System.out.println("Number of Words are:" + countWords(sentence));

I would suggest building a function like this:
public static int getWordCount(String string){
int counter = 0;
boolean wordFound = false;
int endOfLineIndex = s.length() - 1;
for (int i = 0; i < endOfLineIndex; i++) {
if (Character.isLetter(s.charAt(i)) == true)) {
wordFound = true;
} else if (Character.isLetter(string.charAt(i)) == false && wordFound == true) {
counter++;
wordFound = false;
} else if (Character.isLetter(string.charAt(i))) {
counter++;
}
}
return counter;
}
Hope I helped!

Related

Check if String contain only 2 numbers separated by 1 comma in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I need to validate the lines of an input. But each line can only contain 2 numbers separated by 1 comma. Example of format:
1,4
2,7
8,9
Also the first number must be under a certain max (my program checks the max value possible by a id.size() method, it gives the size of a list and that must be the maximum number possible for the first number of the string).
Second number can be any value.
You can use regular expressions to validate that you have two numbers separated by a comma, if you are only working with integers.
if(str.matches("-?[0-9]+,-?[0-9]+")){
//valid
} else {
//invalid
}
After that, you can use String#split along with Integer.parseInt to get the two numbers.
final String[] parts = str.split(",");
final int num1 = Integer.parseInt(parts[0]);
final int num2 = Integer.parseInt(parts[1]);
if(num1 < MAX_VALUE_FOR_FIRST_NUM){
//valid
} else {
//invalid; display error message
}
Use this for getting both numbers (s is input string):
int first=Integer.parseInt(s.split(",")[0].trim().replace("(", ""));
int second=Integer.parseInt(s.split(",")[1].trim().replace(")", ""));
This will get you number and get rid of ( and ). You should use this for each line that you enter.
For checking did input has more numbers use this:
if(s.split(",").length>2){
//show some error
}
After this you only need to check numbers for min and max value for them.
First of all, you want to check if the line you have contains 2 numbers and one comma, and then you have to check if the two substrings that the comma makes are digits. So the code you want is the following.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String: ");
String line = br.readLine();
System.out.println(line);
int max_number = 100;
int firstNumber = 0, secondNumber = 0;
if (line.contains(",")) {
if(isNumeric(line.substring(0,line.indexOf(","))) && isNumeric(line.substring(line.indexOf(",")+1))){
firstNumber = Integer.parseInt(line.substring(0,line.indexOf(",")));
secondNumber = Integer.parseInt(line.substring(line.indexOf(",")+1));
}
}
if(firstNumber <= max_number){
System.out.println("FirstNumber: " + firstNumber + " SecondNumber: " + secondNumber);
}
}
public static boolean isNumeric(String str) {
if (str == null) {
return false;
}
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
You can extract the two numbers using Regular Expression and then check the max condition for the number.
String regex = "^(-?\\d+),(-?\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input); // input as 1,4
if (matcher.find()) {
int num1 = matcher.group(1));
int num2 = matcher.group(2));
if (num1 == id.size()) {
// some logic
}
// some more logic
}

Having a hard time doing this Palindrome on Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm having a hard time learning java and I was hoping to get some type of help on doing this. I'm trying to get the user to input a word and have the system check to see if its a palindrome. I've taken some code from others to get some help but I'm getting stuck.
import java.util.Scanner;
class PalidromeTester
{
public static boolean isPalindrome (String[] word) {
for (int i=0; i< word.length; i++) {
if (!word[i].equals( word[word.length-1-i])){
return false;
}
}
return true;
// read word
public static String readWord(Scanner input){
String word = input.nextLine();
word = word.toLowerCase();
return word;
}
// display results to the screen
public static void displayResults(boolean result){
// display the results
String msg = "\nThat string ";
msg += (result == true) ? " IS " : " is NOT ";
msg += " a palindrome.\n";
System.out.println(msg);
}
// main function
public static void main(String[] args){
// input scanner
System.out.print('\u000C');
System.out.println("Enter the word: ");
Scanner input = new Scanner(System.in);
PalidromeTester.readWord(input);
}
}
Assuming your need, I think this is what you need. I have commented the changes done in the code itself to point out to you why the changes were done in the first place. Also remember there are multiple ways to approach a problem, this is merely just one of those possibilities. Feel free to innovate and add your own technique for solving this.
import java.util.Scanner;
public class Palindrome { //<-- added public to the class otherwise main method won't be called
public static boolean isPalindrome(String word) { //<--changed the String[] to String
for (int i = 0; i < word.length(); i++) {
if (!(word.charAt(i) == word.charAt(word.length() - 1 - i))) { //Since [] will not work on Strings, using charAt() to do the same thing
return false;
}
}
return true;
}
// read word
public static String readWord(Scanner input) {
String word = input.nextLine();
word = word.toLowerCase();
return word;
}
// display results to the screen
public static void displayResults(boolean result) {
// display the results
String msg = "\nThat string ";
msg += (result == true) ? " IS " : " is NOT ";
msg += " a palindrome.\n";
System.out.println(msg);
}
// main function
public static void main(String[] args) {
// input scanner
System.out.print('\u000C');
System.out.println("Enter the word: ");
String s = readWord(new Scanner(System.in)); //Added a call to the readWord method and also passed a Scanner reference to the method and
//storing the read word in String s
boolean result = isPalindrome(s); //Added a call to the palindrome method and also passing the read string s to the method to find whether
//it is palindrome or not and storing the method return value in boolean result variable
displayResults(result); //Finally calling the displayResults with the result we got from isPalindrome() to display the appropriate message
}
}

how to make my program check if its a palindrome by ignoring non-alpha characters and white spaces [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi this code currently checks if it is a palindrome if there all the letters are same capitalization and if there is no spaces. I am trying to make it so it ignores non-alpha and white spaces.
import java.util.*;
public class PalindromeTester
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
After you set your variable "original" to the next line of text, you can call the replaceAll() string method to strip away any unwanted characters with a specifier parameter. Also, you can call toLowerCase() to get all lower case strings.
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
original = original.replaceAll("[^a-zA-Z]","").toLowerCase();
replaceAll() uses a regular expression to search for the specified text and replaces it with the second parameter value.
Here's a quick example for the palindrome "racecar":
String original = "rA89293cEC#Ar";
original = original.replaceAll("[^a-zA-Z]","").toLowerCase();
System.out.println(original);
Can also be done without replacing Chars (and copying the String):
public boolean isPalindrome(String s) {
int start = 0;
int end = s.length()-1;
while(!s.isEmpty() && Character.isSpaceChar(start))
{
start++;
}
if ( s.isEmpty())
return true;
while (start < end )
{
while( ( start < end) && !Character.isLetterOrDigit(s.charAt(start)))
{
start++;
}
while( ( start < end) && !Character.isLetterOrDigit(s.charAt(end)))
{
end--;
}
if ( start >= end )
return true;
if ( Character.toUpperCase(s.charAt(start)) != Character.toUpperCase(s.charAt(end)))
return false;
start++;end--;
}
return true;
}

How do you check if a string is a palindrome in java?

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}
Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).
Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.
This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.
Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.

Scanner only reading first set of input

This is a code I have developed to separate inputs by the block (when a space is reached):
import java.util.Scanner;
public class Single {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Three Numbers:");
String numbers = in.next();
int length = numbers.length();
System.out.println(length);
int sub = length - length;
System.out.println(sub);
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
}
public static double getNumber(String numbers, int length, int sub){
boolean gotNumber = false;
String currentString = null;
while (gotNumber == false){
if (numbers.substring(sub, sub + 1) == " "){
sub = sub + 1;
gotNumber = true;
} else {
currentString = currentString + numbers.substring(sub, sub);
sub = sub + 1;
}
}
return Double.parseDouble(currentString);
}
}
However, it only reads the first set for the string, and ignores the rest.
How can I fix this?
The problem is here. You should replace this line
String numbers = in.next();
with this line
String numbers = in.nextLine();
because, next() can read the input only till the first space while nextLine() can read input till the newline character. For more info check this link.
If I understand the question correctly, you are only calling in.next() once. If you want to have it process the input over and over again you want a loop until you don't have any more input.
while (in.hasNext()) {
//do number processing in here
}
Hope this helps!

Categories