Daniel Avila
Daniel Avila

Reputation: 71

How to format and print multiple strings in Java

When outputting first and last, it combines them both. How would I go about making First and Last be outputted separately. I also tried add an output for the total number of characters would I declare it after the string is declared or after the Out.print it declared?

import java.util.Scanner;

class Lab2
{
    public static void main(String[] args) //header of the main method
    {
  Scanner in = new Scanner(System.in);

        String First;
        String Last;

        System.out.println("Enter you First name");
        First = in.nextLine();

        System.out.println("Enter you Last name");
        Last = in.nextLine();

        System.out.println((First) + (Last));

Upvotes: 0

Views: 4692

Answers (3)

gdsouza
gdsouza

Reputation: 9

You can just add the whitespace manually:

System.out.print(First + “ “ + Last);

Or maybe print it in different lines using “\n” :

System.out.print(First + “\n” + Last);

As for declaring your variables, it is best practice to declare them right after the class when possible:

class Lab2{
String First;
String Last;
int charCount;

public static void main(String[] args){
//code
  }
}

Though you can also declare it inside the method in this case.

To get the amount of characters you must initialize the variable that will store it after getting the input from the scanner so your code should look something like this:


import java.util.Scanner;

class Lab2
{

String First;
String Last;
int charCount;

    public static void main(String[] args) //header of the main method
    {
  Scanner in = new Scanner(System.in);

        System.out.println("Enter you First name");
        First = in.nextLine();

        System.out.println("Enter you Last name");
        Last = in.nextLine();

        System.out.println((First) + (Last));

        charCount = First.length() + Last.length();
        System.out.println(“Total number of characters = “ + charCount);
   }
}


If you are working with bigger strings that may have whitespace or input with leading/trailing spaces, there are a lot of useful methods like String.trim() and String.strip() you can find more reference here:

https://www.geeksforgeeks.org/java-string-trim-method-example/ https://howtodoinjava.com/java11/strip-remove-white-spaces/

Upvotes: 0

Light Bringer
Light Bringer

Reputation: 829

System.out.println(First + " " + Last);

Upvotes: 0

Djaouad
Djaouad

Reputation: 22766

You can use String.format:

System.out.println(String.format("%s %s", First, Last));

Alternatively, you can just add a space there manually:

System.out.println(First + ' ' + Last);

Upvotes: 1

Related Questions