gpt4 book ai didi

java - 显示用户输入的第一个字母

转载 作者:行者123 更新时间:2023-12-01 21:53:39 27 4
gpt4 key购买 nike

例如,我有一个随机的用户输入列表。用户输入的范围可以是 1-10。然后,用户输入将入队并出队以显示用户输入列表。

但是,我想使用用户输入来显示每个用户输入的第一个字母。我尝试创建一个名为 name1 的新变量来存储用户输入,但由于 name1 变量为空,它返回错误。

for(int i =1;i<=value ;i++){
System.out.println("Enter name #" + i+":");
String name = input.next();
String name1 = name;
myQueue.enqueue(name);
}
System.out.println("List of names: ");
for(int j=1; j <=value; j++){
System.out.println(j+". " +(myQueue.dequeue()));

}
System.out.println("Statistics:");
char firstletter = name1.charAt(0); //error: value is null
System.out.println(firstletter);

最佳答案

希望这对您有帮助

import java.util.LinkedList;
import java.util.Scanner;

class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems())
list.addLast(q.dequeue());
}
}

public class myQueue {
public static void main(String[] args) {
GenQueue<Employee> empList;
empList = new GenQueue<Employee>();
GenQueue<HourlyEmployee> hList;
hList = new GenQueue<HourlyEmployee>();

Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
for(int i =1;i<=n ;i++){
System.out.println("Enter a name: ");
String name = reader.next();

hList.enqueue(new HourlyEmployee(name, name));
empList.addItems(hList);
}
System.out.println("The employees' names are:");
while (empList.hasItems()) {
Employee emp = empList.dequeue();
//System.out.println(emp.firstName + " " + emp.lastName);
char firstletter = emp.firstName.charAt(1); //error: value is null
System.out.println(firstletter);
}
}
}

class Employee {
public String lastName;
public String firstName;
public Employee() {
}
public Employee(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}

class HourlyEmployee extends Employee {
public double hourlyRate;
public HourlyEmployee(String last, String first) {
super(last, first);
}
}

关于java - 显示用户输入的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34760313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com