Separating content when reading a txt file in java - java

Sorry if a beginner question, but im trying to read contents from a file in java, and separate 3 strings with a / between them, ex: john/casey/lambert, how would I go along separating these three strings so I can store them into a firstName middleName and lastName variable. Im not sure how to get my scanner or code to recognize the / as a stopping point.

You can take the input in as string s = “John/Casey/lambert” and then you could split it into an array and take the values from there using s.split(“/“, -1)

String contents = "john/casey/lambert";
String contentsSplit[] = contents.split("/");
String firstName = contentsSplit[0]; //john
String lastName = contentsSplit[1]; //casey

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 to get different inputs in the same line?

I want to get different inputs in the same line in java, but instead of just printing them all at once i want to store then as a string or integer e.t.c...
I can´t find a solution, thanks.
You can import them by a deliminator then call the split function on the string and store the results in an array.
String input = scan.nextLine();
//Your input is: FirstName, LastName, DOB
String[] inputArr = input.split[","];
// inputArr[0] -> "firstName" etc..

Taking in a string from a txt file that has prices in double format separated by a tab and putting them into a double array

having a parse issue here on bottom line can someone please help!
FileIO io = new FileIO();
String[] original = io.load("C:\\sharePrice.txt");
int numcols=original[0].split("\t").length;
double[]sharePriceArray = new double[numcols];
for(int i=0;i<numcols;i++)
{ //load in the data
sharePriceArray[i] = Double.parseDouble(original[i].split("\t"));
}
AFAIK, .split splits a string into a string array. Your code is trying to assign a double to a string array, so that's the reason of your parse issue.
To fix, I would reccomend splitting the string into an array using .split(), and then traversing that array to assign to the double.
I suppose this should be like original[i].split("\t")[0] or original[i].split("\t")[1] in this case you are taking first or second value and then do parsing.

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.

Is it possible to add elements to an array previously defined as string

I need to read a text file and store the text in the file in five different arrays. The text file contains questions, four options and the correct answer in one line. I used the scanner to read the textfile and store the whole text as a string and then was trying to use the string tokenizer to differentiate the questions and the options so i could store them in their respective errors. The compiler gives me error when i try doing this:
public void readFile()
{
while (reader.hasNext())
{
String allText = reader.next();
StringTokenizer tokenizer = new StringTokenizer(allText, ",");
while (tokenizer.hasMoreElements())
{
question[index] = tokenizer.nextElement();
}
}
}
If question is a String, you can't add elements to it. You need to create a collection of Strings in order to add a String to it (you can use Array, List, Set etc.)

Categories

Resources