Java:如何在变量中插入新行? [英] Java: how do I insert a new line inside a variable?

查看:84
本文介绍了Java:如何在变量中插入新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,这是我的代码:



String fullName; //将fullName存储为String变量



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

//创建包含你的全名是什么?的输入对话框。



JOptionPane.showMessageDialog(null,你输入了:+

fullName);



我想在自己的行中显示另一行中的姓氏。



我尝试了什么:



我尝试在消息框中使用\ n,但它只是将整个全名取为一个新行。

解决方案

在显示它之前,你必须操纵 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);


这篇关于Java:如何在变量中插入新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆