Breaking up a string in Java into a string array - java

I've researched this subject thoroughly, including questions and answers on this website....
this is my basic code:
import java.util.Scanner;
class StringSplit {
public static void main(String[] args)
{
System.out.println("Enter String");
Scanner io = new Scanner(System.in);
String input = io.next();
String[] keywords = input.split(" ");
System.out.println("keywords" + keywords);
}
and my objective is to be able to input a string like "hello, world, how, are, you, today," and have the program break up this single string into an array of strings like "[hello, world, how, are, you, today]...
But whenever i compile this code, i get this output:
"keywords = [Ljava.lang.String;#43ef9157"
could anyone suggest a way for the array to be outputted in the way i require??

Sure:
System.out.println("keywords: " + Arrays.toString(keywords));
It's not the splitting that's causing you the problem (although it may not be doing what you want) - it's the fact that arrays don't override toString.

You could try using Java's String.Split:
Just give it a regular expression that will match one (or more) of the delimeters you want, and put your output into an array.
As for output, use a for loop or foreach look to go over the elements of your array and print them.
The reason you're getting the output you're getting now is that the ToString() method of the array doesn't print the array contents (as it would in, say, Python) but prints the type of the object and its address.

This code should work:
String inputString = new String("hello, world, how, are, you, today");
Scanner scn = new Scanner(inputString);
scn.useDelimiter(",");
ArrayList<String> words = new ArrayList<String>();
while (scn.hasNext()) {
words.add(scn.next());
}
//To convert ArrayList to array
String[] keywords = new String[words.size()];
for (int i=0; i<words.size(); ++i) {
keywords[i] = words.get(i);
}
The useDelimiter function uses the comma to separate the words. Hope this helps!

Related

How to print part of a String from an array (Java)?

Hello im a total beginner in Java and have a problem. In a code below that has an array of fixed list of guests, how can i print emails of these person? The email must consist of 3 first name digits and two first surname digits, and after these are #guest.com. So it looks like this:
adaro#guest.com
thost#guest.com
In this task i must use methods: substring, split, toLowerCase.
Sorry for my english its not perfect. Please help i've tried to solve this but i'm stuck cant manage it.
public class email {
public static void main(String[] args) {
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
}
}
When you are stuck like this, try breaking down the problem bit by bit.
You are saying you don't know how to extract part of string, but also how to print. I'm tempted to give you written instructions and not the full answer to your question because that's how you will learn better.
You need to construct this email for each String in the String[] array. Look for iterating over arrays in java here for example https://www.geeksforgeeks.org/iterating-arrays-java/
For each String which is of this form "Rock Adam" you need to extract the surname and last name. To do this you need to split the String by space " ". How to do that - How to split a String by space
When you split by space you will get another Array of two elements, first will be surname, second will be first name. Use array indecies to access them.
When you access the firstName your next problem is - how do I get the first 3 characters of that String. How to access 3rd or 2nd is the same problem see how to do this here Extract first two characters of a String in Java
Now that you have the substrings you want to know how to concatenate and print them. How to print multiple variables? Answer is here How to print multiple variable lines in Java. Also for transforming the strings to lowercase you can find answer here https://www.w3schools.com/java/ref_string_tolowercase.asp
Try to do some more work yourself following this and you will learn much more than from copy-pasting what someone will give you directly for free.
Lower code solves your problem. String.split(" ") splits the String at the first occurrence of blank space. It gives a String array back which contains both parts of the name. With String.substring() you can get specific parts of the String.
public static void main(String[] args) {
String[] guests = {"Rock Adam",
"Stewart Thomas",
"Anderson Michael"};
for(String guest : guests){
String[] name = guest.split(" ");
String email = name[1].substring(0,3).toLowerCase() + name[0].substring(0,2).toLowerCase() + "#guest.com";
System.out.println(email);
}
}
Below code is exactly what you are looking for (i guess)
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
List<String> emailIdList = new ArrayList<>();
for (String guest : guests) {
String firstName = guest.split(" ")[1];
String lastName = guest.split(" ")[0];
String emailId = firstName.substring(0,2) + lastName.substring(0,1) + "#guest.com";
emailIdList.add(emailId);
}

How do i declare custom generated strings inside a while loop?

What I'm trying to do is to declare a certain amount of strings according to the amount of tokens a scanner scans in a single input, then have these strings equal the next input. This is what I'm trying:
int numberOfTokens = 0;
boolean mainLoop = true;
Scanner input = new Scanner(System.in);
while(mainLoop == true)
{
while(input.hasNext())
{
String int(+ numberOfTokens) = input.next(); (this doesn't work)
numberOfTokens += 1;
}
}
I hope I made it clear of what I am trying to do. I tried using String arrays, but they won't work for what i'm trying to do.
Thanks.
You can do:
String[] myStringArray = new String[abc];
where abc is an integer you get from user
and then
myStringArray[index] = input.next();
and index must be a valid number between 0 and abc
If you don't know in advance how many strings you will need to store then an array is a poor choice of data structure, at least during the input phase. Use a List instead -- these keep the elements in order, yet expand as needed to accommodate new elements. They are convenient to work with overall, but if you ultimately must get the strings in array form (e.g. because some external API requires that form) then it is easy to obtain the corresponding array.
For example:
List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
tokens.add(input.next());
// a List keeps track of its own length
}
If you later wanted the array then you could do
String[] tokenArray = tokens.toArray(new String[0]);
The number of tokens recorded in the List is available at any time as tokens.size(), or after you convert to an array, as tokenArray.length.
In any event, you cannot create new variables at runtime in Java.
Instead of string variables, you should declare one variable like this before the while loop.
List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
tokens.add(input.next());
}
You can then operate on the tokens, like this:
int n = tokens.size();
for (String token : tokens) {
System.out.println(token);
}

JAVA: How to convert String ArrayList to Integer Arraylist?

My question is -
how to convert a String ArrayList to an Integer ArrayList?
I have numbers with ° behind them EX: 352°. If I put those into an Integer ArrayList, it won't recognize the numbers. To solve this, I put them into a String ArrayList and then they are recognized.
I want to convert that String Arraylist back to an Integer Arraylist. So how would I achieve that?
This is my code I have so far. I want to convert ArrayString to an Int Arraylist.
// Read text in txt file.
Scanner ReadFile = new Scanner(new File("F:\\test.txt"));
// Creates an arraylist named ArrayString
ArrayList<String> ArrayString = new ArrayList<String>();
// This will add the text of the txt file to the arraylist.
while (ReadFile.hasNextLine()) {
ArrayString.add(ReadFile.nextLine());
}
ReadFile.close();
// Displays the arraystring.
System.out.println(ArrayString);
Thanks in advance
Diego
PS: Sorry if I am not completely clear, but English isn't my main language. Also I am pretty new to Java.
You can replace any character you want to ignore (in this case °) using String.replaceAll:
"somestring°".replaceAll("°",""); // gives "sometring"
Or you could remove the last character using String.substring:
"somestring°".substring(0, "somestring".length() - 1); // gives "somestring"
One of those should work for your case.
Now all that's left is to parse the input on-the-fly using Integer.parseInt:
ArrayList<Integer> arrayInts = new ArrayList<Integer>();
while (ReadFile.hasNextLine()) {
String input = ReadFile.nextLine();
try {
// try and parse a number from the input. Removes trailing `°`
arrayInts.add(Integer.parseInt(input.replaceAll("°","")));
} catch (NumberFormatException nfe){
System.err.println("'" + input + "' is not a number!");
}
}
You can add your own handling to the case where the input is not an actual number.
For a more lenient parsing process, you might consider using a regular expression.
Note: The following code is using Java 7 features (try-with-resources and diamond operator) to simplify the code while illustrating good coding practices (closing the Scanner). It also uses common naming convention of variables starting with lower-case, but you may of course use any convention you want).
This code is using an inline string instead of a file for two reasons: It shows that data being processed, and it can run as-is for testing.
public static void main(String[] args) {
String testdata = "55°\r\n" +
"bad line with no number\r\n" +
"Two numbers: 123 $78\r\n";
ArrayList<Integer> arrayInt = new ArrayList<>();
try (Scanner readFile = new Scanner(testdata)) {
Pattern digitsPattern = Pattern.compile("(\\d+)");
while (readFile.hasNextLine()) {
Matcher m = digitsPattern.matcher(readFile.nextLine());
while (m.find())
arrayInt.add(Integer.valueOf(m.group(1)));
}
}
System.out.println(arrayInt);
}
This will print:
[55, 123, 78]
You would have to create a new instance of an ArrayList typed with the Integer wrapper class and give it the same size buffer as the String list:
List<Integer> myList = new ArrayList<>(ArrayString.size());
And then iterate through Arraystring assigning the values over from one to the other by using a parsing method in the wrapper class
for (int i = 0; i < ArrayString.size(); i++) {
myList.add(Integer.parseInt(ArrayString.get(i)));
}

Java reading formatted text file and dividing it

I'm trying to understand file I/O for class and I understand the basics but I'm having trouble understanding how to manage whats in the input file, the input file is formatted like this:
BusinessContact:firstName=Nikolaos;lastName=Tsantalis
SocialNetworkAccount:socialNetworkType=SKYPE;accountID=tsantalis
Basically my contact (which BusinessContact extends from) object has attributes of firstName, lastName and middleName,
it also has object attributes such as SocialNetworkAccount and such....
I don't need to be explained how my objects are formatted, those have been done all I'm trying to understand is how my file.txt in inputed into my program to set my Contact to a BusinessContact as well as setting the first and last name accordingly,
Thanks
EDIT: Im specifically told to use the split method which makes sense but I'm also told (1) create a common method for the parsing of attributes that returns a map where the keys correspond to the attributeNames and the values to the attributeValues (in this way you can reuse the same code)
You can use the Scanner class with different delimiters like below:
Scanner in = new Scanner(/**source*/);
in.useDelimiter(":");
String firstName, lastName;
String firstWord = in.next();
Scanner nameScanner = new Scanner(in.nextLine());
nameScanner.useDelimiter(";");
firstName = getName(new Scanner(nameScanner.next()));
lastName = getName(new Scanner(nameScanner.next()));
private String getName(Scanner nameScanner){
nameScanner.useDelimiter("=");
String nameTitle = nameScanner.next();
return nameScanner.next();
}
This way you read the text in parts as follows as follows:
BusinessContact:firstName=Nikolaos;lastName=Tsantalis
firstName=Nikolaos;lastName=Tsantalis
firstName=Nikolaos;lastName=Tsantalis
I hope this makes sense.
NOTE: This code reads only the first line. If you want to read the second i guess its not hard to modify it. If you want the second line too or if you have any issues let me know and i will update the answer.
EDIT: I just noticed that every line is formated the same way so basically you can use the same code for every line. Maybe in a loop like:
Scanner input = new Scanner(/**source*/);
while(input.hasNextLine()){
Scanner in = new Scanner(input.nextLine());
...
....
//The above code
}
String.split() method:
Scanner in = new Scanner(System.in);
String[] first = in.nextLine().split(":");
String[] second = first[1].split(";");
String[] thirdA = second[0].split("=");
String[] thirdB = second[1].split("=");
for(int i = 0; i < thirdA.length; i++){
System.out.println(thirdA[i]);
System.out.println(thirdB[i]);
}
For the first line, the above code will print:
firstName
lastName
Nikolaos
Tsantalis
Hope this helps.
You could use a regular expression, but you might feel more comfortable with String.split: Split on ":" and get the label, the split the second part on ";" to get the attributes, then split each attribute on "=" to get the key and the value.

How to use a sorting algorithm in Java?

My assignment is to ask a user for the number of strings he would like to input. Then i will prompt him to right the strings. Then i am supposed to print the stings in alphabetical order. I got most of the assignment done, just need a sorting algorithm such as Bubble sort to finish it. this is my code.
import java.io.*;
public class sorting
{
private static BufferedReader stdin=new BufferedReader(new InputStreamReader( System.in));
public static void main(String[] arguments) throws IOException
{
System.out.println("How many strings would you like to enter?");
int stringCount = Integer.parseInt(stdin.readLine());
String[] stringInput = new String[stringCount];
for(int i = 0; i < stringCount; i++)
{
System.out.print("Could you enter the strings here: ");
stringInput[i] = stdin.readLine();
}
//Now how do i use a sorting algorithm?
}
}
Arrays.sort().
Use Rhino as a Javascript parser so you can include jQuery into your project. Then sorting becomes trivial as you can just load the Strings into a <table> and run this nifty plugin on it.
^ DO NOT DO THIS. (well if you do, post the source and tell us what grade you got on the assignment ;)
No really, just write bubble sort by yourself. It's not that long. You probably learned the pseudocode in class. If you need an additional reference, take a look at the Wikipedia article on it. If there's something in particular that you don't understand about the algorithm, post a specific question and we'll help you out. Other than that, you look like you're on the right track so far :)
If this wasn't an exercise you'd just use Arrays.sort(stringInput)
import java.io.*;
import java.util.*;
public class sorting
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
System.out.print("How many strings would you like to enter? ");
String[] stringInput = new String[Integer.parseInt(input.nextLine())];
for(int i = 0; i < stringInput.length; i++)
{
System.out.print("Could you enter the strings here: ");
stringInput[i] = input.nextLine();
}
Arrays.sort(stringInput);
for(String s : stringInput) System.out.println(s);
}
}
It seems to me that you are not being asked to sort the string array, but to print the strings in alphabetical order, which is likely to be a whole lot uglier but a whole lot simpler.
Once the user has typed all of the input strings, you might choose to iterate over the array stringCount times finding, in each iteration, the lowest-valued string; printing it; and then clearing it so that you won't see it in the next iteration.
BUT if you really are being asked to apply a bubble sort (or any kind of sort) on the array, well, that's a whole 'nother question, namely: how do I write a bubble sort for an array of strings. That's a tricky problem for anyone because the strings in the array are of differing lengths: they cannot just be swapped blindly but have to be written into some temp array somewhere that somehow knows how to accomodate their various lengths.
EDIT: Oh, wait a sec: maybe Java knows all about variable-length strings and how to handle them. If so, I take it all back.
Just use the Set str = TreeSet();
then loop through the string str.add("z");
when you iterate the str variable it is automatically sorted.

Categories

Resources