用户输入名字和姓氏,打印出intisials java eclipse
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18781602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User input first and last name , print out intisials java eclipse
提问by user2764700
So , im having a piece of trouble here , tried with tutorials to fix it but nothing really helped me out saw something about printout string 0,1 etc but didnt work eather.
所以,我在这里遇到了一些麻烦,尝试使用教程来修复它,但没有什么能真正帮助我看到有关打印输出字符串 0,1 等的信息,但没有成功。
What the program does atm : Asks user for first/last name and prints it out first +last name
程序在 atm 中的作用:询问用户名字/姓氏并将其打印出来
what i want it to do is print out the intisials of the users first and last name, any ideas how to fix this? Please help , Thanks in advance!
我想要它做的是打印出用户名字和姓氏的缩写,任何想法如何解决这个问题?请帮助,提前致谢!
My code looks like this atm
我的代码看起来像这个 atm
package com.example.str?ng.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String firstName,
lastName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
//obtain user input
System.out.print("Enter your first name: ");
firstName = scanner1.nextLine();
System.out.print("Enter your last name: ");
lastName = scanner1.nextLine();
//output information
System.out.print("Your first name is " + firstName + " and your last name is "+ lastName);
}
}
回答by Arjun Sol
String firstInitial = firstName.substring(0,1);
String secondInitial = lastName.substring(0,1);
回答by Moritz Petersen
You get the 21st character from a String
using String.charAt(21)
.
How to get the initials, I leave as an excercise for you.
您从String
using 中获得第 21 个字符String.charAt(21)
。如何获得首字母,我留给你作为练习。
Please note, that char
is a strange datatype in Java. It represents a character, but works like a number, that's why you get a strange number if you "concatenate" two chars. If you want to create a String out of char
s, you have some options, such as:
请注意,这char
是 Java 中一种奇怪的数据类型。它代表一个字符,但像数字一样工作,这就是为什么如果“连接”两个字符会得到一个奇怪的数字。如果你想用char
s创建一个 String ,你有一些选择,例如:
char c1;
char c2;
String str = "" + c1 + c2;
or
或者
char c1;
char c2;
String str = new String(new char[] {c1, c2});