How to get different inputs in the same line? - java

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..

Related

Separating content when reading a txt file in 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

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);
}

Java input/output confusion

I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.

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.

Multiple inputs with arrays

I need to write a program that helps determine a budget for "peer advising" the following year based on the current year. The user will be asked for the peer advisor names and their highest earned degree in order to determine how much to pay them. I am using a JOptionPane instead of Scanner and I'm also using an ArrayList.
Is there a way for the user to input both the name and the degree all in one input and store them as two different values, or am I going to have to have two separate input dialogs? Example: storing the name as "Name1" and the degree as "Degree1 in order to calculate their specific pay.
Also, I am using an ArrayList but I know that the list will need to hold a maximum of six (6) elements, is there a better method to do what I am trying to do?
Here is what I had down before I started thinking about this, if it's necessary.
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class PeerTutoring
{
public static void main(String[] args)
{
ArrayList<String> tutors = new ArrayList<String>();
for (int i = 0; i < 6; i++)
{
String line = null;
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
String[] result = line.split("\\s+");
String name = result[0];
String degree = result[1];
}
}
}
"Is there a way for the user to input both the name and the degree all
in one input, but store them as two different values."
Yes. You can ask the user to enter input separated with space for example, and split the result:
String[] result = line.split("\\s+"); //Split according to space(s)
String name = result[0];
String degree = result[1];
Now you have the input in two variables.
"I decided to use ArrayList but I know the number of names that will be inputed (6), is there a more appropriate array method to use?"
ArrayList is fine, but if the length is fixed, use can use a fixed size array.
Regarding OP update
You're doing it wrong, this should be like this:
ArrayList<String[]> list = new ArrayList<String[]>(6);
String[] splitted;
String line;
for(int i=0;i<6;i++) {
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
splitted = line.split("\\s+");
list.add(splitted);
}
for(int i=0;i<6;i++)
System.out.println(Arrays.deepToString(list.get(i))); //Will print all 6 pairs
You should create an ArrayList that contains a String array that will represent the input (since the user enters pair as an input). Now, all what you have to do is to insert this pair to the ArrayList.
What you can do is store the input from you JOptionPane in a String, and then split the String into an array to store the name and degree entered. For example:
String value = null;
value = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] tokens = value.split(" ");//if you input name followed by space followed by degree, this splits the input by the space between them
System.out.println(tokens[0]);//shows the name
System.out.println(tokens[1]);//shows the degree
Now you can use tokens[0] to add the name to your List.

Categories

Resources