How to print multiple variable lines in java

I am trying to print test data used in webdriver test inside print string in Java

I need to print several variables used in a class inside the system.out.print function (printf / println / whatever).
Can you guys help me?

 public String firstname; public String lastname; firstname = "First " + genData.generateRandomAlphaNumeric(10); driver.findElement(By.id("firstname")).sendKeys(firstname); lastname = "Last " + genData.generateRandomAlphaNumeric(10); driver.findElement(By.id("lastname")).sendKeys(lastname); 

I need these printouts in a print statement as:
Name: (the value of the variable that I used)
Surname: (the value of the variable that I used)

Using what follows gives an accurate result.
But I need to reduce the number of printf lines and use a more efficient way.

 System.out.printf("First Name: ", firstname); System.out.printf("Last Name: ", lastname); 

Thanks!

+7
java println
source share
4 answers

You can do this with 1 printf :

 System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname); 
+20
source share

Or try the following:

 System.out.println("First Name: " + firstname + " Last Name: "+ lastname +"."); 

Good luck

+5
source share
 System.out.println("First Name: " + firstname); System.out.println("Last Name: " + lastname); 

or

 System.out.println(String.format("First Name: %s", firstname)); System.out.println(String.format("Last Name: %s", lastname)); 
+2
source share

You can create a Class Person with the firstName and lastName fields and define the toString() method. Here I created a util method that returns a String representation of a Person object.

This is a sample.

the main

 public class Main { public static void main(String[] args) { Person person = generatePerson(); String personStr = personToString(person); System.out.println(personStr); } private static Person generatePerson() { String firstName = "firstName";//generateFirstName(); String lastName = "lastName";//generateLastName; return new Person(firstName, lastName); } /* You can even put this method into a separate util class. */ private static String personToString(Person person) { return person.getFirstName() + "\n" + person.getLastName(); } } 

Person

 public class Person { private String firstName; private String lastName; //getters, setters, constructors. } 

I prefer a separate method to use toString() , because toString() used for debugging. stack overflow

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need a different representation of objects, so I created a util class that builds a string based on the output.

0
source share

All Articles