I have a string where i need to place the values from the list,But when i for loop the list i will get one value at a iteration.
public class Test2 {
public static void main(String[] args) throws ParseException, JSONException {
List<String> value=new ArrayList<String>();
value.add("RAM");
value.add("26");
value.add("INDIA");
for(int i=0;i<value.size();i++){
String template="My name is "+value.get(i) +" age is "+value.get(i)+" country is"+value.get(i);
System.out.println(value.get(i));
}
o/p should be like this: String ="My name is +"+RAM +"age is "+26+"Country is"+INDIA;
}
}
You don't need a for loop, simply access the elements using index of the List as shown below:
System.out.println("My name is "+value.get(0) +
" age is "+value.get(1)+" country is"+value.get(2));
Also, I suggest you use StringBuilder for appending strings which is a best practice, as shown below:
StringBuilder output = new StringBuilder();
output.append("My name is ").append(value.get(0)).append(" age is ").
append(value.get(1)).append(" country is ").append(value.get(2));
System.out.println(output.toString());
What's happening is that in each iteration you're taking the i-th element of the list and you're placing it in all the positions of your String template.
As #javaguy says, there's no need to use a for loop if you only have those three items in your list, and another solution is to use String.format:
String template = "My name is %s age is %s country is %s";
String output = String.format(template, value.get(0), value.get(1), value.get(2));
It's probably a bit slower (interesting discussion here) but performances don't seem to be relevant in your case, so the choiche between the two options would be mostly based on personal taste.
You do not need any loop! Also you do not need any array list I am sorry but I could fully understand what exactly you need but I this code will help you:
List<String> value = new ArrayList<String>();
value.add("RAM");
value.add("26");
value.add("INDIA");
String template = "My name is " + value.get(0) + " age is " + value.get(1) + " country is" + value.get(2);
System.out.println(template);
// o/p should be like this: String ="My name is +"+RAM +"age is
// "+26+"Country is"+INDIA;
Related
good afternoon, I would need help with the following method where I have a list of rooms, for example, and it is to print a URL with the data. only that the last data of the list would need to remove the .append(";") which would be the separator and replace it with (" ") or remove the ; . Only in the cases of the last object (room),
I investigated but I would not know what is best if the size or the lastIndexOf
example
rooms.get(rooms.size()-1); -->option 1
rooms.lastIndexOf(room); --> option 2
the url comes as follows,
https://hotel.google.net/hotels/ytd.proba.miami,2/MIA/XXXXX-XXXXX/1DR;1DR;?token=Ws2QmzjsxDFC7jeN&
I would only need the last 1DR to not have the ; just the last. If I'm missing any more information, tell me. Thanks a lot
private String getFormattedRooms(List<HotelRoom> rooms) {
StringBuilder formattedRooms = new StringBuilder();
for (HotelRoom room : rooms) {
formattedRooms.append("1").append(getSupplierRoomType(room)).append(getChildrenAges(room)).append(";");
}
return formattedRooms.toString();
}
What you're actually building is a series of strings joined by ';', so why not build each string and then join them?
With streams, for example:
rooms.stream()
.map(room -> "1" + getSupplierRoomType(room) + getChildrenAges(room))
.collect(Collectors.joining(";"));
Without streams:
private String getFormattedRooms(List<HotelRoom> rooms) {
List<String> roomStrings = new ArrayList<>();
for (HotelRoom room : rooms) {
roomStrings.add("1" + getSupplierRoomType(room) + getChildrenAges(room));
}
return String.join(";", roomStrings);
}
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);
}
I am working on a Lab on the site Zybooks and I have completed the following code below:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName;
String middleName;
String lastName;
firstName = scnr.next();
middleName = scnr.next();
lastName = scnr.nextLine();
if (lastName.contains("")){
System.out.println(middleName + ", " + firstName.charAt(0) + ".");
}
else {
lastName = lastName.substring(1);
System.out.println(lastName + ", " + firstName.charAt(0) + "." + middleName.charAt(0) + ".");
}
}
}
The Exception Error that I receive is this:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at LabProgram.main(LabProgram.java:13)
When I run the following code in an IDE everything works just fine. However when I try running it in Zybooks I get an exception error. I've come to learn that this is because when I don't add a space after I enter two names that Zybooks gives an exception error. However when I add a space after the last name the code compiles as intended. For grading purposes I need the code to compile without a space from the keyboard, thus I am asking how I can get this code to compile. I've tried manually adding whitespace but nothing has worked.
Any help would be very much appreciated
Looking at the code it's obvious that you have three (3) specific User entry prompts to deal with. The User must supply a First Name, then the User needs to supply a Middle Name, and then finally the User needs to supply a Last Name. As with any input each of these names needs to be validated for proper context. This would include the rules for names, for example everyone has a First Name and Last Name but not everyone has a Middle Name also first and last names can contain two name words (ex: De Vanderholt).
When you have three specific prompts for the User to fill in then let them know exactly where they are at. Display on Screen what the User is expected to enter. It's always a good idea to place each prompt into a loop so that the input can be validated and if there is a problem the User is given the opportunity to provide actual valid data (in this case a valid name).
In your code you use the Scanner#next() method to retrieve the input for both First Name and Middle Name(s) however this method will not play well with multi word names since the next() method is token based. This means that if a two word name is supplied to the First Name prompt then only the first word is retrieved and the second word is automatically applied to the Middle Name prompt. You don't even get a chance to enter the middle name. This is no good unless special code is put in place to take car of this situation. It's just better not to use the next() method in this case and simply use the Scanner#nextLine() method for all your prompts. Keep in mind however that the Scanner#next() method will work just fine if you know that only a single name word will be provided by the User but this method is better used in conjunction with the Scanner#hasNext() method.
Look at your code. As said earlier, everyone has a Last Name but not everyone has a Middle Name so why have this line of code (unless your rules include the fact that last names can be nothing):
if (lastName.contains("")){
It should actually never be allowed to come to this scenario where the last name contains nothing, don't even accept the fact unless it's a middle name. If the supplied Last Name was validated then you would never need to worry about this situation unless of course your rules allow it. The example code below does not allow it.
Because there are three prompt which basically do the same thing and require the same basic validation a helper method (getName()) is used so as to eliminate the need for duplicate code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// First Name:
String firstName = getName(scnr, "First");
// Middle Name:
String middleName = getName(scnr, "Middle");
// Last Name:
String lastName = getName(scnr, "Last");
System.out.println(new StringBuilder("")
.append(lastName).append(", ")
.append(firstName.charAt(0))
.append(". ")
.append(middleName.isEmpty() ? "" : middleName.charAt(0))
.append(middleName.isEmpty() ? "" : ".").toString());
// O R
/*
System.out.println(new StringBuilder("")
.append(lastName).append(", ")
.append(firstName)
.append(" ")
.append(middleName)
.toString());
*/
// O R
/*
System.out.println(new StringBuilder("")
.append(firstName)
.append(" ")
.append(middleName)
.append(middleName.isEmpty() ? "" : " ")
.append(lastName)
.toString());
*/
}
The Helper Method (getName()):
private static String getName(final Scanner scnr, final String nameTitle) {
String name = "";
while (name.isEmpty()) {
System.out.print("Enter your " + nameTitle + " Name: --> ");
// Get input and trim off leading/trailing whitespaces, etc
name = scnr.nextLine().trim();
// Is this for a Middle Name?
if (nameTitle.equalsIgnoreCase("middle")) {
// If nothing was supplied then there is no
// middle name so break out of prompt loop.
if (name.isEmpty()) {
break;
}
}
// Validate name...
/* Does the supplied name only contain A to Z characters
in any letter case. Add characters to the regular
expression as you see fit. (?i) means any letter case. */
if (name.matches("(?i)[A-Z. ]+")) {
// Yes, it does...
/* Ensure 'first' character of each name word (if more than one)
is upper letter case. */
String[] tmp = name.split("\\s+");
StringBuilder nme = new StringBuilder("");
for (String str : tmp) {
if (!Character.isUpperCase(str.charAt(0))) {
str = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
if (!nme.toString().isEmpty()) {
nme.append(" ");
}
nme.append(str);
}
name = nme.toString();
}
// No it doesn't so inform User of the mistake and to try again.
else {
System.err.println("Invalid " + nameTitle + " Name Supplied! (" + name + ") Try Again...");
name = ""; // Set to null string so as to re-prompt.
}
}
return name;
}
I have a program that requests the first and last names of 10 people from the console and then adds them to a Linked List under a single entity, 'fullName'. Is there a way to use Collections.sort() to sort the names based on the last name and not the first. The order of first name then last name needs to be kept. This is what I have so far:
public void requestNames(){
for(int i = 1; i < 11; i++){
// Request first name.
System.out.print("Enter first name of friend # " + i + ":");
String fName = scanner.nextLine();
// Request last name.
System.out.print("Enter last name of friend # " + i + ":");
String lName = scanner.nextLine();
// Concatenate first and last name and hold in fullName variable.
String fullName = fName + " " + lName;
myList.add(fullName);
}
scanner.close();
}
public void sortList(){
Collections.sort(myList);
}
Yes. Provided that you are using LinkedList from the Java Collections API, you can write a custom comparator for this operation.
Collections.sort(myList, new Comparator<String, String>() {
public int compare(String left, String right) {
String leftLast = String.split("\\s")[1];
String rightLast = String.split("\\s")[1];
return leftLast.compareTo(rightLast);
}
}
Graphically, create a LinkedList “Full name” of your first name and last name combined. Perform the
following operations on the LinkedList.
Split Full name into two lists, “First name” and “last name” containing your first and last
name.
Empty “last name”
Copy “First name” to “last name”.
I was wondering if there's a way to get an index, let me show you an example.
String[] names = {"Daniel", "Lewis", "Sarah", "John"};
String cmd = input.nextLine();
String CMD[] = cmd.split(" ");
if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[0])){
System.out.println("My name is Daniel!");
} else if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[1])) {
System.out.println("My name is Lewis!");
} else if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[2])) {
System.out.println("My name is Sarah!");
} else if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[3])) {
System.out.println("My name is John!");
}
Is there an easier way to do this, than nesting if statements?
Please note, I'd only want to use names inside of the table, so I can't just make a String called myName equal to CMD[1].
I suppose it's sort of like a database of usernames, if your username doesn't exist, you can't log in.
I want it like that, but without nesting loads of if statements, and the names Array would be the database in this instance.
You could do
List<String> names = Arrays.asList("Daniel", "Lewis", "Sarah", "John");
if (names.contains(CMD[3]) {
System.out.println("My name is " + CMD[0]);
} else {
// not found...
}
You are splitting on a space, so
CMD[0].equalsIgnoreCase("my name is")
will never evaluate to true.
Why are you testing for "my name is " at all? Just capture the fourth word, if that is the format you're using: CMD[3].
To avoid these if-else-if-elses, put the names into a Map where the key is the name, and the value is always null.
Then test the name against the keys:
if(mapOfNames.containsKey(CMD[3]))
You can try a for loop:
for (int i = 0; i < names.length(); i++) {
if (CMD[3].equalsIgnoreCase(accountIndex[i])) {
System.out.println("My name is " + names[i] + "!");
break;
}
}
Running cmd.split() will split the array giving you an array: {"my", "name", "is", "some_name"}. Which means that the name you want to check will be given at the fourth element in the array hence index [3].
String[] names = {"Daniel", "Lewis", "Sarah", "John"};
String cmd = input.nextLine();
String CMD[] = cmd.split(" ");
// Initial check to see if my name is exists.
if(cmd.subtstring(0, 10).equalsIgnoreCase("my name is") && cmd.length > 3)
{
// This loop is better than checking each individual case because it allows you to dynamically add elements to your names array
for(int i = 0; i < names.length; i++)
{
// Must start at the fourth element since my, name, and is will be the 0-2 elements.
if(CMD[3].equalsIgnoreCase(names[i]))
{
System.out.println("My name is "+names[i]+"!");
break;
}
}
}
You can store the valid usernames in a TreesSet and then when user enters a name you can lookup the TreeSet to test if the given name is a valid name.
TreeSet<String> validNames = new TreeSet<String>();
validNames.add("John");
validNames.add("Mary");
.....
.....
// For searching
if(validNames.contains(CMD[0]))
{
// name exists
}
else{
// invalid name
}
Note : You can store the names in any searchable collection (HashMaps are also a good choice for this scenario. This is just a pointer and you need to deep dig to find which Data structure suits your need. For more information you can refer the following links :
TreeSet
HashMap
You can convert array to list and then search for the name in the list with contains method:
if(Arrays.asList(names).contains(CMD[3]))
System.out.println("My name is " + CMD[3] + "!");