I am having issues understanding how to create an array of n objects in Java.
This is the constructor of class ServicePath as follows:
public ServicePath(String id) {
this.id = id;
}
This is the elements of the array that I would like to create the objects.
String ServicePathArrays[] = {"SH11","SH13","SH17","SH110","SH111","SH112","SH115", ...}
I tried the following, but it creates it manually.
ServicePath[] servicePathArray = new ServicePath[ServicePathArrays.length];
For example, manually it creates the following
ServicePath[0] = new ServicePath("SH11");
ServicePath[1] = new ServicePath("SH13");
..
..
I would like to create it automatically using
String ServicePathArrays in such way:
ServicePath[0].id = "SH11";
ServicePath[1].id = "SH12";
ServicePath[2].id = "SH13";
..
..
This could be done using the functional behavior of jdk8+ :
String servicePathArray[] = {"SH11", "SH13", "SH17",
"SH110", "SH111", "SH112", "SH115"};
List<ServicePath> collection = Stream.of(servicePathArray)
.map(ServicePath::new)
.collect(Collectors.toList());
System.out.println(collection);
String ServicePathArrays[] = {"SH11","SH13","SH17","SH110","SH111","SH112","SH115", ...};
ServicePath[] servicePathArray = new ServicePath[ServicePathArrays.length];
for(int i = 0; i < ServicePathArrays.length; i++) {
servicePathArray [i] = new ServicePath(ServicePathArrays[i]);
}
Related
This question already has answers here:
Java List<string> not adding to list after Arrays.asList() has been used
(3 answers)
Closed 4 months ago.
My controller class:
#PostMapping(value = "/uniqueUrl")
#ResponseBody
public ResponseEntity<MyResponse> urlGenerator(#RequestBody MyRequest myRequest){
log.info("Request for url : ", myRequest);
MyResponse myResponse= this.generateUrlService.urlGenerator(myRequest);
log.info("generateUniqueUrl response: ", myResponse.getLongUniqueUrlList());
return ResponseEntity.accepted().body(myResponse);
}
MyRequest class:
#Data
public class MyRequestimplements Serializable {
#NotNull(message = "Url cannot be null or empty")
private String url;
#NotNull(message = "count cannot be null or empty")
private int cound;
}
My service implemantation :
#Override
public myResponse urlGenerator(MyRequest myRequest) {
log.info("urlGenerator started..");
myUrlRequestValidator.validate(myRequest);
String longUrl = myRequest.getUrl();
int count = myRequest.getCount();
List<String> uniqueUrlList = Arrays.asList(new String[count]);
for (String string : uniqueUrlList) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
MyResponse response = new MyResponse();
response.setLongUniqueUrlList(uniqueUrlList);
return response;
}
MyResponse class:
#Data
public class MyResponse extends BaseResponse {
private List<String> longUniqueUrlList;
private List<String> shortUrlList;
}
In the method where my Controller and Service class is as follows, the result of uniqueUrlList returns null. I want to add each string formed by the add method to the list, but it does not add it. Can you help me where am I going wrong?
edit1 : When I change the random url generation and adding to the list in this way, it does not enter the for loop, or when I do not change the loop and only define it as an arraylist, it gives a Null error in the add method. How can I solve this? It's such an easy thing, but I don't understand why I can't do it?
List<String> uniqueUrlList = new ArrayList<String>();
String string = null;
for ( int j = 0; j < count; j++) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
}
It is null because your List<String> uniqueUrlList is initialized with Arrays.asList which are fixed in size and unmodifiable, as specified in the Javadoc. The Arrays.asList(new String[count]) is also empty as there are no elements inside the new String[count].
Instead you should initialize it with a new ArrayList<String>():
List<String> uniqueUrlList = new ArrayList<String>();
Where you can then modify the list as you please, using a loop to add to your uniqueUrlList as many as myRequest.getCount() times.
You should initialize a list by
List<String> uniqueUrlList = new ArrayList<>();
Hi.
I'm making an app that receives data from bluetooth by using stringbuilder
And makes it slice for using another activity.
The image shows what i want to make.
Q1. What should i use c->d, d->e ?
Q2. There will be a lot of data, I want to know the way to simplify this sequence
******************** edited ********************
I have practiced by adding value to Arraylist.
But in String Array, there is no .get(), so i couldn't access to element's length.
public static ArrayList<String> randomValue = new ArrayList<>();
public static int iDistance=0, xIAngle=0, yIAngle=0, zIAngle=0;
public static String distance, xAngle, yAngle, zAngle;
randomValue.add("12345090080070");
randomValue.add("15640080085071");
randomValue.add("16542070084074");
randomValue.add("12645080087078");
randomValue.add("21345084081060");
randomValue.add("14785078075065");
randomValue.add("13155079077077");
randomValue.add("14623080078078");
randomValue.add("14918086080078");
randomValue.add("15684085082080");
for (int i=0; i<randomValue.size(); i++){
String a = randomValue.get(i);
String distance = a.substring(0,5);
String xAngle = a.substring(5,8);
String yAngle = a.substring(8,11);
String zAngle = a.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
It seems like you are just stuck on finding the equivalent of get for a string array. To access an element in an array, the syntax is array[I], so if you were using a string array, this line:
String a = randomValue.get(i);
would have been:
String a = randomValue[i];
The code for your sequence of transformations can be shortened with Streams:
// this is the sequence of transformation starting with the sting builder "a"
List<String> randomValueWithLength14 =
Arrays.stream(a.toString().split(";")).filter(x -> x.length() == 14)
.collect(Collectors.toList());
// this is the for loop shown in your code
for (int i=0; i<randomValueWithLength14.size(); i++){
String s = randomValueWithLength14.get(i);
String distance = a.substring(0,5);
String xAngle = s.substring(5,8);
String yAngle = s.substring(8,11);
String zAngle = s.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
I am attempting to take all the information that added by the user in the text fields, and then add them a 2D array. I have accomplish that by doing this:
int minorinput = JOptionPane.showConfirmDialog(frame, panel1, "Choose Minor Stats", JOptionPane.OK_CANCEL_OPTION);
if(minorinput == JOptionPane.OK_OPTION)
{
int [][] pureMR = new int [4][4];
pureMR[0][0] = Integer.parseInt(Melee.getText());
pureMR[1][0] = Integer.parseInt(Ranged.getText());
pureMR[2][0] = Integer.parseInt(RC.getText());
pureMR[3][0] = Integer.parseInt(Negotiation.getText());
pureMR[0][1] = Integer.parseInt(Dodge.getText());
pureMR[1][1]= Integer.parseInt(Perception.getText());
pureMR[2][1] = Integer.parseInt(Will.getText());
pureMR[3][1] = Integer.parseInt(Procure.getText());
pureMR[0][2] = Integer.parseInt(rideBox.getText());
pureMR[1][2] = Integer.parseInt(rideBox2.getText());
pureMR[2][2] = Integer.parseInt(artBox.getText());
pureMR[3][2] = Integer.parseInt(art2.getText());
pureMR[0][3] = Integer.parseInt(knowledgeBox.getText());
pureMR[1][3] = Integer.parseInt(knowledge2Box.getText());
pureMR[2][3] = Integer.parseInt(infoBox.getText());
pureMR[3][3] = Integer.parseInt(info2Box.getText());
But I can't figure out how to transfer the array to a different class, where it will be used in an object constructor that will allow me to print via the objects toString method.
How should I be going about transferring the 2D array from class to class?
Class I want to add the Array to:
if(pureinput == JOptionPane.OK_OPTION)
{
String name = nameBox.getText();
String age = ageBox.getText();
String gender = genderBox.getText();
String bloodType = bloodBox.getText();
String height = heightBox.getText();
String weight = weightBox.getText();
String zodiac= zodiacBox.getText();
String work = workBox.getText();
String cover = coverBox.getText();
String breed = "Pure";
String sydrome = syndrome1Box.getText();
int[] pureBS = new int[4];
pureBS[0] = Integer.parseInt(bodyBox.getText());
pureBS[1] = Integer.parseInt(senseBox.getText());
pureBS[2] = Integer.parseInt(mindBox.getText());
pureBS[3] = Integer.parseInt(skillBox.getText());
int[] pureSS = new int[6];
pureSS[0] = Integer.parseInt(mHPBox.getText());
pureSS[1] = Integer.parseInt(stockBox.getText());
pureSS[2] = Integer.parseInt(savingsBox.getText());
pureSS[3] = Integer.parseInt(initBox.getText());
pureSS[4] = Integer.parseInt(moveBox.getText());
pureSS[5] = Integer.parseInt(dashBox.getText());
String origin = orginBox.getText();
String exp = ExperienceBox.getText();
String encounter = EncounterBox.getText();
String awake = AwakeningBox.getText();
int eRate = Integer.parseInt(EncroachmentRateBox.getText());
String impulse = ImpulseBox.getText();
int eRate2= Integer.parseInt(EncroachmentRateBox2.getText());
Character pure = new Character(name,age,bloodType,gender, height,weight,zodiac,work,cover,
breed,sydrome,pureBS, pureSS,origin,exp,encounter,awake,eRate,
impulse,eRate2, //Needs a 2D array here);
System.out.println(pure.pureToString());
It creates this dialog box.
The simplest way: simply call a setter method, and pass the array into the instance:
if(minorinput == JOptionPane.OK_OPTION) {
int [][] pureMR = new int [4][4];
// code to fill array
// assuming your OtherClass has this type of setter method...
// because if it doesn't, it NEEDS one.
otherInstance.setPureMr(pureMR);
Where you get your reference to the otherInstance instance will depend totally on how your program is structured, information that we are not privy to at this moment.
Having said this, I do have to wonder if your 2D array is a kludge, if you're far better off creating a class to hold this information, and then passing an object of this class into your other instance.
I am naming all of these one by one. Is there a method that takes less space?
public class Matt{
PImage matt,
imgLS1, imgLS2, imgLS3, imgRS1, imgRS2, imgRS3,
imgLSB1, imgLSB2, imgLSB3, imgRSB1, imgRSB2, imgRSB3,
imgLW1, imgLW2, imgLW3, imgRW1, imgRW2, imgRW3,
imgLWB1, imgLWB2, imgLWB3, imgRWB1, imgRWB2, imgRWB3;
public Matt(){
imgLS1 = loadImage("./Images/Matt/MattLS1.png");
imgLS2 = loadImage("./Images/Matt/MattLS2.png");
imgLS3 = loadImage("./Images/Matt/MattLS3.png");
imgRS1 = loadImage("./Images/Matt/MattRS1.png");
imgRS2 = loadImage("./Images/Matt/MattRS2.png");
imgRS3 = loadImage("./Images/Matt/MattRS3.png");
imgLSB1 = loadImage("./Images/Matt/MattLSB1.png");
imgLSB2 = loadImage("./Images/Matt/MattLSB2.png");
imgLSB3 = loadImage("./Images/Matt/MattLSB3.png");
imgRSB1 = loadImage("./Images/Matt/MattRSB1.png");
imgRSB2 = loadImage("./Images/Matt/MattRSB2.png");
imgRSB3 = loadImage("./Images/Matt/MattRSB3.png");
imgLW1 = loadImage("./Images/Matt/MattLW1.png");
imgLW2 = loadImage("./Images/Matt/MattLW2.png");
imgLW3 = loadImage("./Images/Matt/MattLW3.png");
imgRW1 = loadImage("./Images/Matt/MattRW1.png");
imgRW2 = loadImage("./Images/Matt/MattRW2.png");
imgRW3 = loadImage("./Images/Matt/MattRW3.png");
imgLWB1 = loadImage("./Images/Matt/MattLWB1.png");
imgLWB2 = loadImage("./Images/Matt/MattLWB2.png");
imgLWB3 = loadImage("./Images/Matt/MattLWB3.png");
imgRWB1 = loadImage("./Images/Matt/MattRWB1.png");
imgRWB2 = loadImage("./Images/Matt/MattRWB2.png");
imgRWB3 = loadImage("./Images/Matt/MattRWB3.png");
}
}
Put your images in a Map<String,PImage>, organizing the map by image suffix. As far as accessing the images is concerned, this approach may be slightly less convenient/efficient than using variables directly, but it will save you a lot of space:
static final String[] suffixes = new String[] {"LS1", "LS2", "LS3", ..., "RWB3"};
Map<String,PImage> images = new HashMap<String,PImage>();
public Matt() {
for (String suffix : suffixes) {
PImage image = loadImage("./Images/Matt/Matt"+suffix+".png");
images.put(suffix, image);
}
}
Since the "LS", etc., seem to have semantic meaning, I'd suggest a variation of the solution by #dasblinkenlight that uses an enum:
final int N_FILES = 3; // files/position -- could also be a variable
enum Position {
LS, RS, LSB, RSB, LW, RW, LWB, LRB
}
Map<Position, String[]> files = new EnumMap<>(Position.class);
for (Position pos : Position.values()) {
String[] posFiles = new String[N_FILES];
files.put(pos, posFiles);
for (int i = 1; i <= N_FILES; ++i) {
posFiles[i-1] = "./Images/Matt/Matt" + pos.name() + i + ".png";
}
}
Then you can access any element with code like this:
Position p = RS; // or any other value
int index = 0; // 0..(N_FILES-1), corresponding to suffixes 1..N_FILES
String fileName = files.get(p)[i];
public static void main(String[] args)
{
String input="jack=susan,kathy,bryan;david=stephen,jack;murphy=bruce,simon,mary";
String[][] family = new String[50][50];
//assign family and children to data by ;
StringTokenizer p = new StringTokenizer (input,";");
int no_of_family = input.replaceAll("[^;]","").length();
no_of_family++;
System.out.println("family= "+no_of_family);
String[] data = new String[no_of_family];
int i=0;
while(p.hasMoreTokens())
{
data[i] = p.nextToken();
i++;
}
for (int j=0;j<no_of_family;j++)
{
family[j][0] = data[j].split("=")[0];
//assign child to data by commas
StringTokenizer v = new StringTokenizer (data[j],",");
int no_of_child = data[j].replaceAll("[^,]","").length();
no_of_child++;
System.out.println("data from input = "+data[j]);
for (int k=1;k<=no_of_child;k++)
{
family[j][k]= data[j].split("=")[1].split(",");
System.out.println(family[j][k]);
}
}
}
i have a list of family in input string and i seperate into a family and i wanna do it in double array family[i][j].
my goal is:
family[0][0]=1st father's name
family[0][1]=1st child name
family[0][2]=2nd child name and so on...
family[0][0]=jack
family[0][1]=susan
family[0][2]=kathy
family[0][3]=bryan
family[1][0]=david
family[1][1]=stephen
family[1][2]=jack
family[2][0]=murphy
family[2][1]=bruce
family[2][2]=simon
family[2][3]=mary
but i got the error as title: in compatible types
found:java.lang.String[]
required:java.lang.String
family[j][k]= data[j].split("=")[1].split(",");
what can i do?i need help
nyone know how to use StringTokenizer for this input?
Trying to understand why you can't just use split for your nested operation as well.
For example, something like this should work just fine
for (int j=0;j<no_of_family;j++)
{
String[] familySplit = data[j].split("=");
family[j][0] = familySplit[0];
String[] childrenSplit = familySplit[1].split(",");
for (int k=0;k<childrenSplit.length;k++)
{
family[j][k+1]= childrenSplit[k];
}
}
You are trying to assign an array of strings to a string. Maybe this will make it more clear?
String[] array = data.split("=")[1].split(",");
Now, if you want the first element of that array you can then do:
family[j][k] = array[0];
I always avoid to use arrays directly. They are hard to manipulate versus dynamic list. I implemented the solution using a Map of parent to a list of childrens Map<String, List<String>> (read Map<Parent, List<Children>>).
public static void main(String[] args) {
String input = "jack=susan,kathy,bryan;david=stephen,jack;murphy=bruce,simon,mary";
Map<String, List<String>> parents = new Hashtable<String, List<String>>();
for ( String family : input.split(";")) {
final String parent = family.split("=")[0];
final String allChildrens = family.split("=")[1];
List<String> childrens = new Vector<String>();
for (String children : allChildrens.split(",")) {
childrens.add(children);
}
parents.put(parent, childrens);
}
System.out.println(parents);
}
The output is this:
{jack=[susan, kathy, bryan], murphy=[bruce, simon, mary], david=[stephen, jack]}
With this method you can directory access to a parent using the map:
System.out.println(parents.get("jack"));
and this output:
[susan, kathy, bryan]