I have been trying to write this code where a user enters two words with or without a comma and if it does not have a comma print the an error saying so and then loop back to ask for another set of words. Yes this is homework and I have searched the internet for help and it just has not clicked with me so far. I am needing help with the loop in my code which is java. These are the set of requirements for my warm up program followed by my code. Thank you for any help anyone can give.
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.
3) Extract the two words from the input string and remove any spaces. Store the
strings in two separate variables and output the strings.
4) Using a loop, extend the program to handle multiple lines of input. Continue
until the user enters q to quit.
Here is my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
System.out.println("Enter input string: ");
while (!inputDone) {
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
}
if (lineString.contains(",")) {
String[] parts = lineString.trim().split("\\s*,\\s*");
firstWord = parts[0];
secondWord = parts[1];
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
} else {
System.out.println("Error: No comma in string");
}
break;
}
return;
}
}
1) You do not need the return statement for a main method of type void
2) The break at the end of your loop is what is terminating it after the first run.
Writing break; within your loop is the same thing as telling your loop to stop looping. If you want to define another condition to terminate your loop, but dont want to put it in your while, then put your break inside of some sort of condition, that way it doesn't happen every single time.
I am trying to figure out when the user enters q the program quits here is my code so far.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
String s = sc.nextLine();
System.out.println("Enter input string: ");
if (s.indexOf(",") == -1) //checks if there is a comma in the string
{
System.out.println("Error: No comma in string");
} else {
//there is a comma in the string
String s1 = s.substring(0, s.indexOf(","));
String s2 = s.substring(s.indexOf(",") + 1);
s1 = s1.replace(" ", "");
s2 = s2.replace(" ", "");
//store both the strings in s1 and s2
System.out.println("First word: " + s1);
System.out.println("Second word: " + s2);
s1 = s1.trim();
s2 = s2.trim(); //remove extra spaces
System.out.println(s1 + " " + s2);
break;
}
}
}
}
Related
Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}
I'm working on a parsing assignment, and I'm supposed to take the input and turn it into two separate strings and output the strings. If there is no comma, I give an error message. If the choice is "q", then end the loop. Here is my code:
import java.util.Scanner;
import java.lang.*;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
/* Type your code here. */
String name;
String first;
String last;
int commaIndex;
int size;
boolean quit = false;
while (!quit)
{
System.out.println("Enter input string:");
name = scnr.nextLine();
commaIndex = name.indexOf(',');
size = name.length();
// get q case
if (name.equals("q"))
{
quit = true;
}
// if no comma, give error message
else if (commaIndex == -1)
{
System.out.println("Error: No comma in string.");
System.out.println();
}
else
{
first = name.substring(0, commaIndex);
last = name.substring(commaIndex + 1, size);
// re do, but without spaces
first = first.replaceAll(" ", "");
last = last.replaceAll(" ", "");
commaIndex = name.indexOf(',');
first = name.substring(0, commaIndex);
last = name.substring(commaIndex + 1, size);
System.out.println("First word: " + first);
System.out.println("Second word: " + last);
System.out.println();
}
}
}
}
And the input is this:
Jill, Allen
Golden , Monkey
Washington,DC
q
I'm not getting the points because of the space after the word "Golden " and before " Monkey"
try this
/* Type your code here. */
String name;
String first;
String last;
while (true)
{
System.out.println("Enter input string:");
name = scnr.nextLine();
// get q case
if (name.equals("q"))
{
//You can avoid to use quit flag, you can break the loop
break;
}
else
{
//Separate the input with split by the comma character
string [] arr = name.split(",");
// if no comma, give error message in other words if you array is empty
if(arr.length==0){
System.out.println("Error: No comma in string.");
System.out.println();
}
//check if you have more than 2 words
if(arr.length>1){
//the trim function will remove all white spaces at the start and end of the string
first = arr[0].trim();
last = arr[1].trim();
System.out.println("First word: " + first);
System.out.println("Second word: " + last);
System.out.println();
}else{
first =arr[0].trim();
System.out.println("First word: " + first);
System.out.println();
}
}
}
Use String.split(String) it takes a regular expression. Split on optional whitespace and comma. Like,
String[] tokens = name.trim().split("\\s*,\\s*");
String first = tokens[0];
String last = tokens[tokens.length - 1];
I'm trying to figure out if I can count the characters of each token and display that information such as:
day is tokenized and my output would be: "Day has 3 characters." and continue to do that for each token.
My last loop to print out the # of characters in each token never prints:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Example of Console:
Please type a sentence containing at least 4 words, with a maximum of 8 words:
Hello there this is a test
Thank you.
You entered:
Hello there this is a test
Each word in your sentence is: [Hello, there, this, is, a, test]
First off, I have added the necessary imports and built a class around this main method. This should compile.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SOQ_20200913_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Next, let's look at this working example. It seems like everything up until your final while loop (the one that counts character length) works just fine. But if you notice, the while loop before the final one will continue looping until it has no more tokens to fetch. So, after it has finished gathering all of the tokens and has no more tokens to gather, you try and create the final while loop, asking it to gather more tokens. It would not have reached the while loop until it ran out of tokens to gather!
Finally, in order to solve this, you can simply go through the list that you added to in the second to last while loop, and simply cycle through that for your final loop!
For example:
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println("Word: " + each + " Length:" + each.length());
}
My Computer Science class assignment requires that I write a program which determines if a word or phrase is a palindrome (is the same forward and backwards, ie "noon"). As part of this, I have to write a method which removes all punctuation and spaces, so they are not counted in determining if it is a palindrome. It also runs on a loop, allowing the user to input as many phrases they want until they indicate they're done. My problem is that when the word/phrase entered contains a space, somehow it terminates the loop and doesn't allow more input. The program works just fine, as long as the input has no spaces. Here's my code:
In class RecursivePalindrome:
public String removePunctuation(String s){
s = s.replaceAll("\\.","");
s = s.replaceAll("!","");
s = s.replaceAll(",","");
s = s.replaceAll(" ","");
s = s.replaceAll("'","");
s = s.replaceAll("-","");
s = s.replaceAll("\\?","");
return s;
}
public boolean isPalindrome(String s) {
s = removePunctuation(s);
String firstChar = s.substring(0,1);
String lastChar = s.substring(s.length()-1);
if (s.length() == 1){
return true;
}
if (s.length() == 2 && firstChar.equalsIgnoreCase(lastChar)){
return true;
}
if (!firstChar.equalsIgnoreCase(lastChar)){
return false;
}
return isPalindrome(s.substring(1, s.length() - 1));
}
In class RecursivePalindromeTester:
public static void main(String[]args){
//Create objects
Scanner in = new Scanner(System.in);
RecursivePalindrome palindrome = new RecursivePalindrome();
//Output
for (String again = "Y"; again.equalsIgnoreCase("Y"); again = in.next())
{
//Prompt for input
System.out.println();
System.out.print("Enter a word or phrase: ");
String phrase = in.next();
//Output
if (palindrome.isPalindrome(phrase)){
System.out.println("This is a palindrome.");
}
else
System.out.println("This is not a palindrome.");
System.out.print("Another word or phrase? (Y/N): ");
}
}
The output should be:
"Enter word or phrase: <input>mom- mom!
This is a palindrome
Another word or phrase? (Y/N): <input>Y
Enter a word or phrase: <input>Dog?
This is not a palindrome
Another word or phrase? (Y/N): <input>N"
Terminate
But instead I get:
"Enter word or phrase: <input>mom- mom!
This is a palindrome
Another word or phrase? (Y/N):"
Terminate
I really have no idea why a space would cause the loop to terminate, especially since it doesn't do this with any other punctuation.
Totally agreed with #Ilya Bursov comment,
You should use in.nextLine() instead of in.next() , there are big difference between both methods
next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line
Try like this ,
class RecursivePalindromeTester {
public static void main(String[] args) {
//Create objects
Scanner in = new Scanner(System.in);
RecursivePalindrome palindrome = new RecursivePalindrome();
//Output
for (String again = "Y"; again.equalsIgnoreCase("Y"); again = in.nextLine()) {
//Prompt for input
System.out.println();
System.out.print("Enter a word or phrase: ");
String phrase = in.nextLine();
//Output
if (palindrome.isPalindrome(phrase)) {
System.out.println("This is a palindrome.");
}
else
System.out.println("This is not a palindrome.");
System.out.print("Another word or phrase? (Y/N): ");
}
}
}
I turned a codingbat warmup exercise into a program on Eclipse. The exercise calls to take the last char of a word and tack it onto both the front and end of a word, e.g. "cat" → "tcatt."
First attempt:
I started with this set of code and received the error "void methods cannot return a value." After some research, it appears that it's simply that if there's only one main method, you cannot return a value.
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String str = input.nextLine(); // user input
String last = str.substring(str.length() - 1);
return last + str + last;
Second Attempt:
I tried here adding a second method and renaming the second string at the bottom to str1, to correct a duplicate local variable error:
public static void main(String[] args) {
}
public String backAround(String str) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String str1 = input.nextLine(); //user input
String last = str1.substring(str.length() - 1);
return last + str1 + last;
This code now displays no errors, but won't display anything and thus won't take any user input. What is the methodology to correctly get the user input and return the string?
You are confusing a function return with simply displaying text back to the user. If you do not understand functions yet, you can stick with modifying the main function, and simply print results back to the console
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String str = input.nextLine(); // user input
String last = str.substring(str.length() - 1);
System.out.println(last + str + last);
So for a string method, you return a string value. SO you will have to have a string varable equal to that string value, then print it out.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String str1 = input.nextLine(); //user input
String result = backAround(str1);
System.out.print(result);
}
public String backAround(String str) {
String last = str.substring(str.length() - 1);
return last + str + last;
}
Your problem is your code is correct but never used.
Change String backAround(String str) to String backAround() since you do not need the str param since it is never used. Then add to you main the following
System.out.println(backAround());
The main is the only function that will be run when you run your application. By adding the System.out.println(backAround()) line you tell your application it has to run the backAround function and then printing the returned String