How to fill an array with while loop? - java

I've a piece of code something like this and I want to insert the data by using a while.
Weather weather_data[] = new Weather[]{
new Weather(0, "Cloudy"),
new Weather(0, "Showers"),
new Weather(0, "Snow"),
new Weather(0, "Storm"),
new Weather(0, "Sunny")
};
How can I fill this list using a while ?
Thanks

Try this:
Weather weather_data[] = new Weather[5];
int i = 0;
while(i < weather_data.length){
//fill array [i]
i++;
}

I understand that you want to fill your array with the following String array as base:
String[] weatherTypes = {"Cloudy","Showers","Snow","Storm","Sunny"};
Then you can do this:
int i=0;
Weather[] weather_data = new Weather[];
for (String weatherType: weatherTypes){
weather_data[i] = new Weather(0,weatherType);
i++;
}
You could use also use a list:
List<Weather> weather_data = new ArrayList<Weather>();
for (String weatherType: weatherTypes){
weather_data.add(new Weather(0,weatherTypes));
}

Weather[] weather_data = new Weather[5];
public void addWeatherData(Weather newWeather) {
int counter = 0;
while (counter < weather_data.length) {
if (weather_data[counter] == null) {
weather_data[counter] = newWeather;
return;
}
counter++;
}
}

Related

How to put array values to another array random?

I have the array of images with a length of 6 (we call array first).I want to save this 6 values in another array with a length of 12 so that each value of the first array repeated twice in the second array and the values placed in random places of the second array .
For example : first array = {3,4,20,33,1,25}
The second array can be = {4,20,33,1,20,25,25,3,4,1,3,33}
public class PlayActivity extends AppCompatActivity {
public static boolean isTheSameOk = true;
final Random rnd = new Random();
int saverandom;
int dontsame = 0 ;
int [] allimages = {R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5,
R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10, R.drawable.img11,
R.drawable.img12, R.drawable.img13, R.drawable.img14, R.drawable.img15, R.drawable.img16, R.drawable.img17,
R.drawable.img18, R.drawable.img19, R.drawable.img20, R.drawable.img21, R.drawable.img22, R.drawable.img23,
R.drawable.img24, R.drawable.img25, R.drawable.img26, R.drawable.img27, R.drawable.img28, R.drawable.img29,
R.drawable.img30, R.drawable.img31, R.drawable.img32, R.drawable.img33, R.drawable.img34, R.drawable.img35,
R.drawable.img36, R.drawable.img37, R.drawable.img38, R.drawable.img39, R.drawable.img40};
int [] chooseimages = new int [6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
//choose 6 image from 40 image we have for putting into buttons
for(int counter = 0 ; counter<6 ; counter++){
saverandom = rnd.nextInt(39);
if(DontSameChoose(allimages[saverandom])){
chooseimages[counter] = saverandom;
}else {
counter--;
}
}
//put the select images in buttons
}
protected boolean DontSameChoose (int imageid){
for(int c = 0 ; c<6 ; c++){
if(imageid == chooseimages[c]){
isTheSameOk = false;
}
}
return isTheSameOk;
}
}
the first array is choose images that have the 6 id of the images and i want to save the values in the way i said above in the another array with the lenght of 12 .
If you transform your arrays into ArrayList, here is a short solution:
ArrayList<Integer> secondList = new ArrayList<>(firstList);
secondList.addAll(firstList);
Collections.shuffle(secondList);
Use this code
HashMap <Integer,Integer> mapa;
mapa = new HashMap<>();
int cont=0;
int arr[] = new int[12];
int arr2[] = new int[]{3,4,20,33,1,25};
for(int i=0;i<12;i++){
arr[i] = (int)Math.random()*100;
}
while(true){
int random = (int)Math.random()*12;
if(mapa.containsKey(random)){
}else{
mapa.put(random, 1);
arr[random] = arr2[cont++];
}
if(cont >= 6){
break;
}
}

Sorting array list

public class Saleitem {
public Product product = null;
public int numberofproduct = 0;
static ArrayList<Saleitem> Saleitemarray = new ArrayList<Saleitem>();
static ArrayList<Integer[]> total = new ArrayList<Integer[]>();
//read the sales data
public static void salesData() {
String SalesDataCSV = "SalesData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
System.out.println("\nThe Sales Data file has been opened\n");
try {
int currentcustomer = 1;
int lastcustomer = 1;
double sum = 0;
br = new BufferedReader(new FileReader(SalesDataCSV));
line = br.readLine();
System.out.println("-----------------------------------------------");
System.out.println("Sales Data File");
System.out.println("Customer ID, Product ID, Number of Units");
System.out.println("-----------------------------------------------");
while ((line = br.readLine()) != null) {
String field[] = line.split(cvsSplitBy);
if(field.length>1) {
String currentcustomerID = field[0];
String currentproductID = field[1];
String currentunitnumber = field[2];
Product currentproduct = null;
currentcustomer = Integer.parseInt(currentcustomerID);
int currentproductid = Integer.parseInt(currentproductID);
int currentproductunit = Integer.parseInt(currentunitnumber);
//-------------------------------------
// START OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
System.out.println(currentcustomer + " , " + currentproductid + " , " + currentproductunit);
////////////////////
if (lastcustomer == currentcustomer) {
Saleitem salesItemObject = new Saleitem(currentproductid, currentproductunit,
Product.getUnitPrice(currentproductid));
Saleitemarray.add(salesItemObject);
} else {
// sale receipt date, time, etc.
Salereceipt salesReceiptObject = new Salereceipt(lastcustomer, lastcustomer,
sum, "2/20/16", (int) (Math.random() * 2000));
Salereceipt.receipt.add(salesReceiptObject);
lastcustomer = currentcustomer;
Saleitemarray.clear();
sum = 0;
}
///////////////////////////
//Find the correct product that the customer ordered
for (int i = 0; i < Product.productData.size(); i++){
if (((Product.productData).get(i)).productID == currentproductid){
currentproduct = Product.productData.get(i);
}
}
Saleitem salesItemObject = new Saleitem(currentproduct, currentproductunit);
Saleitemarray.add(salesItemObject);
boolean found = false;
//update total
for (int i = 0; i < total.size(); i++){
//total is an array of arrays =)
//in the array, index 0 is the productID
// index 1 is the total sold of that product
//Find the correct product total
if ((total.get(i))[0] == salesItemObject.product.productID){
//if we found it then we will mark found
//so that we can add in the item if it doesnt exist
//in our total array
found = true;
//increment the total number of prodcuts sold
(total.get(i))[1] += salesItemObject.numberofproduct;
}
}
if (found == false){
Integer[] array = new Integer[2];
// index 0 = product id
// index 1 = total number of products sold
array[0] = salesItemObject.product.productID;
array[1] = salesItemObject.numberofproduct;
total.add(array);
}
//-------------------------------------
// END OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
//this is done inside of the constructor
if (currentcustomer == lastcustomer){
sum += currentproduct.productPrice * currentproductunit;
}
}
}
The Sales Data is imported from a file that has Customer_ID[0], Product_ID[1], Units_ordered[2]
I want to sort the ArrayList total by the Product_ID in ascending order. What would be the best way to do this. Im new to java so I don't know much of the syntax.
total.sort((item1, item2) -> item1.getProductId() - item2.getProductId());
You can use Collections#sort like below.
Add a getter for ProductId and you're done
Collections.sort(total, new Comparator<Saleitem>(){
#Override
public int compare(Saleitem s1, Saleitem s2) {
return s1.getProductId() - s2.getProductId();
}
});

Add the items from one list to another list in java

I have two arraylists say
ArrayList<BaseItem> normal;
ArrayList<BaseItem> highlighted;
normal = new ArrayList<BaseItem>();
highlighted = new ArrayList<BaseItem>();
what I am doing is I am Iterating through a 3rd list(called MyItems) and adding the items in it called highlight and normal to the above two lists like this.
for (Iterator<BaseItem> iterator = MyItems.iterator(); iterator.hasNext();) {
BaseItem itemtype = iterator.next();
if (itemtype.isHighlight()) {
highlighted.add(itemtype);
}
else{
normal.add(itemtype);
}
}
So my question is I want to add every 5th and 6th item of the highlited list to the list called normal .i.e elements like 5,6,11,12,17,18 and so on
and also I want to add every 6th and 7th item of normal list to highlighted list i.e 6,7,13,14 and so on.
so now my highlighted and normal lists will contain the items like this
Highlighted -> highlighted1,highlighted2,highlighted3,highlighted4,normal6,normal7 highlighted7,highlighted8.highlighted9,highlighted10,normal13,normal14 and so on
Normal -> Noraml1,normal2,normal3,normal4,normal5,highlighted5,highlighted6,normal7,normal8,normal9,normal10,normal11,normal12,highlighted11,highlighted12 and so on
Any help is always appreciated,
Thanks
If I understand, use a counter when after 5 and 6 insert in your list, add in normal list instead of highlighted list
Try this:
int highAdded = 0;
int normalAdded = 0;
for (Iterator<BaseItem> iterator = MyItems.iterator(); iterator.hasNext();) {
BaseItem itemtype = iterator.next();
if (itemtype.isHighlight()) {
highAdded++;
if (highAdded == 5) {
normal.add(itemtype);
} else if (highAdded == 6) {
normal.add(itemtype);
highAdded = 0;
} else {
highlighted.add(itemtype);
}
}
else{
normalAdded++;
if (normalAdded == 6) {
highlighted.add(itemtype);
} else if (normalAdded == 7) {
highlighted.add(itemtype);
normalAdded = 0;
} else {
normal.add(itemtype);
}
}
}
EDIT
I write this code:
public class StackOverFlowSample {
public static void main(String [] args) {
List<String> lst = new ArrayList<String>();
List<String> lstHigh = new ArrayList<String>();
List<String> lstNormal = new ArrayList<String>();
lst.add("highlighted01");
lst.add("highlighted02");
lst.add("highlighted03");
lst.add("highlighted04");
lst.add("highlighted05");
lst.add("highlighted06");
lst.add("highlighted07");
lst.add("highlighted08");
lst.add("highlighted09");
lst.add("highlighted10");
lst.add("highlighted11");
lst.add("highlighted12");
lst.add("highlighted13");
lst.add("highlighted14");
lst.add("highlighted15");
lst.add("highlighted16");
lst.add("normal01");
lst.add("normal02");
lst.add("normal03");
lst.add("normal04");
lst.add("normal05");
lst.add("normal06");
lst.add("normal07");
lst.add("normal08");
lst.add("normal09");
lst.add("normal10");
lst.add("normal11");
lst.add("normal12");
lst.add("normal13");
lst.add("normal14");
lst.add("normal15");
lst.add("normal16");
int highAdded = 0;
int normalAdded = 0;
for (Iterator<String> iterator = lst.iterator(); iterator.hasNext();) {
String itemtype = iterator.next();
if (itemtype.startsWith("highlighted")) {
highAdded++;
if (highAdded == 5) {
lstNormal.add(itemtype);
} else if (highAdded == 6) {
lstNormal.add(itemtype);
highAdded = 0;
} else {
lstHigh.add(itemtype);
}
}
else{
normalAdded++;
if (normalAdded == 6) {
lstHigh.add(itemtype);
} else if (normalAdded == 7) {
lstHigh.add(itemtype);
normalAdded = 0;
} else {
lstNormal.add(itemtype);
}
}
}
String result = "HIGHLIGHTED ARRAY: ";
for (String curr : lstHigh) {
result += curr + ", ";
}
System.out.print(result);
result = "NORMAL ARRAY: ";
for (String curr : lstNormal) {
result += curr + ", ";
}
System.out.print(result);
}
}
The output is:
HIGHLIGHTED ARRAY: highlighted01, highlighted02, highlighted03, highlighted04, highlighted07, highlighted08, highlighted09, highlighted10, highlighted13, highlighted14, highlighted15, highlighted16, normal06, normal07, normal13, normal14,
NORMAL ARRAY: highlighted05, highlighted06, highlighted11, highlighted12, normal01, normal02, normal03, normal04, normal05, normal08, normal09, normal10, normal11, normal12, normal15, normal16,
Tell me if it's OK ;)

Map key value pair in java not getting properly

i am using Map for inserting some objects, while puting object its working fine ,
but while iterating same map i m getting the size of object as correctly, but i m gettting only
last object,in all the iteration , for ur reference i am pasting all the code as follows,
package map;
Map<Integer,ListLabcar> ma = new LinkedHashMap<Integer,ListLabcar>();
ListLabcar lc = new ListLabcar();
for(int l =0;l<5;l++){
int j = 0;
for(int i = 0;i<=3;i++){
if(i==l){
System.out.println("ok");
j+=1;
lc.setIn(j);
lc.setS("a-"+l);break;
}
else{
lc.setIn(l);
lc.setS("zero-"+l);
//break;
}
}
ma.put(l, lc);
System.out.println(ma.get(l).getIn());
System.out.println(ma.get(l).getS());
}System.out.println(ma.size());
Set<Integer> ke = ma.keySet();
for(Integer k:ke){
System.out.println(k);
System.out.println("int--->"+ma.get(k).getIn());
System.out.println("sttr--->"+ma.get(k).getS());
}
}
}
This line need to be in the first for loop.
ListLabcar lc = new ListLabcar();
What you are doing is rewriting the values and not adding new objects in the map.
EDIT :
package map;
Map<Integer,ListLabcar> ma = new LinkedHashMap<Integer,ListLabcar>();
for(int l =0;l<5;l++){
ListLabcar lc = new ListLabcar();
int j = 0;
for(int i = 0;i<=3;i++){
if(i==l){
System.out.println("ok");
j+=1;
lc.setIn(j);
lc.setS("a-"+l);break;
}
else{
lc.setIn(l);
lc.setS("zero-"+l);
//break;
}
}
ma.put(l, lc);
System.out.println(ma.get(l).getIn());
System.out.println(ma.get(l).getS());
}
System.out.println(ma.size());
Set<Integer> ke = ma.keySet();
for(Integer k:ke){
System.out.println(k);
System.out.println("int--->"+ma.get(k).getIn());
System.out.println("sttr--->"+ma.get(k).getS());
}
}

Temp arrays not working after adding 3rd Item

I had to make a Temp array to keep resizing the array list if the user decides to keep adding items to the cart, but my Temp array works until I try to add 3 different items to the cart.
I was instructed to do it this way instead of an array list to show the difficulty of arrays.
orderProduct [productCount] = aProduct;
orderQuantity [productCount] = aQuantity;
}
}
You forgot to increase productCount when there is already a product in the cart.
Moreover, you can just set the product and quantity array to the temp arrays instead of copying back.
orderProduct = tempOrderedProducts;
orderQuantity = tempOrderedQuantity;
Because you forgot productCount++ after resizing the array.
The following code will work:
public void setOrderProduct(Product aProduct, int aQuantity) {
if (productCount == 0) {
orderProduct[0] = aProduct;
orderQuantity[0] = aQuantity;
} else {
Product[] tempOrderedProducts = new Product[orderProduct.length + 1];
int[] tempOrderedQuantity = new int[orderQuantity.length + 1];
for (int i = 0; i < orderProduct.length; i++) {
tempOrderedProducts[i] = orderProduct[i];
tempOrderedQuantity[i] = orderQuantity[i];
}
orderProduct = new Product[tempOrderedProducts.length];
orderQuantity = new int[tempOrderedQuantity.length];
for (int i = 0; i < orderQuantity.length; i++) {
orderProduct[i] = tempOrderedProducts[i];
orderQuantity[i] = tempOrderedQuantity[i];
}
orderProduct[productCount] = aProduct;
orderQuantity[productCount] = aQuantity;
productCount++; //you forgot this
}
}
What's more, there is a simple way to deal with array copy:
public void setOrderProduct(Product aProduct, int aQuantity) {
if (productCount == 0) {
orderProduct[0] = aProduct;
orderQuantity[0] = aQuantity;
} else {
Product[] tempOrderedProducts = new Product[orderProduct.length + 1];
int[] tempOrderedQuantity = new int[orderQuantity.length + 1];
//System.arraycopy is more convenient and efficient
System.arraycopy(orderProduct, 0, tempOrderedProducts, 0, orderProduct.length);
System.arraycopy(orderQuantity, 0, tempOrderedQuantity, 0, orderQuantity.length);
//you don't need to copy back, just re-assign the reference
orderProduct = tempOrderedProducts;
orderQuantity = tempOrderedQuantity;
orderProduct[productCount] = aProduct;
orderQuantity[productCount] = aQuantity;
productCount++;
}
}

Categories

Resources