简体   繁体   中英

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

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);
System.out.println(First + " " + Last);

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM