Randomizing in Java - java

I have 4 Strings to represent people and 4 Strings to represent names.
I'm trying to randomize them so that every time I start my application, my four people will have different names, but no one can have the same name during runtime.
Example:
String person_one;
String person_two;
String person_three;
String person_four;
String name_one = "Bob";
String name_two = "Jane";
String name_three = "Tim";
String name_four = "Sara";
Hope this makes some sense.

You can use Collections.shuffle():
List<String> names = new ArrayList<String>();
names.add("Bob");
names.add("Jane");
names.add("Tim");
names.add("Sara");
Collections.shuffle(names);
person_one = names.get(0);
person_two = names.get(1);
person_three = names.get(2);
person_four = names.get(3);

You can use Collections.shuffle().

Related

I want to data type Conversion in a row in android

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);
}

Use csv data as string java

This maybe simple but java isn’t really my thing but I'm working with a java API.
I need to parse a csv file and use the values as strings.
CSV file:
Mac,device,level ,key number,key function ,name,number,prim
01:1A:E8:84:9D:27,0,0,1,31,line,441865945218,TRUE
01:1A:E8:84:9D:27,0,0,2,51,dss,441865985452,FALSE
each row need to be read seprately so something like.
Read first row of csv
Assign values to strings (e.g. mac = 01:1A:E8:84:9D:27 device = 0 and so on)
Run "code" using these strings
Read second row of csv
So on till end of csv.
Thanks
I have tried csvreader but I'm not able to use the strings outside of the while function and it does not read line by line.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
while (phones.readRecord()){
String deviceID = phones.get("Mac");
String device = phones.get("device");
String level = phones.get("level");
String keynumber = phones.get("key number");
String keyfunction = phones.get("key Function");
String label = phones.get("name");
String e164 = phones.get("number");
String prim = phones.get("prim");
}
As you are new to Java, whatever you are doing, looks like it reads the file line by line. But as you are defining the Strings in while loop, you won't be able to access it outside.
If you want to read all lines and store in Strings, you should probably take array for all of them and define them outside the while loop, add values in the loop and then you'll be able to use it.
Or just create a Phone class:
public class Phone{
String deviceId;
String device;
......etc...
//setters and getters
}
And take an array of it outside while. Something like this:
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
List<Phone> phonesArr=new ArrayList<Phone>();
while (phones.readRecord())
{
Phone phone=new Phone();
phone.setDeviceId(phones.get("Mac"));
phone.setDevice(phones.get("device"));
.....
phones.add(phone);
}
// array phones will be accessible here
Hope that helps!
You have to declare the Strings outside of the loop. Otherwise the String variables would be loop scoped.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
String deviceID;
String device;
String level;
String keynumber;
String keyfunction;
String label;
String e164;
String prim;
while (phones.readRecord()){
deviceID = phones.get("Mac");
device = phones.get("device");
level = phones.get("level");
keynumber = phones.get("key number");
keyfunction = phones.get("key Function");
label = phones.get("name");
e164 = phones.get("number");
prim = phones.get("prim");
}
See:
Scopes tutorial
Javadoc: Variables
In the end I just called the funtion from the while loop.
while (phones.readRecord()) {
deviceID = phones.get("Mac");
Device = phones.get("device");
Level = phones.get("level");
Keynumber = phones.get("key number");
Keyfunction = phones.get("key function");
Label = phones.get("name");
E164 = phones.get("number");
Prim = phones.get("prim");
tools connect = new tools();
connect.connect();
connect.setkeys(deviceID,Device,Level,Label,Keynumber,Keyfunction,E164,Prim);
//System.out.println(Prim);
}
phones.close();

Java Convert List<String> to List<Object>

I've two classess CsvRead and MyOwnClass.
In CsvRead I've a method public static List getDataFromCsv(); It returns list of all data. And this data I want to take in another method in class MyOwnClass and return there as list of objects of My OwnClass
It looks like this:
List<String> dataFromCsv = new ArrayList<String>();
And in another class, I want to convert it to List<Object> of my class.
private static List<String> getDataFromCsvClass = new ArrayList<String>();
getDataFromCsvClass = CsvReader.getAllCsvData(filename);
String name = dataFromCsv[0];
String surname = dataFromCsv[1];
String birth = dataFromCsv[2];
I want to return new MyOwnClass(name, surname, birth);
MY ERROR: array required but List found: String name = allData[0]; etc
You can create a method to convert a String to MyOwnClass and use stream to map the elements, e.g.:
public static MyOwnClass convertToObject(String element){
String[] tokens = element.split(",");
return new MyOwnClass(tokens[0], tokens[1], tokens[2]);
}
//code to convert
List<String> dataFromCsv = new ArrayList<String>();
List<MyOwnClass> list = dataFromCsv.stream()
.map(e -> convertToObject(e))
.collect(Collectors.toList());
However, this may not work if let's say name or surname contains comma. In which case, I would recommend having a look at OpenCSV library and this example of how to read csv into objects.
Supposing that the list contains the name, surname and birth in every group of 3 strings (i.e., the elements on index 0, 3, 6, 9 etc. contain the name), you might try the following:
public List<MyOwnClass> convertCsvData(List<String> csv_data)
{
// Initialize result
List<MyOwnClass> result;
result = new ArrayList<MyOwnClass>();
// Parse data
int counter;
String name;
String surname;
String birth;
for (counter = 0; counter < csv_data.size(); counter += 3)
{
name = csv_data.get(counter);
surname = csv_data.get(counter + 1);
birth = csv_data.get(counter + 2);
result.add(new MyOwnClass(name, surname, birth));
}
// Done
return (result);
} // convertCsvData
Somthing like this :
private static MyOwnClass toMyOwnClass(String str){
String[] object= str.split(",");
return new MyOwnClass(object[0], object[1], object[2]);
}
List<String> dataFromCsv = new ArrayList<String>();
List<MyOwnClass> list = new ArrayList<>();
for(String string : dataFromCsv ){
if(StringUtils.isNoneEmpty(string)){
list.add(toMyOwnClass(string));
}
}
And then you return your list

Adding HashSet/Array to HashMap error

I am a beginner at Java, and I'm having trouble understanding why I'm getting an error. I have a .csv file containing cities, provinces, and respective populations of Canada. I have been trying to read the file and then put the PROVINCE and POPULATION values into a HashMap (cana) via a key/value pair. I've created a HashSet (canada) to split up the .csv, and I would like to keep that as-is if possible.
My question is about the cana.add(provSet, pop1). I am getting an "cannot find symbol - method add(java.util.Set) error around the "put", and I can't figure out why. Can someone please help me understand what I've done wrong? Since I am a beginner, additional explanation would be greatly appreciated!
String filename = "canada.csv";
try
{
BufferedReader br = new BufferedReader(new FileReader("canada.csv"));
String line = null;
HashSet<String> canada = new HashSet<String>();
HashMap<Set<String>, Set<Integer>> cana = new HashMap<Set<String>, Set<Integer>>();
while((line=br.readLine())!=null) {
String city = line.split(",")[0];
canada.add(city);
String province = line.split(",")[1];
canada.add(province);
Set<String> provSet = new HashSet<String>(Arrays.asList(province));
String population = line.split(",")[2];
canada.add(population);
int p = new Integer(population);
Set<Integer> pop1 = new HashSet<Integer>(Arrays.asList(p));
cana.add(provSet, pop1); //ERROR
//Trying to find the most populated province
String maxProvince = "";
int maxProvPop = 0;
for(String province : cana.keySet()) {
int provPop = cana.get(province);
System.out.println(population);
if( provPop > maxProvPop )
{
maxProvPop = provPop;
maxProvince = province;
}
System.out.println("The most populated province is " + maxProvince + " with a population of " + maxProvPop);
}
I think you're mixing up the methods for HashSet and HashMap. You use the add method for HashSet, and put method for HashMap.
HashSet Documentation
HashMap Documentation

Getting a part of a string in java

so, right now I have this String:
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
I want to be able to get just this part of the the string but I'm at a loss as to how to do this.
Needed Output:
String[] requiredOutput;
requiredOutput[1] = 48526; // csfo_offering
requiredOutput[2] = csfo_add_ind A;
or
requiredOutput[2] = A; // csfo_add_ind
EDIT:
I have used some of your suggestions and am trying out subString but it seems like its a temp fix because if the length of the original string changes then it will throw a wrench in my calls. I will try regex next because it seems to go by pattern matching and I might be able to figure something out with that. Thanks everyone for all your help.
Suggestions are still appreciated!
Are the numbers always the same length? If so, use String.subString. If not use String.indexOf("csfo_add") to find the locations of the "csfo_add" parts and then find the relative locations of the required information.
Hi there you can also use split if you always have the same pattern for your string.
for example
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
System.out.println(csfo.split("csfo_add_ind ")[1].split("\\]\\)")[0]);
Would get the requiredOutput[2] = A; // csfo_add_ind
and this would get the first one
String[] requiredOutput = new String[2];
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
requiredOutput[0] = "csfo_add_ind " + csfo.split("csfo_add_ind ")[1].split("\\]\\)")[0];
requiredOutput[1] = csfo.split("\\]\\[csfo_add_ind ")[0].split("csfo_offering = ")[1];
//System.out.println(requiredOutput[0] + " et " + requiredOutput[1] );

Categories

Resources