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());
Related
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 have been asked to created a program that asks the user for two inputs, both of which have to be stored as strings. The first input can be one or multiple words, and the second input has to be one sole character. After the user enters both inputs the program should count how many times, if any, the sole charter appears in the first string. Once the iteration through the first string is done the program should then output the number of instances of the second string. Example:
"There is 1 occurrence(s) of 'e' in test."
The program must use the a while loop and string values. This is the solution I have as of right now following the parameters established by the professor
public static void main(String[] args) {
String inputEntry; // User's word(s)
String inputCharacter; // User's sole character
String charCapture; // Used to create subtrings of char
int i = 0; // Counter for while loop
int charCount = 0; // Counter for veryfiying how many times char is in string
int charCountDisplay = 0; // Displays instances of char in string
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
inputCharacter = scan.nextLine();
if (inputCharacter.length() > 1 || inputCharacter.length() < 1) // if user is not in compliance
{
System.out.print("Please enter one character. Try again.");
return;
}
else if (inputCharacter.length() == 1) // if user is in compliance
{
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
System.out.print("There is " + charCountDisplay +
" occurrence(s) of " + inputCharacter + " in the test.");
}
}
This iteration has a bug. Instead of counting all the instances of the inputCharacter variable it only counts up to one, regardless of how many instances appear on the string. I know the problem is in this part of the code:
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
I just can't quiet pin down what I'm doing wrong. It seems to me that the charCountDisplay variable reverts to zero after each iteration. Isn't that supposed to be avoided by declaring the variable at the very beginning?... I'm one confused fellow.
This is wrong
charCapture = inputEntry.substring(charCount);
does not return one char
try using inputEntry.charAt(charCount)
Another hint is to define your variables close to where you use them rather than at the top of your method like:
String inputEntry;
inputEntry = scan.nextLine();
Even better would be to do inline
String inputEntry = scan.nextLine();
It will make your code a lot more concise and readable.
A more concise way to do your code is:
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
String inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
String inputCharacter = scan.nextLine();
// validate
// then
int len = inputEntry.length();
inputEntry = inputEntry.replace(inputCharacter, "");
int newlen = inputEntry.length();
System.out.format("There is %d occurrence(s) of %s in the test.%n",
len - newlen, inputCharacter);
output
Enter some words here: scarywombat writes code
Enter a character here: o
There is 2 occurrence(s) of o in the test.
Here is a complete MVCE:
package com.example.countcharacters;
/**
* EXAMPLE OUTPUT:
* Enter some words here:
* How now brown cow
* Enter a character here:
* abc
* Please enter one character. Try again.
* Enter a character here:
* o
* There are 4 occurrence(s) of o in the text How now brown cow.
*/
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Captures word(s)
String inputEntry;
System.out.println("Enter some words here: ");
inputEntry = scan.nextLine();
// Captures char
char inputCharacter;
while (true) {
System.out.println("Enter a character here: ");
String line = scan.nextLine();
if (line.length() == 1) {
inputCharacter = line.charAt(0);
break;
} else {
// if user is not in compliance
System.out.println("Please enter one character. Try again.");
}
}
// iterates through word(s)
int charCountDisplay = 0;
int i = 0;
while(i < inputEntry.length()) {
char c = inputEntry.charAt(i++);
if (c == inputCharacter) {
++charCountDisplay;
}
}
// Print results
System.out.print("There are " + charCountDisplay +
" occurrence(s) of " + inputCharacter +
" in the text " + inputEntry + ".");
}
}
NOTES:
You can use "char" and "String.charAt()" to simplify your code.
In general, it's preferable to declare variables close to where you use them (rather than at the top).
You can put your test for "one character only" in its own loop.
'Hope that helps!
inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() will give you the number of occurrences of a character in the string.
String inputEntry = "text";
char inputCharacter = 'x';
System.out.print("There is " + inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() + " occurrence(s) of " + inputCharacter + " in the text " + inputEntry + ".");
Thanks for checking out my question.
Here the user enter the string in the format: "xD xS xP xH". The program takes the string, splits it on the space bar, then uses regex to parse the string. There is an issue with my "final string regex" and I am not sure where.
final String regex = "([0-9]+)[D|d]| ([0-9]+)[S|s]| ([0-9]+)[P|p]| ([0-9]+)[H|h]";
Lastly, the loop prints out only the value for D so I suspect it reaches an error moving to match S or s.
public class parseStack
{
public parseStack()
{
System.out.print('\u000c');
String CurrencyFormat = "xD xS xP xH";
System.out.println("Please enter currency in the following format: \""+CurrencyFormat+"\" where x is any integer");
Scanner scan = new Scanner(System.in);
String currencyIn = scan.nextLine();
currencyFinal = currencyIn.toUpperCase();
System.out.println("This is the currency you entered: "+currencyFinal);
String[] tokens = currencyFinal.split(" ");
final String input = tokens[0];
final String regex = "([0-9]+)[D|d]| ([0-9]+)[S|s]| ([0-9]+)[P|p]| ([0-9]+)[H|h]";
if (input.matches(regex) == false) {
throw new IllegalArgumentException("Input is malformed.");
}
long[] values = Arrays.stream(input.replaceAll(regex, "$1 $2 $3 $4").split(" "))
.mapToLong(Long::parseLong)
.toArray();
for (int i=0; i<values.length; i++)
{
System.out.println("value of i: "+i+ " |" +values[i]+ "|");
}
//pause to print
System.out.println("Please press enter to continue . . . ");
Scanner itScan = new Scanner(System.in);
String nextIt = itScan.nextLine();
}
}
Your regular expression should be [\d]+[DdSsPpHh].
The problem you are having is you split the string into chunks, then you match chunks with a RegEx that matches the original string that you have split.
HOWEVER this answer only addresses a problem in your code. Your routine doesn't seem to cater your expectation. And your expectation is not clear at all.
EDIT
Added the multidigit requirement.
Your regex can be simplified somewhat.
"(?i)(\d+d) (\d+s) (\d+p) (\d+h)"
will do a case-insensitive match against multiple digits ( \d+ )
This can be further simplified into
"(?i)(\d+[dsph])"
which will iteratively match the various groups in your currency string.
First of all your regex looks a bit to complex. You input format is "xD xS xP xH" also you are converting the input to uppercase currencyIn = currencyIn.toUpperCase(); but this isn't the problem.
The problem is
String[] tokens = currencyIn.split(" ");
final String input = tokens[0];
You are splitting the input and only use the first part which would be "xD"
The fixed code would look like:
String currencyIn = scan.nextLine();
currencyIn = currencyIn.toUpperCase();
System.out.println("This is the currency you entered: "+currencyIn);
final String regex = "([0-9]+)D ([0-9]+)S ([0-9]+)P ([0-9]+)H";
if (!currencyIn.matches(regex)) {
throw new IllegalArgumentException("Input is malformed.");
}
long[] values = Arrays.stream(currencyIn.replaceAll(regex, "$1 $2 $3 $4").split(" "))
.mapToLong(Long::parseLong)
.toArray();
for (int i=0; i<values.length; i++) {
System.out.println("value of i: "+i+ " |" +values[i]+ "|");
}
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++;
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");
}
}
}