且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:如何在变量中插入新行?

更新时间:2023-12-03 20:27:04

在显示它之前,你必须操纵 fullName 变量。

一些事情:

 fullName = JOptionPane.showInputDialog(null, 你的全名是什么?); 

fullName = fullName.trim()。replaceFirst( \\\\ +,System.lineSeparator()); // 替换行尾字符遇到的第一个空格

JOptionPane.showMessageDialog(null, 您输入了: + System.lineSeparator()+全名);


For Example this is my code:

String fullName; // Stores fullName as a String variable

fullName = JOptionPane.showInputDialog(null,"What is your full name?");
// Creates input dialog box containing "What is your full name?"

JOptionPane.showMessageDialog(null, "You entered: " +
fullName);

I want to display the first name in its own line the last name in another line.

What I have tried:

I've tried using "\n" inside the message box, but it just takes the whole full name to a new line.

You have to manipulate the fullName variable before displaying it.
Something along:
fullName = JOptionPane.showInputDialog(null,"What is your full name?");

fullName = fullName.trim().replaceFirst("\\s+", System.lineSeparator()); // Replace the first whitespace(s) encountered by an end-of-line character

JOptionPane.showMessageDialog(null, "You entered:" + System.lineSeparator() + fullName);