I'm trying to write a program where a user would enter a phrase, and the program would count the blank spaces and tell the user how many are there. Using a for loop but i'm stuck, could someone help me out?
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for(ch=phrase.charAt()
// and count the blank spaces
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
The for loop for counting spaces would be written as follows:
for(int i=0; i<phrase.length(); i++) {
if(Character.isWhitespace(phrase.charAt(i))) {
countBlank++;
}
}
It reads as follows: “i is an index, ranging from the index of the first character to the index of the last one. For each character (gotten with phrase.charAt(i)), if it is whitespace (we use the Character.isWhitespace utility function here), then increment the countBlank variable.”
Just wondering, couldn't you just split the string entered by blank spaces and take the length of the array subtracted by 1?
In C# it would be as trivial as
string x = "Hello Bob Man";
int spaces = x.Split(' ').Length - 1;
Pretty sure java has a split? Works even if you have two contiguous spaces.
You have probably problem with that for each loop
char[] chars = phrase.toCharArray(); Change string into array of chars.
for(char c : phrase.toCharArray()) { //For each char in array
if(Character.isWhitespace(c) { //Check is white space.
countBlank++; //Increment counter by one.
}
}
or
for(int i =0; i <phrase.lenght(); i++) {
if(Character.isWhitespace(phrase.charAt(i)) { //Check is the character on position i in phrase is a white space.
countBlank++; //Increment counter by one.
}
}
You have to complete for cycle and count spaces
//replace this lines
for(ch=phrase.charAt()
// and count the blank spaces
//to this lines
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
}
Loop through the characters in the string.
Check if the character is a space (char value = 32 or ch == ' ')
If space, add to countBlank, otherwise continue
Display the results.
You might look at the String and Character classes in the Java documentation for assistance.
I'm not very familiar with java, but if you can access each character in the string.
You could write something like this.
int nChars = phrase.length();
for (int i = 0; i < nChars; i++) {
if (phrase.charAt(i) == ' ') {
countBlank++;
}
}
This is at the following Java Tutorials
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
String[] items = p.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
OUTPUT:
one
two
three
four
five
The regex for whitespace is \s
Hope that helps.
Related
Hi guys i made this
import java.util.Scanner;
//Creates a class
public class codeString {
public static void main(String[] arg) { //creates scanne/giving name
Scanner ImBack = new Scanner(System.in);
//print out "enter any String" and asks to put in data
System.out.print("Enter any String :");
String Word = ImBack.nextLine();
int ascii = (int) Word.charAt(0);
System.out.println(ascii);
System.out.println((char) Word.charAt(0));
}
}
But when i run it it converts only 1 letter, I know that i have to make a loop..
so then i went on google and made this
for (Word.charAt(0); Word = int; Word = Word) {
System.out.println("" + Word);
}
printing lots of errors, one of them was asking for toString, but it worked with out the toString for the one letter, so i know i did loop wrong 100%, could anyone help? and will i need a
length
in there?
You need something like this :
for (int i = 0; i < Word.length(); i++) {
System.out.println(Word.charAt(i));
}
Word.length() return to you the length of your word or text
Word.charAt(i) to get character by character
You can learn also the Oracle tutorials about Arrays and do...while Loop
So I've been making a small piece of code in Java that takes input from the user counts the uppercase, lowercase and other parts (such as spaces, numbers, even brackets) and then returns how much there are of each to the user.
The problem I have is that say I put in "Hello There" it stops counting spots after the "o" in Hello. So after the first word.
Code
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = 0;
int lower = 0;
int other = -1;
int total = 0;
String input;
System.out.println("Enter the phrase: ");
input = scan.next();
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) upper++;
if (Character.isLowerCase(input.charAt(i))) lower++;
else other++;
total = upper + lower + other;
}
System.out.println("The total number of letters is " + total);
System.out.println("The number of upper case letters is " + upper);
System.out.println("The number of lower case letters is " + lower);
System.out.println("The number of other letters is " + other);
}
}
Scanner#next:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
The problem is that next doesn't see the word "There" since "Hello World" is not a complete token.
Change next to nextLine.
Advice: Use the debugger and you'll find the problem quickly, and when you have doubts refer to the docs, they're there for you.
Problem is that next() only returns the line before a space but nextLine() will read the whole line.
So Change
scan.next();
to
scan.nextLine();
You need to change next() to nextLine()- it will read all the line
As others have said. You should change from scn.next to scn.nextLine(). But why? This is because scn.next() only read until it encounters a space, and it stops reading. So whatever input after a space will not be read.
scn.nextLine() reads until a newline (i.e. enter) is encountered.
You can try with regular expressions:
public static void main(String[] args) {
String input = "Hello There";
int lowerCase = countMatches(Pattern.compile("[a-z]+"), input);
int upperCase = countMatches(Pattern.compile("[A-Z]+"), input);
int other = input.length() - lowerCase - upperCase;
System.out.printf("lowerCase:%s, upperCase:%s, other:%s%n", lowerCase, upperCase, other);
}
private static int countMatches(Pattern pattern, String input) {
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please insert a word.: ");
String word = (" ");
while (in.hasNextLine()){
System.out.println(in.next().charAt(0));
}
}
}
I am attempting to read each letter from the input and seperate it with a space.
For example: Input is Yes.
The output should be
Y
E
S
.
I do not understand how to make the char go to the next letter in the input. Can anyone help?
You've got a bug in 'hasNextLine' your loop -- an extraneous ; semicolon before the loop body. The semicolon (do nothing) will be looped, then the body will be executed once.
Once you fix that, you need to loop over the characters in the word. Inside the 'hasNextLine' loop:
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
// print the character here.. followed by a newline.
}
You could do
while (in.hasNext()) {
String word = in.next();
for (char c: word.toCharArray()) {
System.out.println(c);
}
}
I need some help with a palindrome detector that I am doing for homework. I need the user to enter a statement, so more then one word, and the program needs to detect which words are a palindrome and which ones are not. However, something in my loop is going wrong in that, it will only detect the first word then blend the others after together. I'm not sure what I'm doing wrong.
import javax.swing.JOptionPane;
public class Main {
static int numpali = 0;
public static void main(String[] args) {
// ask the user to enter a statement
String statement = JOptionPane.showInputDialog("Enter a Statement");
String reverse = "";
// Array to split the sentence
String[] words = statement.split(" ");
// Run a loop to seperate the words in the statement into single Strings
for (String word : words) {
// Print out original word
System.out.println(word + "\n");
int wordlength = word.length();
// send the word to lowercase so capitals are negligible
String wordlower = word.toLowerCase();
// Run a loop that reverses each individual word to see if its a
// palindrome
for (int t = wordlength; t > 0; t--) {
reverse += wordlower.substring(t - 1, wordlength);
wordlength--;
}
System.out.println(reverse);
// show a message if the word is a palindrome or not, and add 1 to the
// total number of palindromes
if (reverse.equals(wordlower)) {
JOptionPane.showMessageDialog(null, word + " is a Palindrome!");
numpali = numpali + 1;
}
word = "";
}
System.out.println("Number of Palindromes:" + "\n" + numpali);
}
}
I've tried to explain what its doing the best I can inside the program.
You never reset the "reverse" value inside your loop. So after the first word your just adding more characters to "reverse" every iteration.
Put
reverse = "";
inside your main for loop
Reset the value of reverse to reverse=""; just like what you have done word="";
I need to count the number of words and I am assuming the correct way to do it is by calculating the number of times that the previous character in a string is not a letter (ie other characters) because this is to assume that there would be colons,spaces,tabs, and other signs in the string.
So at first my idea was to loop through each character and count how many times that you will not get a letter of an alphabet
for(int i = 0; i < string.length(); i++) {
for(int j = 0; i < alphabets.length(); j++) {
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
}
}
However I will always get an array out of bounds because of this. So, I kinda need a little help or another way that can actually be more efficient.
I thought of using Matches to only [a-zA-z] but I'm not sure how do I handle a char to be comparable to a string in counting how many times it occurs.
Thank you
You can use String.split() to convert the string into an array, with one word in each element. The number of words is given by the length of the array:
int words = myString.split("\s+").length;
Your suggestion to use a regex like "[A-Za-z]" would work fine. In a split command, you'd split on the inverse, like:
String[] words = "Example test: one, two, three".split("[^A-Za-z]+");
EDIT: If you're just looking for raw speed, this'll do the job more quickly.
public static int countWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}
This problem is slightly more complicated than your algorithm allows.
What if there are two or more spaces in a row?
What if the string starts or ends with whitespace (or non-word characters)?
This looks like homework, so I don't want to provide any code. I suggest an alternative approach which is simpler to think about.
Walk through the characters in the string, one by one.
Do something to remember if you are currently scanning a word or if you are not currently scanning a word.
Do something to determine when you enter or leave a word, and increment your counter accordingly.
The reason you are getting an IndexOutOfBoundsException is probably because when i is 0 your inner loop will have string.charAt(i-1) which will throw an exception since 0-1 is -1. If you fix that your method might work, although you can use more efficient techniques.
Addressing the code directly, your first loop has i=0 as the first value of i, but then you ask for
string.charAt(i-1) = string.charAt(-1),
which is where your array-out-of-bounds is coming from.
The second loop has another problem:
for(int j = 0; i < alphabets.length(); j++) {
You may also want to consider apostrophes as parts of words as well.
Use just like this
String s = "I am Juyel Rana, from Bangladesh";
int count = s.split(" ").length;
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
You are incrementing the counter if the character is some alphabet character. You should increment it if it is no alphabet character.
The following program will count the number of words in a sentence. In this program, we are counting alphabets just after space. The alphabet can be of lower case or upper case. We are inserting a space at the beginning since people don't start a sentence with space. We also need to take care that any special character or number should not be counted as a word.
`import java.util.Scanner;
public class WordSent {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter the sentence");
String str=in.nextLine();
String space=" ";
String spaceword=space.concat(str);
int count=0;
for(int i=0; i<spaceword.length()-1;i++)
{
for (int k=0; k<=25; k++)
{
if(spaceword.charAt(i)==' '&& (spaceword.charAt(i+1)==((char)(65+k)) || spaceword.charAt(i+1)==((char)(97+k))))
{
count++;
}
}
}
System.out.println("Total number of words in a sentence are" +" : "+ count);
}
}`