I am somewhat lost on what to do.
There are 4 parts.
Prompt the user for a string that contains two strings separated by a comma.
Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.
Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.
Final outcome should print out as follows:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.
Here's my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String lineString = "";
int commaLocation = 0;
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
if (lineString.equals("q")) {
inputDone = true;
}
else {
commaLocation = lineString.indexOf(',');
firstWord = lineString.substring(0, commaLocation);
secondWord = lineString.substring(commaLocation + 1, lineString.length());
System.out.println("First word: " + firstWord);
System.out.println("Second word:" + secondWord);
System.out.println();
System.out.println();
}
}
return;
}
}
Let's have a look at the line:
commaLocation = lineString.indexOf(',');
in case there is no comma, .indexOf() returns -1 - you can take advantage of it and add an if condition right after this line and handle this case as well!
You can use :
if (input.matches("[^,]+,[^,]+")) {//If the input match two strings separated by a comma
//split using this regex \s*,\s* zero or more spaces separated by comman
String[] results = input.split("\\s*,\\s*");
System.out.println("First word: " + results[0]);
System.out.println("Second word: " + results[1]);
} else {
//error, there are no two strings separated by a comma
}
Related
I want to change my strings into array lists in my scanner program. I know that I have to use the .split method, but I am not sure how. I will use this example:
This is a good class with JAVA -> [This, is, a, good, class, with, Java]
This is what I have so far:
import java.util.*;
public class scanner_LAB {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a sentance with the word \"java\" in it: ");
// input and end program
System.out.println();
System.out.println("Done - Press enter key to end program");
String line = input.nextLine();
System.out.println(line);
// length
int length = line.length();
System.out.println("Your sent " + length);
// upper case and lower case
String lowerCase = line.toLowerCase();
System.out.println(lowerCase);
String upperCase = line.toUpperCase();
System.out.println(upperCase);
System.out.println(lowerCase.indexOf("java"));
// java to Java
System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "Java" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// java to JAVA
System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "JAVA" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// string to arrays
}
}
You can use the split function of string to split the string into array.
String[] strArray = line.split(" ");
To answer your question about using the split method, this is the general way to use it
// string to arrays
String[] words = line.split(" ");
for(String word: words)
System.out.println(word);
I ran your code and this works four your intended purpose (I've just commented out some of your code that wasn't related to this question)
import java.util.*;
public class scanner_LAB {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a sentance with the word \"java\" in it: ");
// input and end program
//System.out.println();
//System.out.println("Done - Press enter key to end program");
String line = input.nextLine();
System.out.println(line);
// length
int length = line.length();
System.out.println("Your sent " + length);
// upper case and lower case
String lowerCase = line.toLowerCase();
System.out.println(lowerCase);
String upperCase = line.toUpperCase();
System.out.println(upperCase);
System.out.println(lowerCase.indexOf("java"));
// java to Java
//System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "Java" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// java to JAVA
//System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "JAVA" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// string to arrays
String[] words = line.split(" ");
System.out.println(Arrays.asList(words));
}
}
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 trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];
First off, I am brand new to both Java and to this website. I am going to ask my question as thoroughly as I can. However, please let me know if you think I left something out.
I am working on a school assignment, and I am stuck on the second portion of it. I am able to prompt the user, but can not for the life of me, figure out how to ensure that the input string contains a comma. I did try searching this site, as well as Googling it, and haven't been able to find anything. Perhaps I am not wording the question appropriately.
(1) Prompt the user for a string that contains two strings separated by a comma.
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
So far I have this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter string seperated by a comma: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
// Create new input string stream
inSS = new Scanner(lineString);
// Now process the line
firstWord = inSS.next();
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
if else (lineString != ",") { // This is where I am stuck!
System.out.print("No comma in string");
}
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
I know my "if else" is probably not correct. I just don't know where to begin for this particular command. Unfortunately my eBook chapter did not cover this specifically. Any thoughts would be greatly appreciated. Thank you so much!
I suspect you want to assert if the input contains a comma, and at least one letter either side. For this you need regex:
if (!input.matches("[a-zA-Z]+,[a-zA-Z]+")) {
System.out.print("Input not two comma separated words");
}
Since you are looking for a string with a comma in it and you want to get the string “Before” the comma and the string “After” the comma, then string.split(‘,’) is what you want. Asking if the string “Contains” a comma gives you no information about the string before or after the comma. That’s where string.split() helps. Since you don’t care “Where” the comma is you simply want the string before the comma and the string after the comma. The string.split(‘,’) method will return a string array containing the strings that are separated by commas (in your case) or any character.
Example:
string myString = “firstpart,secondpart”;
… then
string[] splitStringArray = myString.Split(‘,’)
This will return a string array of size 2 where
splitStringArray[0] = “firstpart”
splitStringArray[1] = “secondpart"
with this info you can also tell if the user entered the proper input… i.e…
if the splitStringArray.Length (or Size) = 0, then the user did not input anything, if the splitStringArray.Length (or Size) = 1 then the user input 1 string with no commas… might check for exit here. If the splitStringArray.Length (or Size) = 2 then the user input the string properly. if the splitStringArray.Length (Size) > 2 then the user input a string with more than 1 comma.
I hope that helps in describing how string.split works.
Your code however needs some work… without going into much detail below is a c# console while loop as an example:
inputDone = false;
while (!inputDone)
{
Console.Clear();
Console.WriteLine("Enter string seperated by a comma: ");
lineString = Console.ReadLine();
string[] splitStringArray = lineString.Split(',');
// check for user to quit
if (splitStringArray.Length == 1)
{
if (splitStringArray[0] == "q")
{
inputDone = true;
Console.Clear();
}
else
{
// 1 string that is not "q" with no commas
}
}
if (splitStringArray.Length == 2)
{
// then there are exactly two strings with a comma seperating them
// or you may have ",string" or "string,"
Console.WriteLine("First word: " + splitStringArray[0]);
Console.WriteLine("Second word: " + splitStringArray[1]);
Console.ReadKey();
}
else
{
Console.WriteLine("Input string empty or input string has more than two strings seperated by commas");
Console.ReadKey();
}
}
Hope that helps.
This worked for me:
import java.util.Scanner;
import java.io.IOException;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String nextWord = "";
System.out.println("Enter input string: ");
while (lineString.matches("q") == false) {
lineString = scnr.nextLine();
lineString = lineString.replaceAll(",",", ");
inSS = new Scanner(lineString);
int delimComma = lineString.indexOf(",");
if ((delimComma <= -1) && (lineString.matches("q") == false)) {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
else if ((delimComma <= -1) && (lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2) && (lineString.matches("q") == false)) {
System.out.println("Error: Two words");
System.out.println("Enter input string: ");
}
else if (lineString.matches("q") == false) {
firstWord = inSS.next();
nextWord = inSS.nextLine();
System.out.println("First word: " + firstWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("Second word: " + nextWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("\n");
System.out.println("Enter input string: ");
}
continue;
}
return;
}
}
I am trying to figure out how to place a limit on the amount of characters used in a String but, I can't seem to figure out how to code that if, for example I say 'He' instead of 'Hello' I want my code to show an error because 'He' contains less than 3 characters. Any suggestions?
package trial;
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = input.nextLine();
System.out.println("The Word you have typed is: " + word);
your code is good just let the user keep entering the value until the characters more than 3 so you do that by while loop that check the number of word's characters
package trial;
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word="";
while(word.length()<3){
System.out.println("Enter a word with more or equals to 3 characters: ");
word = input.nextLine();
}
System.out.println("The Word you have typed is: " + word);
If you want to allow only alphanumeric characters you can use a regex with \w and leverage String.matches like:
String word = input.nextLine();
// Validates word is 3 or more characters long
if (!word.matches("\\w{3,}")) {
throw new IllegalArgumentException("Word must have 3 or more characters");
}
System.out.println("The Word you have typed is: " + word);
Another regex ideas might be:
[\w\s]{3,} --> alphanumeric and spaces with 3 or more
You can check the Strings length to see if it is less than 3...
if(word.length() < 3)
{
System.err.println("Error");
}