How to print multiple variable lines in Java

前端 未结 5 1719
北荒
北荒 2021-01-03 19:38

I\'m trying to print the test data used in webdriver test inside a print line in Java

I need to print multiple variables used in a class inside a system.out.pr

相关标签:
5条回答
  • 2021-01-03 19:45

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

    This is a sample

    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 util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

    I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.

    0 讨论(0)
  • 2021-01-03 19:47

    Or try this one:

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

    Good luck!

    0 讨论(0)
  • 2021-01-03 19:52

    Suppose we have variable date , month and year then we can write it in the java like this.

    int date=15,month=4,year=2016;
    System.out.println(date+ "/"+month+"/"+year);
    

    output of this will be like below:

    15/4/2016

    0 讨论(0)
  • 2021-01-03 19:59

    You can do it with 1 printf:

    System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);
    
    0 讨论(0)
  • 2021-01-03 20:10
    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));
    
    0 讨论(0)
提交回复
热议问题