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.
Related
I want my code to respond if the user only presses enter and doesn't type anything else. I use .trim to react to only putting in spaces but, it gives me an error when I just hit enter as the input. Here is what I have so far:
import java.util.Scanner;
class Main {
static Scanner name = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What is your first name?");
String a = name.nextLine();
String b = a.substring(0, 1).toUpperCase() + a.substring(1);
String c = a.trim();
if (c.length() != 0) {
if (a.contains(" ")) {
System.out.println("You put space in your name. : (");
} else {
System.out.println(b + " is a nice name! : )");
}
} else {
System.out.println("Thats not a name! : (");
}
}
}
try (Scanner scan = new Scanner(System.in)) {
System.out.println("What is your first name?");
String str = scan.nextLine().trim();
if (str.isEmpty())
System.err.println("You entered an empty name");
else if (str.contains(" "))
System.err.println("You put space in your name.");
else {
String name = Character.toUpperCase(str.charAt(0)) + str.substring(1);
System.out.println('\'' + name + "' is a nice name!");
}
}
I think this is probably what you want. Furthermore, I've also highlighted a few best practices.
class Main {
private static Scanner scanner = new Scanner(System.in); // Point 0 - Use access modifiers!
public static void main(String[] args) {
System.out.println("What is your first name?");
String name = ""; // Point 1 - Initialize your variables to avoid NullPointerException
// Point 2 - Always check if there is something to read from scanner
if (scanner.hasNextLine()) {
name = scanner.nextLine();
}
// Point 3 - You can methods in place instead of stack variables
if (!name.isEmpty()) {
if(name.contains(" ")) {
System.out.println("You put space in your name. : (");
} else {
// Point 4 - You can do away with extra variables
System.out.println(capitalize(name) + " is a nice name! : )");
}
} else {
System.out.println("That's not a name! : (");
}
scanner.close(); // Point 5 - Clean up your resources
}
// Point 6 - Concise methods makes code more readable
private static String capitalize(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
}
You can look up more about Scanner.
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.
I am new to Java and cannot figure out where I am going wrong with my code. The program is supposed to take a couple words input as a single string with a comma and print them out as two separate words without the comma. It is supposed to print out an error message if there is no comma as well. Entering "q" will quit the program. It works perfectly when a "q" is entered. It also works when there is no comma, however, after the output it adds the following error message:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ParseStrings.main(ParseStrings.java:16)
Also, the program won't work when there is a comma input, but when I comment out the part about the comma in the code, it works but gives the above error message. Any assistance in showing me my errors will be greatly appreciated. Here is the code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
boolean noComma = false;
System.out.println("Enter input string or q to quit: ");
while (!inputDone) {
userInput = scnr.nextLine();
if (userInput.equals("q")) {
System.out.println(" Exiting.");
inputDone = true;
}
else {
while (!noComma) {
if (userInput.indexOf(',') < 0) {
System.out.println("Error: No comma in string");
noComma = true;
}
else {
firstWord = userInput.substring(0, userInput.indexOf(','));
firstWord = firstWord.trim();
secondWord = userInput.substring(userInput.indexOf(',') + 1, userInput.length());
secondWord = secondWord.trim();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
}
}
return;
}
}
You don't need the while loop:
while (!noComma) {
It will be infinite because noComma won't be set unless there are no commas in the input. The if statement that you have after that handles this condition the way I think you want:
if (userInput.indexOf(',') < 0) {
In your Code if i typed a String with no comma output is correct but if again i typed with comma or without comma it stuck in the infinite loop and if I terminate the program it is giving the exception.It is Thrown by various accessor methods to indicate that the element being requested does not exist. now let me show the error in your code
while (!inputDone) {userInput = scnr.nextLine();
if (userInput.equals("q")) {
System.out.println(" Exiting.");
inputDone = true;
}
else {
while (!noComma) {
if (userInput.indexOf(',') < 0) {
System.out.println("Error: No comma in string");
noComma = true;
}
when i typed without comma it came to first else and due to condition match it entered in noComma while loop and with printing the message it set the noComma flag now it can not enter in the else as the very first while condition is false so it will now never go to the else condition so now it is just checking this condition
while (!inputDone) {userInput = scnr.nextLine();
if (userInput.equals("q")) {
System.out.println(" Exiting.");
inputDone = true;
}
with a infinite while loop which is taking the input but just searching for the "q" so when you terminate this program by Ctrl+c it will end with that Exception.
Please Correct me If I am wrong anywhere.
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;
}
}
This is a simple question selection, and then answer program:
import java.util.Scanner;
public class Mains {
static Scanner console = new Scanner(System.in);
static Tof tof = new Tof();
static int Ievel = 0;
static int Input = 0;
static boolean GAME = true;
static boolean AT_START = true;
static boolean IN_QUESTION = false;
public static void main (String[] args) {
while (GAME) {
String InputS = "";
if (AT_START) {
System.out.println("Welcome to the game! Please select a number from 1 to 10.");
AT_START = false;
}
if (!IN_QUESTION)
Input = console.nextInt();
if (Input == -1) {
GAME = false;
console.close();
} else {
String question = tof.getQuestion(Input);
String answer = tof.getAnswer(Input);
System.out.println(question);
IN_QUESTION = true;
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS != console.nextLine()) {
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
}
}
}
}
}
Problem:
When entering the IN_QUESTION loop, and writing a answer, it will always be incorrect.
That's because the InputS variable is ALWAYS empty, no matter what, while it has console.nextLine() set on it.
Why is it empty? How do I fix this?
In-case you need the other class Tof: http://pastebin.com/Fn5HEpL2
nextInt doesn't get the line terminator after the integer and you're reading from the console twice (the second time being in the if-statement).
So if you enter:
123
apple
The following happens:
Input gets assigned a value of 123
InputS gets assigned an empty string
InputS gets compared against apple and it is not equal (from InputS != console.nextLine() - I'm not sure why it's there)
You can fix it by:
Putting a console.nextLine(); after console.nextInt();
OR
Use Input = Integer.parseInt(console.nextLine()) instead of nextInt
Removing this - if (InputS != console.nextLine())
You're reading from the console twice. This should work:
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
The problem is that the new line character was not read by the nextInt() method so it remain in the scanner buffer and when the next time you called nextLine() that character was printed first.
This is how to fix the issue:
//empty the newline character from the scanner
console.nextLine();
while (IN_QUESTION) {
InputS= console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
You call console.nextLine twice. This means that you read a line that you'll check, and another you won't. This is probably not what you are after. Also note that your initial call of nextInt will not consume the newline you pressed after entering the number. You need a nextLine right after that, but before the main loop.
Some general remarks:
uppercase names are only for constants, so your variables should be lowercase;
you should really be using local variables instead of static ones. Right now this isn't hurting you, but it soon could.