I'm trying to write a program that will take a string and parse it into two outputs, with the delimiter being a comma. It loops until the user enters the character "q".
i.e.: Console prompts to enter an input, and user inputs "first, second" and then "q" for the second prompt, and the output will be:
Enter input string:
First word: first
Second word: second
Enter input string:
If there is no comma in the input, it throws an error and prompts again
i.e. User inputs "first second" and the output will be:
Enter input string:
Error: No comma in string
Enter input string:
Below is what I have so far:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Scanner for standard input
Scanner inSS = null; // Scanner to write input to buffer
String firstWord = ""; // First word string
String secondWord = ""; // Second word string
String userInput = ""; // Input from prompt
int i = 0; // Loop iterator
boolean inputDone = false; // Boolean to repeat while loop
boolean hasComma = false; // Boolean to check for comma
// Do while inputDone is false
while (!inputDone) {
//Prompt user to input a string
System.out.println("Enter input string: ");
// Write string to userInput
userInput = scnr.nextLine();
// Exit program if user inputs q
if((userInput.equals("q"))) {
inputDone = true;
break;
}
else{
// Write userInput to buffer
inSS = new Scanner(userInput);
// Write first word from buffer
firstWord = inSS.next();
// Loop through first word string
for (i = 0; i < firstWord.length(); ++i) {
// If char is a comma, write everything after to secondWord and set inputDone to true
if(firstWord.charAt(i) == ',') {
secondWord = inSS.next();
hasComma = true;
}
}
// If hasComma is false, return error
if (!hasComma){
System.out.println("Error: No comma in string");
}
// Else print first word and second word
else {
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println("");
System.out.println("");
}
}
}
return;
}
}
Problems:
I don't know how to remove the comma from the output
If there is no space it errors out
If there is a space between the first word and the comma, it writes firstWord but does not overwrite the previous value for secondWord (or errors if it's the first input given)
I'm taking a beginner's Java course and we have not gone over the .parse() method yet, so it's not really an option at this time.
Thank you in advance!
Try using string split.
String str="first, second";
String[] arr=str.split(",");
if(arr.length == 2) {
System.out.println("First :" + arr[0]);
System.out.println("Second :" + arr[1]);
} if(arr.length > 2) {
System.out.println("More than 1 comma used.");
} else {
System.out.println("Error. No comma found.");
}
You can use trim() in case your string has any spaces around comma.
So what I've done is probably the laziest and the most rookie way, but it does work.
Use a for loop to check each character of the string for the comma.
char ch;
String str = "";
if(userInput.charAt(userInput.length()-1) == ',')
System.out.println("Error. You must have a comma here.");
else {
for(int i = 0; i < userInput.length(); i++)
{
ch = userInput.charAt(i);
if(ch != ',')
str += ch;
else
{
firstWord = str;
secondWord = userInput.substring(i+1);
break;
}
}
}
If the selected letter is not a comma, it is added to the temporary string.
If it is a comma, then the temporary string becomes the first word, and the second word is the string after the occurrence of the comma.
if(userInput.charAt(userInput.length()-1) == ',') Handles the exception that may arise if the input is hello ,, or anything that ENDS with a comma.
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);
}
I am currently working on an assignment to parse strings and I am running into an issue.
It appears, that if nothing is entered, it is generating my error message I have created when a comma is not inputted.
According to the assignment in zybooks, it should not be outputting anything. Below is my code.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
//local variables
String lineString;
String firstWord;
String secondWord;
int commaLocation;
boolean inputDone;
//checks to end the program
inputDone = false;
//keeps the loop running until q is entered
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
//checks comma
commaLocation = lineString.indexOf(',');
if (commaLocation == -1) {
System.out.println("Error: No comma in string");
}
else {
firstWord = lineString.substring(0, commaLocation);
firstWord = firstWord.replace(" ", "");
secondWord = lineString.substring(commaLocation + 1, lineString.length());
secondWord = secondWord.replace(" ", "");
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
System.out.println();
}
if (lineString.equals("q")) {
inputDone = true;
}
}
return;
}
}
It happens because when nothing is entered, comma cannot be found, therefore indexOf returns -1.
I would add something like
if (lineString.isEmpty()) {
continue;
}
right after lineString = scnr.nextLine();
EDIT:
I just noticed, that your error message will be printed in case, when your input equals 'q'. I assume this is not an expected behaviour, so I recommend to place
if (lineString.equals("q")) {
inputDone = true;
}
right after assignment of lineString or the if block I suggested above.
so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));
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;
}
}
import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you