Splitting every String the user enters with a comma error - java

I am supposed to split every string the user enters with a comma.
For example, if the user enters in "Rabbit", I am supposed to print it out as
"R, a, b, b, i, t"
To do that, I searched up the split method String.split();
The code I wrote is as follows
import java.util.*;
class Split{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a String");
String str= input.nextLine();
printLetters(str);
}
public static String[] printLetters (String a){
return a.split(",");
}
}
Actually I am supposed to write the code using a method that accepts Strings, but when I wrote the String.split(), it said I have to use String [], so I just changed it to String[].
But that code didn't print anything.
I want to know why that is so, and also want to know how to accomplish this task using public static String.
I know there are lots of posts related to it, but I couldn't find anything that matches the requirement, which is using public static String.
I didn't learn the split method either, so I'm not supposed to use it to be honest.
This is my first year taking computer science, and the only things I know are
for loops, if else, nested loops, etc.
It would be preferable not to use the split method, but it's ok to use it because I'm curious about it too.
Thank you in advance :)

From what I can see, you are trying to take an input string and return a new string with inserted commas after every character.
String.split() does something quite different. For example, if I had "R,a,b,b,i,t", I could use String.split() with the delimiter , to get ["R", "a", "b", "b", "i", "t"] back.
A simple solution to your problem would be to iterate through the input string character by character and after each character except for the last one, add a comma to the return string.
Since your assignment is to actually do this yourself, I won't be posting a code solution. However, I hope my explanation cleared up your misconceptions and is enough for you to write a solution.

Use String.join().
import java.util.*;
class Split{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a String");
String str= input.nextLine();
String word = printLetters(str);
System.out.println(word);
}
public static String printLetters (String a){
return String.join(", ", a.split(""));
}
}
See String.join() and String.split() for more info.

public static void printLetters (String a){
String output = "";
for (int i=0; i<a.length(); i++)
{
output += a.charAt(i);
if (i != a.length()-1)
output += ",";
}
System.out.println(output);
}
See #Andrew Fan's answer. It describes what the split method does. What you need to do is like the reverse of that. You may use a for loop or a while loop.
*Since you are new to programming,
output += ","
is the same as
output = output + ","

Related

How to loop a String ArrayList in java and how to split the elements in it

I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.

Java Split("\\|") not working for strings with space

for the below input im expecting all the strings delimited with "|" to be available in an array. but only first string is available and the next string is partially available.the rest is not at all available. please help me in understanding it. i explored all the help docs and previous stackoverflow stuff but not able to solve it. i tried with split(String regex,int limit)as well but no use. I dont want to replace the whitespace as i need to retain that.
input "1|New York|1345|134|45634"
Expected output is: 1,New York,1345,134,45634
Actual output is:1,New
public class test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String strinp=scanner.next();
//System.out.println(strinp.replaceAll(" ", ""));
String[] strArr=strinp.split("\\|");
//System.out.println(Arrays.deepToString(strArr));
for (String s:strArr) {
System.out.println(s);
}
}
}
scanner.next() splits on spaces itself. So your first scanner.next() call reads 1|New which you then split.
Use scanner.nextLine() to read the whole line, it will be split successfully.
Change:
String strinp = scanner.next();
To:
String strinp = scanner.nextLine();
Or you can declare scanner as:
Scanner scanner = new Scanner(System.in).useDelimiter("\\n");

How to compare words of one string in Java with words of another string and separate the words on match?

This was an interview question.
You are told to take string input from user & output a string (or array of string) separated by spaces with meaningful words matching from another string called as Dictionary. You have a dictionary function to check if word exists or not.
For example:
if Input is "howareyou"
Output should be "how are you".
where the words 'how', 'are', 'you' are exist in dictionary string.
One more example:
Input: "somethingneedstobedone
Output: "something needs to be done
(Assuming that dictionary has words like something, needs, to, be, done.
I am not getting when to do k++ if there is no match.
The code I tried:
public class Sample1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j,k,len;
String[] dict= {"how","are","you","something","needs","to","be","done"};
//StringBuilder str=new StringBuilder("howareyou");
StringBuilder str=new StringBuilder("somethingneedstobedone");
len=str.length();
for(i=0,j=0,k=0;i<len;i++)
{
for(j=i+1;j<len;j++)
{
if(dict[k].toString().equals(str.substring(i, j)))
{
str.insert(j, " ");
k++;
}
}
}
System.out.println(str);
sc.close();
}
The commented case works well, but help me to get second case worked.
The issue you're having (and the reason the first string succeeded and the second does not) is to do with the order of words in the dict.
Your current implementation checks if the words in the dict appear in the string exactly in the order they were entered into the dict -
after you found the first word, put in a space and proceed to find the second word. If you did not find the next word, you do not proceed with the process.
There are many ways to rewrite the code to get what you want, but the minimal change is:
public class Sample1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j,k,len;
String[] dict= {"how","are","you","something","needs","to","be","done"};
//StringBuilder str=new StringBuilder("howareyou");
StringBuilder str=new StringBuilder("somethingneedstobedone");
len=str.length();
for(i=0,j=0;i<len;i++) //removed k from here
{
for(j=i+1;j<len;j++)
{
for (k=0;k<dict.length;k++) { //added this loop!
if(dict[k].toString().equals(str.substring(i, j)))
{
str.insert(j, " ");
}
} //Loop closing for k - the dictionary
}
}
System.out.println(str);
sc.close();
}

Splitting user_input strings, converting to uppercase & lowercase, and returning correct format

I've been trying to figure out how to create a program for a class. So far, I've gotten the rest of it down but I'm still unsure on how to do the start to it.
It requires for me to receive a name in any format: jOhn, joHN, JoHn
and convert it to John. I've been searching everywhere on how to separate them and return but I've had no luck.
Can anybody help?
This is for Java by the way.
EDIT: Not sure if I ended up doing it the right way, but I ended up with this:
System.out.println("Please type in your first name.");
String firstName = fName.next();
String partFirstName = firstName.toUpperCase().substring(0,1);
String partFirstName2 = firstName.toLowerCase().substring(1);
String correctFirst = (partFirstName + partFirstName2);
Simply in Java, without any 3rd party libraries, you can iterate over each element of an array of splitted Strings and then do:
Character.toUpperCase(user_input.charAt(0)) + user_input.substring(1).toLowerCase();
I don't know if this is what you are looking for but you could try the following:
EDIT: Thanks to Bohemian for pointing out a little bug in my code. The simplest code for the name formatting problem is Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase();. This is also what mhasen answered with so credit to him and also to Bohemian. Below contains the code snippet and all.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String newInput = Character.toUpperCase(charAt(0))
+ input.substring(1).toLowerCase();
System.out.println();
System.out.println(newInput);
scan.close();
}
}
You can use Apache Commons Lang library's WordUtils.capitalize()
e.g: WordUtils.capitalize("john") will return "John".
And in order to split the string you can use split() method of String:
String input = "jOhn,JOhn,jOHn";
String[] values = input.split(",");
values will be array of String contain "jOhn","JOhn" and "jOHn"

charAt method is returning an integer. Need to convert to int

I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.

Categories