Problems with counting spaces - Java - java

I'm having problems with the code below. It asks for the user to type in a sentence basically.
System.out.println("Enter a string containing spaces: ");
inputString = keyboard.next();
int lengthString = inputString.length();
System.out.println("You entered: " + inputString + "\n" + "The string length is: " + lengthString);
The problem is when it prints the statement, it only prints the first word, then counts the characters contained within the first word. I'm really new to Java, so I was wondering what should I do to make the program count the WHOLE string.

You should use nextLine() method instead of next():
inputString = keyboard.nextLine();
Scanner#next() method reads the next token. Tokens are considered to be separated by a delimiter. And the default delimiter of Scanner is as recognized by Character.isWhitespace.

keyboard.nextLine() will pull in the entire line. next() only gets the next word. next() uses spaces by default to determine word sizes, but you can also set a custom delimiter if you want it to pull in different tokens.

Related

If the user enters a blank space as their input, how would you read that as a " " string?

//Example:
Scanner scanner = new Scanner(System.in);
String character = scanner.next();
//User hits the space bar and hits enter
System.out.println(character);
//character should = " "
scanner.next() gives you the next complete token, which is defined as follows:
A complete token is preceded and followed by input that matches the delimiter pattern.
If you want the space, I'm assuming you want the whole line. You should either tell the scanner to get the entire line or set the delimiter of the scanner to the line break character. See scanner.nextLine() and scanner.useDelimiter().

Regex for java project

How would I do java regex for the following examples each its taken in by scanner as a string and regex can only be set after the scanner has taken in each part so where regex can be set is after the scanner e.g
Scanner scan = new Scanner(System.in);
String veriableName = scan.nextLine();
String studentID = scan.nextLine();
String word = scan.nextLine();
................
//regex can only be set here
String veriableNamePattern = "";
String studentIDPattern="";
String wordPattern="";
.............
if(veriableNamePattern.matches(veriableNamePattern ){
System.out.println(veriableName + " is valid.");
}
else{
System.out.println(studentID + " is valid.");
}
here are the examples I am trying to do:
A variable name composed of some alphabetic character followed by any sequence of letters or numbers.
A student ID number represented by 7 digits that must start with 1 and end with the letter s.
Any four letter word that ends in ‘ed’.
A product code represented by two digits followed by three capital letters.
Find all € values from €100 to €999 at the beginning of a line.
Just.. read through your code, treat it like a term paper, you proofread those too, surely:
You are calling veriableNamePattern.matches(veriableNamePattern) - it won't, of course. You want to match veriableName.
You print studentID + " is valid." in both cases, making it impossible to tell the difference. presumably you want to introduce a not somewhere in that second println lline.
Some examples:
// first letter optionally followed by a letter/number/underscore (\w) group
String variablePattern = "[a-zA-Z]\\w*";
// Sequence of digits starting with 1, followed by 6 digits, ending with 's' or 'S'
String studentIdPattern = "1[0-9]{6,6}s|S";
// Sequence of 2 letters followed by "ed"
String fourEdPattern = "[a-zA-Z]{2,2}ed";

Looped If statements confusion - using scanners to find palindroms, cannot use .reverse for assignment

When I input any sentence, my output returns that any string is a palindrome, and I think that my replaceAll calls aren't working in some cases. This is likely due to error my part, because using the Scanner class in Java is new for me (more used to input from C++ and Python3). I added comments to make it clearer what my intentions were when writing the program.
import java.util.Scanner;
public class PalindromeTest
{
public static void main (String[] args)
{
Scanner stringScan = new Scanner(System.in); //Scanner for strings, avoids reading ints as strings
Scanner intScan = new Scanner(System.in); //Scanner for ints, avoids reading strings as ints
String forwardPal = ""; //Variables for the rest of the program
String reversePal = "";
String trimForward = "";
char tempChar;
int revCount;
int revPalLength;
int quit;
while (true) //Loop to keep the program running, problem is in here
{
System.out.println("Please enter a word or a sentence."); //Prompts user to enter a word or sentence, I assume that the program is counting
forwardPal = stringScan.nextLine();
trimForward = forwardPal.replaceAll(" " , ""); //Trims the forwardPal string of characters that are not letters
trimForward = trimForward.replaceAll("," , "");
trimForward = trimForward.replaceAll("." , "");
trimForward = trimForward.replaceAll("!", "");
trimForward = trimForward.replaceAll(":", "");
trimForward = trimForward.replaceAll(";", "");
revPalLength = trimForward.length() ; //Makes the reverse palindrome length equal to the length of the new trimmed string entered
for (revCount = revPalLength - 1; revCount >= 0; revCount--) //Loop to count the reverse palindrome and add each character to the string reversePal iteratively
{
tempChar = trimForward.charAt(revCount);
reversePal += tempChar;
System.out.println(reversePal);
}
if (trimForward.equalsIgnoreCase(reversePal)) //Makes sure that the palindrome forward is the same as the palindrome backwards
{
System.out.println("Congrats, you have a palindrome"); //Output if the sentence is a palindrome
}
else
{
System.out.println("Sorry, that's not a palindrome"); //Output if the sentence isn't a palindrome
}
System.out.println("Press -1 to quit, any other number to enter another sentence."); //Loops to ask if the user wants to continue
quit = intScan.nextInt(); //Checks if the user input a number
if (quit == -1) //If the user inputs -1, quit the program and close the strings
{
stringScan.close();
intScan.close();
break;
}
}
}
}
Your problem is this line
trimForward = trimForward.replaceAll("." , "");
That function takes the first argument as a regex, and the dot means that it is replacing all characters as a "".
Instead, use
trimForward = trimForward.replace("." , "");
In fact, all your lines should be using #replace instead of #replaceAll as none of them take advantage of regex. Only use those if you plan to take advantage of it.
Or in fact, if you do want to use a regex, this is a nice one which does all of that in one neat line.
trimForward = forwardPal.replaceAll("[ .!;:]" , "");
I hope this was of some help.
The simplest fix is to use replace() instead of replaceAll().
replace() replaces all occurences of the given plain text.
replaceAll() replaces all occurences of the given regex.
Since some of your replacements have special meaning in regex (specifically the dot ., which means any character), you cant use replaceAll() as you are currently (you'd have to escape the dot).
It's common, and quite reasonable, to assume that replace() replaces one occurrence and replaceAll() replaces all occurrences. They are poorly named methods, because they interpret their parameters differently, yet both replace all matches.
As an aside, you may find this briefer solution of interest:
forwardPal = forwardPal.replaceAll("\\W", ""); // remove non-word chars
boolean isPalindrome = new StringBuilder(forwardPal).reverse().toString().equals(forwardPal);

Splitting a comma and space separated input into two words

I am having difficulty splitting a string of user input into two words. The string is in the format "word1, word2", and I am trying to create two separate strings of word1 and word2. Here is my attempt:
System.out.println("Enter the two words separated by a comma, or 'quit':");
Scanner sc = new Scanner(System.in);
String input = sc.next();
while(!input.equals("quit")){
input.replaceAll("\\s+","");
System.out.println(input); //testing
int index1 = input.indexOf(",");
String wordOne = input.substring(0, index1);
String wordTwo = input.substring(index1+1, input.length() );
if(wordOne.length()!=wordTwo.length()){
System.out.println("Sorry, word lengths must match.");
}
System.out.println("Enter the two words separated by a comma, or 'quit':");
input = sc.next();
}
This is the output:
Enter the two words separated by a comma, or 'quit':
leads, golds
leads,
Sorry, word lengths must match.
Enter the two words separated by a comma, or 'quit':
golds
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1911)
at Solver.main(Solver.java:22) //this points to the line "String wordOne = input.substring(0, index1);"
Could someone please tell me where I am going wrong?
Why don't you try:
input.split(",");
This will give you an String array. From JavaDocs.
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Update: Since, you are using sc.next() which will take a single word unless it sees a space at which it will terminate the input. You should instead use sc.nextLine() to keep the complete input as user inputs.
next()
public java.lang.String 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. This method may block while
waiting for input to scan, even if a previous invocation of hasNext
returned true.
nextLine()
public java.lang.String nextLine()
Advances this scanner past the
current line and returns the input that was skipped. This method
returns the rest of the current line, excluding any line separator at
the end. The position is set to the beginning of the next line. Since
this method continues to search through the input looking for a line
separator, it may buffer all of the input searching for the line to
skip if no line separators are present.
The problem is that you are using sc.next() instead of sc.nextLine(). I can see that in your input you are entering "leads, gold" where leads, is followed by a space. In this case sc.next() will return just "leads," and not "leads, gold"

Regex in scanner only finds first match

I have a text file containing a number of articles which I need to parse through.
I need to retrieve every single word in each article, excluding any full stops, commas, etc. The articles are separated by a specific two lines, and I'm trying to use a regex pattern to find these points.
An example of the document is as follows:
.I 1
.W
this is article one.
.I 2
.W
this is article two.
.I 3
.W
this is article three.
The code below seems to find the first occurrence .I 1 and add all subsequent words, but once it gets to the next separator it adds it as a word instead of skipping it.
Scanner scanner = new Scanner(document);
scanner.useDelimiter("[^\\w']+");
String separator;
while (scanner.hasNext()){
separator = scanner.findInLine(Pattern.compile(".I \\d"));
if (separator!= null) {
System.out.println("Found: " + separator);
scanner.nextLine();
scanner.nextLine();
}
list.add(scanner.next());
}
scanner.close();
If possible I'd also like to be able grab the actual article number, which is the number attached to each separator.
What's wrong in my code?
The problem is that since you tell the Scanner to use everything except word characters and ticks as delimiters, the dot in front of I is consumed by scanner.next() each time it is about to come up in your findInLine search.
You can fix this by reading input by line instead of reading it by word, like this:
list.add(scanner.nextLine());
To get article number, parse the delimiter starting at character 3:
int num = Integer.valueOf(separator.substring(3));
Here is a demo that reads from standard input:
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("[^\\w']+");
String separator;
Pattern rx = Pattern.compile(".I \\d");
while (scanner.hasNext()){
separator = scanner.findInLine(rx);
if (separator!= null) {
int num = Integer.valueOf(separator.substring(3));
System.out.println("Found: " + separator+", article number: "+num);
scanner.nextLine();
scanner.nextLine();
}
System.out.println(scanner.nextLine());
}
scanner.close();
Demo.

Categories