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];
Related
The problem in question is indentifying if a string has a comma and outputting the substrings from the original string.
Here is my code:
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String fullString = "";
int checkForComma = 0;
String firstSubstring = "";
String secondSubstring = "";
boolean checkForInput = false;
while (!checkForInput) {
System.out.println("Enter input string: ");
fullString = scnr.nextLine();
if (fullString.equals("q")) {
checkForInput = true;
}
else {
checkForComma = fullString.indexOf(',');
if (checkForComma == -1) {
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
else {
continue;
}
firstSubstring = fullString.substring(0, checkForComma);
secondSubstring = fullString.substring(checkForComma + 1, fullString.length());
System.out.println("First word: " + firstSubstring);
System.out.println("Second word: " + secondSubstring);
System.out.println();
System.out.println();
}
}
return;
}
}
The error I keep receiving when I compile is this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 10
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at ParseStrings.main(ParseStrings.java:34)
I'm still somewhat new to programming and have never seen this type of error before, what are some ways to solve this and what might be causing it?
The exception occurs when the index is out of range.
What is a StringIndexOutOfBoundsException? How can I fix it?
For your code you are not re intializing the value of variable checkForComma
if (checkForComma == -1)
{
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
If checkForComma=-1, it will then take the next input and jump to
firstSubstring = fullString.substring(0, checkForComma);
A string index cannot be -1/negative, so it shows error.
Solution for the error
You should reinatialize the value of checkForComma, as per your program intake but
dont let it over pass the range of variable fullString.
Instead of using continue in the else when u check if the checkForComma variable equals -1, u can directly use the all other code which should be running when checkForComma has a real value.
Just replace this part of the code.
checkForComma = fullString.indexOf(',');
if (checkForComma == -1) {
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
else {
firstSubstring = fullString.substring(0, checkForComma);
secondSubstring = fullString.substring(checkForComma + 1);
System.out.println("First word: " + firstSubstring);
System.out.println("Second word: " + secondSubstring);
System.out.println();
System.out.println();
}
And to get the second word, you can use only the beginning input which is checkForComma + 1 in this case as this will return the value till the end of the string.
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());
}
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.
e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.
Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.
Thank you in advance for any help.
Jack
This is what I've got so far, but I don't think it works properly.
public class WordPlay {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word;
String palindrome = "";
String quit = "quit";
do {
System.out.print("Enter a word: ");
word = scanner.nextLine().toUpperCase();
int length = word.length();
for (int i = length - 1; i >= 0; i--) {
palindrome = palindrome + word.charAt(i);
}
if (word.equals(palindrome)) {
System.out.println("Is the word + palindrome + " same as " + word + "?", true);
} else {
System.out.println(false);
}
} while (!word.equals(quit));
System.out.println("Good Bye");
scanner.close();
}
}
Here it is.
public static void main(String[] args) {
// To take input.
Scanner scan = new Scanner(System.in);
System.out.print("Enter Word: ");
String word = scan.next(); // taking the word from user
// moving first letter to the end.
String newWord = word.substring(1) + word.charAt(0);
// reversing the newWord.
String reversed = new StringBuffer(newWord).reverse().toString();
// printing output.
System.out.println("You have entered '"+word+"'. "
+ "Is "+newWord+" same as "+word+"? "
+reversed.equals(word)+".");
// closing the input stream.
scan.close();
}
This works:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
char s2 = s1.charAt(0);
String s3 = s1.substring(1) + s2;
s3 = new StringBuilder(s3).reverse().toString();
if(s1.equals(s3))
System.out.println("They are same");
else
System.out.println("They are not the same");
}
}
This is very simple with some of observation. Your question is you have to move the first latter to the end and check reverse if the new string is same or not.
My ovservation:
For BANANA new string is ANANAB. Now reverse the string and check weather it is same as the first one.
Now If you ignore the first char B the string will be ANANA. As you have to reverse the string and check this one is same as the first one so this is like palindrome problem. For the input BANANA ANANA is palindrome. We are moving the first char to the end so there is no impact of it on checking palindrome. So I ignore the first char and check the rest is palindrome or not.
The Method is like:
private static boolean getAns(String word) {
int st = 1;
int en = word.length() - 1;
while (st < en) {
if (word.charAt(en) != word.charAt(st)) {
return false;
}
st++;
en--;
}
return true;
}
The main function is:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input your String:");
String word = scanner.nextLine();
boolean ans = getAns(word);
System.out.println("You have entered " + word + ". Is " + word.substring(1) + word.charAt(0) + " same as " + word + "? : " + ans + ".");
}
The Runtime for this problem is n/2 means O(n) and no extra memory and space needed,
I have tried to code it. See if it helps
import java.util.Scanner;
class StringCheck
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
String tempstr = new String();
System.out.println("Enter your String ");
str = sc.next();
int len = str.length();
//putting first character of str at last of tempstr
for (int i = 1 ; i<len; i++)
{
tempstr += str.charAt(i);
}
tempstr += str.charAt(0);
//reversing tempstr
char[] tempchar = tempstr.toCharArray();
int j = len-1;
char temp;
for ( int i = 0; i<len/2 ; i++)
{
if(i<j)
{
temp = tempchar[i];
tempchar[i] = tempchar[j];
tempchar[j]= temp;
j--;
}
else
break;
}
//reversing completed
tempstr = new String(tempchar);
// System.out.println("the reversed string is "+tempstr);
if(str.compareTo(tempstr)==0)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}
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;
}
}
}
}
I am quite new to programming and I am writing this code to count a string (length) to a point when I encounter a space. The aim is - when the user enters his/her name AND surname, the program should split the name from surname and count how many letters/characters were there in the name (and surname).
My code doesn't seem to reach/execute the "if-statement", if I enter two strings (name & surname) separated by space (output: Your name is: (empty space) and it has 0 letters. However, if I enter only one string, the if-statement, it gets executed.
What I am doing wrong?
My example code:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
for(int x = 0; x<=nameAndSurname.length()-1; x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
scan.close();
}
Why bother with all that code? Just skip the for-loop, have an
if (space != -1) nameOnly = nameAndSurname.substring(0,space);
and if you really want to know the amount of letters, it is
space+1
No need for all that complicated stuff.
if(nameAndSurname.indexOf(x) == space)
This line isn't doing what you think it is doing.
It's getting a char (character) from the index of x, and comparing it to the value of space. Space is an integer, so you are comparing the character at position x to the integer position of the first space. In this case, the letter at position x is cast into an integer, and then compared to the actual number value of the first space!
To fix the program, replace your entire if statement with this.
if (nameAndSurname.charAt(x) == ' ') //if there is a space
{
count = c-1; //how many characters/letters was there before space
System.out.println(count);
}
Extra:
Since the way you've solved this problem is a bit overkill, I've posted another solution below which solves it in a way that is easier to read. Also it won't break if you put in more or less than 1 space.
Scanner scan = new Scanner(System.in);
String nameAndSurname;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine().trim();
int indexOfFirstSpace = nameAndSurname.indexOf(' ');
if (indexOfFirstSpace > -1) {
String firstName = nameAndSurname.substring(0, indexOfFirstSpace);
System.out.println("Your first name is " + firstName.toUpperCase());
System.out.println("It is " + firstName.length() + " characters long.");
}
You can verify if your string has space before start the loop, something like this:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
if(space == -1) {
System.out.println("Your name has no spaces");
} else {
for(int x = 0; x<nameAndSurname.length(); x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
}
scan.close();
}