I'm trying to count the number of non-blank characters in a string.
It works fine when there are no leading blank spaces, but when I add 3 spaces in from, it doubles the number of non-blank characters.
This is my code:
import java.io.*;
import java.util.*;
public class countCharacters
{
public static void main(String[] args) throws Exception
{
String str1;
int count;
count = 0;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
while(str1.length() > 0)
{
System.out.println("The String ''" + str1 + "''");
System.out.println("has " + str1.length() + " Characters, including all blanks.");
for(int i=0; i < str1.length(); ++i)
if(str1.charAt(i) !=' ')
count++;
str1 = str1.trim();
System.out.println("and " + str1.length() + " Characters, trimmed of leading and trailing blanks.");
System.out.println("and " + count + " non-blank characters.");
System.out.println("");
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
}
System.out.println("Program complete.");
}
}
Are you sure that it doubles the count every time? Maybe this only happens on the second time through the main loop?
You should be resetting count when you enter a new string. Otherwise, you're just adding to the count from the previous time through the main loop. Add a line like count = 0; before the System.out.print("Enter a string: "); at the bottom of the main loop, or declare and initialise count inside the loop, rather than before the loop.
A much cleaner way to do this would be to just make a copy without any spaces and compare the lengths:
String str1 = " the quick brown fox ";
String spaceless = str1.replace(" ", "");
System.out.println("Number of spaces: "+(str1.length() - spaceless.length()));
You could simply do
String temp = str1.replaceAll("\\s+","");
temp.length() will give you the answer.
You can get rid of temp variable if modifying str1 is an option
Have you tried using the static method:
Character.isWhitespace(char ch);
For example,
if(!Character.isWhitespace(str1.charAt(i)))
count++;
Related
The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}
The Java task is to have the user type a sentence/phrase and then print out how many characters the sentence has. My .length() method is only counting the first word and space as characters. I've read previous questions and answers involving nextLine() but if I use that instead of next() it only lets the user type it's question and waits, doesn't print anything else immediately anymore. I'm brand new to Java and I think this can be fixed with a delimiter but I'm not sure how or what I'm missing. TIA!!
Update: Here's my code.
import java.util.Scanner;
class StringStuff{
public static void main( String [] args){
Scanner keyboard = new Scanner(System.in);
int number;
System.out.print("Welcome! Please enter a phrase or sentence: ");
System.out.println();
String sentence = keyboard.next();
System.out.println();
int sentenceLength = keyboard.next().length();
System.out.println("Your sentence has " + sentenceLength + " characters.");
System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");
}
}
when I type "Hello world." as the sentence it prints:
Your sentence has 6 characters.
The first character of your sentence is H.
The index of the first space is -1.
keyboard.next call is waiting for user input. You're calling it twice, so your program expects the user to enter two words.
So, when you type in "Hello world." it reads "Hello" and "world." separately:
//Here, the sentence is "Hello"
String sentence = keyboard.next();
System.out.println();
//Here, keyboard.next() returns "World."
int sentenceLength = keyboard.next().length();
And when you use nextLine your code is waiting for the user to enter two lines.
To fix this you need to:
Read the whole line with nextLine.
Use sentence instead of requesting user input the second time.
Something like this should work:
String sentence = keyboard.nextLine();
System.out.println();
int sentenceLength = sentence.length();
import java.util.Scanner;
public Stringcount
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the sentence:");
String str=s.nextLine();
int count = 0;
System.out.println("The entered string is: "+str);
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) != ' ')
count++;
}
System.out.println("Total number of characters in the string: " + count);
System.out.println("The first character of your sentence is " + str.substring(0,1) + ".");
System.out.println("The index of the first space is " + str.indexOf(" ") + ".");
}
}
I am not getting the correct output... Any help with this function in JAVA?
The expected Output should be:
The total sum of the word lengths entered was: 9 (depending on user
input) The longest word was: Oranges, with length 7 The
shortest word was: Ox, with length 2
Note: No Array is to be used. Thanks
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
int count = 0;
while (!(line = input.nextLine()).isEmpty())
{
System.out.println("Enter word: ");
count++;
} System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " input + " with length " + input.length);
System.out.println("The shortest word was: " input + " with length " + input.length);
}
}
In your while block (the lines between the {} pair after while), you have the line that someone entered. It is of type String.
If you look up the String class in Java, you will find that it has a method for length(), so that's how you get the length of the line (line.length() returns an int length).
To track the longest line, you need a variable declared up where count is declared that is going to store the longest line entered. For each line, compare the length of the line you have with the longest length you've encountered so far; if the current one is the longest, then store its length (and its value, if you'll need that also, in a variable declared next to count and the longest line value). The reason I'm pointing out where to put them is that they need to be declared outside the while loop so that you can refer to them after the loop has finished.
Shortest is done the same way, with different variables.
Good luck -- post more questions if you need to! I've tried to give you enough info that you can write the actual code yourself, but it's hard to gauge just how much that is.
it would be something like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
int count = 0;
String shortest = String.format("%0" + 10000 + "d", 0).replace("0", "x");
String longest = "";
while (!(line = input.nextLine()).isEmpty()) {
System.out.println("Enter word: ");
count += line.length();
if (line.length() > longest.length())
longest = line;
if(line.length() < shortest.length())
shortest = line;
}
System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " + longest + " with length " + longest.length());
System.out.println("The shortest word was: " + shortest + " with length " + shortest.length());
}
}
Set the smallest and largest word sizes based on the first word encountered. Then keep comparing values to determine the sizes. This also handles case if words are the same size.
public static void main(String[] args) {
String line;
Scanner input = new Scanner(System.in);
int count = 0;
int largestSize = 0;
int smallestSize = 0;
String longestWord = "";
String shortestWord = "";
while (!(line = input.nextLine()).isEmpty()) {
System.out.println("Enter word: ");
count++;
//Initialize sizes and words on first round.
if (count == 1) {
smallestSize = largestSize;
shortestWord = line;
}
//Do the comparisons.
if (largestSize <= line.length()) {
largestSize = line.length();
longestWord = line;
} else if (smallestSize > line.length()) {
smallestSize = line.length();
shortestWord = line;
}
}
System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " + longestWord + " with length " + longestWord.length());
System.out.println("The shortest word was: " + shortestWord + " with length " + shortestWord.length());
}
The user will input a string and the program should recognize the integers.
If the user inputs Hello12 3 it should output:
The integral numbers are:
id1 12
id2 3
but in my code, it outputs
The integral numbers are:
int1
int2
int3
int4
int5
int6 12
int7 3
How should i fix it?
My code:
import java.util.*;
public class LexicalAnalyzer {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String str;
int j=0;
System.out.println("Lexical Analyzer for Algebraic Expressions\n");
System.out.print("Enter the String: ");
str = input.nextLine();
System.out.println("String length is: "+str.length());
System.out.println("\nThe integral numbers are: \n");
String intNum = str.replaceAll("[^0-9]", " ");
String[] intSplit = intNum.split(" ");
for(int i=0;i<intSplit.length;i++){
System.out.println("int"+(i+1)+" "+intSplit[i]);
}
}
}
You are replacing every non-numeric character with a space. You need to replace it with "" so that there are no extra spaces. Then you split on space and you will get the desired result. Also, you need to preserve the spaces between numbers by using [^0-9\\s] so that the spaces are not replaced by "" (empty String).
Replace:
String intNum = str.replaceAll("[^0-9]", " ");
with:
String intNum = str.replaceAll("[^0-9\\s]", "");
Instead of wasting time (CPU resources) on modifying the string, just search for what you want:
Matcher m = Pattern.compile("[0-9]+").matcher(str);
for (int i = 1; m.find(); i++)
System.out.println("int" + i + " " + m.group());
I am a student at the moment so I am still learning. I picked up VB pretty quick and it was simple Java on the other hand I am pretty confused on.
The Assignment I have been given this time has me confused "Write a method to determine the number of positions that two strings differ by. For Example,"Peace" and "Piece" differ in two positions. The method is declared int compare(String word1, String word2); if the strings are identical, the method returns 0. It returns -1 if the two strings have different lengths."
Additional "Write a main method to test the method. The main method should tell how many, positions the strings differ, or that they are identical, or if they are different lengths, state the lengths. Get the strings from the console.
So far this is where I am at and I am looking for someone to help break this down in I DUMDUM terms if they can I don't need a solution only help understanding it.
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.print("Enter a word");
String word1;
String word2;
word1 = scanner.next();
System.out.print("Enter another word");
word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x >= length; x = x+1) {
if (word1.charAt(x) == word2.charAt(x)) {
count = count + 1;
System.out.print (count);
}
}
}
}
Additional Question
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int word1Length = word1.length();
int word2Length = word2.length();
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
for(int x = 0; x < word1Length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}}}
System.out.println (count+" different chars");
}
After implementing the knowledge Iv gained from your responses I have ran in to a problem with the last line:
System.out.println (count+" different chars");
It says Error expected however it worked before I added the next part of my assignment which was this:
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
for(int x = 0; x >= length; x = x+1) {
You probably mean
for(int x = 0; x < length; x = x+1) {
Shifting around some code, adding some line breaks and making 2 small tweaks to the logic produces a program that is closer to what you are trying to build.
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x < length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}
}
System.out.println (count+" different chars");
}
}
It looks like in addition to the for loop that #LouisWasserman pointed out you had code that was trying to find characters that are the same.
What you need is a loop which compares the two strings and counts the places where they are not equal.
Your logic counts the number of places where the two characters are the same. You are also printing the count each time the two characters are equal.
What it sounds like you need is a loop that iterates over the characters in the two strings comparing each character and incrementing the count of mis-matched or different characters. Then after getting a count of different characters by comparing all of the characters, you would print out the count of different characters.
So the basics would be: (1) read each of the strings, (2) check that the lengths are the same, (3) if same length then loop over the string comparing each character and incrementing the count of mis-matched characters each time there is a difference, (4) print out the count. If the string lengths are different then just set the count to negative one (-1) and do not bother to compare the two strings.
What would be kind of neat to do is to create a string of underscores and asterisk, in which each matching character position is represented by an underscore and each mis-matching character position is represented by an asterisk or perhaps the string would contain all of the matching characters and the mis-matching characters would be replaced by an asterisk.
Edit: adding example program
The example below is an annotated rewrite of your program. One change that I made was to use a function to perform the counting of the non-matching characters. The function, countNonMatchChars () is a static function in order to work around the object oriented nature of Java. This function is a utility type function and not really part of a class. It should be available to anyone who wants to use it.
Also rather than incrementing variables with the syntax of var = var + 1; I instead use the postincrement operator of ++ as in var++;.
package arraysandstrings;
import java.util.Scanner;
public class so_strings_main {
// function to compare two strings and count the number
// of characters that do not match.
//
// this function returns an integer indicating the number
// of characters that did not match or a negative one if the
// strings are not equal in length.
//
// "john" "john" returns 0
// "john1" "john2" returns 1
// "mary1" "john1" returns 4
// "john" "john1" returns -1 (lengths are not equal)
public static int countNonMatchChars (String s1, String s2)
{
// initialize the count to negative one indicating strings unequal in length
// get the lengths of the two strings to see if any comparison is needed
int count = -1;
int word1Length = s1.length();
int word2Length = s2.length();
if (word1Length == word2Length) {
// the lengths of the two strings are equal so we now do our comparison
// we start count off at zero. as we find unmatched characters, we
// will increment our count. if no unmatched characters found then
// we will return a count of zero.
count = 0;
for(int iLoop = 0; iLoop < word1Length; iLoop++) {
if (s1.charAt(iLoop) != s2.charAt(iLoop)) {
// the characters at this position in the string do not match
// increment our count of non-matching characters
count++;
}
}
}
// return the count of non-matching characters we have found.
return count;
}
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Count non-matching characters in two strings.");
System.out.println("Enter first word");
String word1 = scanner.next();
System.out.println("Enter second word");
String word2 = scanner.next();
int count = countNonMatchChars (word1, word2);
if (count < 0) {
System.out.println ("Words are a diffrent length");
System.out.println (" " + word1 + " Has " + word1.length() + " chars");
System.out.println (" " + word2 + " Has " + word2.length() + " chars");
} else {
System.out.println (count + " different chars");
}
}
}