gpt4 book ai didi

java - 从数组列表中提取组合字符串

转载 作者:行者123 更新时间:2023-12-01 10:23:54 24 4
gpt4 key购买 nike

我正在扫描三个不同的输入,并使用 toString 将它们转换为单个字符串。然后我想编辑各个输入。
例如:

name phoneNumber address 
sarmad 12345 myhouse

如何编辑“我的房子”?

import java.util.ArrayList;
import java.util.Scanner;

public class mainClass {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> arraylist = new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();

int choice;
String phoneNumber;
String name,address;
String format = "Empty";
int x = 1;
int flag = 0;

do{
try{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice = Integer.parseInt(input.next());

switch (choice){

case 1:{
System.out.println("Enter name ");
name = input.next();
System.out.println("Enter phone number");
phoneNumber = input.next();
System.out.println("Enter address");
address = input.next();
format = FormatObject.toString(phoneNumber, name, address);
arraylist.add(format);
flag++;
}
break;

case 2:{
System.out.println("Name Phone number Address");
System.out.println();

for(int i = 0; i < flag; i++){
System.out.println(arraylist.get(i));
}
}
break;

default:{
System.out.println("Enter right choice");
}
}
}

catch(Exception InputMismatchException){
System.out.println("Enter right choice");
}
} while(x == 1);
}
}

我的toString方法:

public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;

public String toString(){
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}

public String toString (String phone,String name,String address){
phoneNumber = phone;
nameUser = name;
addressUser = address;
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
}

最佳答案

这里你需要的是实现 setters/getters为您的属性(property)。

public class CreateFormat {
private String phoneNumber;
private String nameUser;
private String addressUser;

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public String getPhoneNumber() {
return phoneNumber;
}
// Similar set & get methods for other properties too.
}

关于java - 从数组列表中提取组合字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35437103/

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