just after a bit of help with something that I cant seem to get right.
I have the following code which displays the values in a csv file. This is working.
while(file.hasNext()){
String data = file.nextLine();
String[] values = data.split(",");
for(String index : values){
System.out.printf("%s \t", index);
}
System.out.println();
}
The code displays:
1 John Smith Engineering
2 Jim Jones Cooking
I want to take the values just from values[0] (which are the ID's - 1,2) and copy them into a new int array so I can pass this to other methods to perform searches and whatnot. Any help would be greatly appreciated.
Thanks!
Not quite sure I understand your question fully, but you can try this:
String[] str_array = {...};
int[] int_array = {...};
int_array[index] = Integer.parseInt(str_array[index]);
This way you can add a String to an int array, watch out for NumberFormatExceptions.
Edit:
ArrayList<Integer> ids = new ArrayList<>(); // IDs: 1, 43, 23...
Scanner scanner = new Scanner(System.in); // Reading from console
int input = scanner.nextInt();
if (ids.contains(input)) {
// true
} else {
// false
}
Just save values[0] into a seperate list and convert it to an array. If you know the number of ids you can directly save your ids into an array.
List<String> ids = new ArrayList<>();
while (file.hasNext()) {
String data = file.nextLine();
String[] values = data.split(",");
if (values.length >= 1) {
ids.add(values[0]);
for (String index : values) {
System.out.printf("%s \t", index);
}
}
System.out.println();
}
String[] idsArray = new Integer[ids.size()];
ids = ids.toArray(idsArray);
// use idsArray
you can try this:)
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
while(file.hasNext()){
String data = file.nextLine();
String[] values = data.split(",");
for(int key=0;key<values.size();key++){
if (!map.containsKey(key)){
map.put(key, new ArrayList<String>());
}
map.get(key).add(values[key]);
}
}
Integer[] items = new Integer[map.get(0).size()];
for (i = 0; i < map.get(0).size() ; i++) {
items[i]=Integer.valueOf(map.get(0).get(i));
}
Related
I want to take from rotatedZeros the numbers in every array, one by one, and transform it to indexes, as to retrieve the String/s from courses an put those array in finalExcelFormula . Or can anybody explain how this is done with Map.
rotatedZeros contains all posible unique numbers make un from all digits.
Ex: rotatedZeros.get(3) = [1,3,4]; I want to return from the courses ArrayList the string at indexes 1 ,3 and 4 and put this array inside finalExcelFormula array.
Obs. The numbers are always ascending !
List<Integer[]> rotatedZeros;
List<String[]> finalExcelFormula = new ArrayList<>(1023);
static List<String> courses = new ArrayList<>();
courses.add("\"Vue\"");
courses.add("\"Mathematics\"");
courses.add("\"Geography\"");
courses.add("\"Physics\"");
courses.add("\"Sport\"");
courses.add("\"Literature\"");
courses.add("\"Design\"");
courses.add("\"C++\"");
courses.add("\"Java\"");
courses.add("\"C#\"");
private void finalExcelFormula() {
for(int i = 0; i < rotatedZeros.size(); i++) {
for(int e = 0; e < rotatedZeros.get(i).length; e++){
Arrays.stream(finalExcelFormula.get(i)).toArray(courses.get(rotatedZeros.get(i)[e]));
}
}
}
to construct the finalExcelFormula, you need tto stream over the Integer[] and create corresponding String[] for them while looking up the courses, something over the lines of:
List<String[]> finalExcelFormula = rotatedZeros.stream()
.map(rotatedZeroArray -> Arrays.stream(rotatedZeroArray)
.map(courses::get)
.toArray(String[]::new))
.collect(Collectors.toList());
Even though i read your question about 4 times, i have no clue as to what you're trying to do...
so here is a rudimentary hasmap implementation ...
public static void main(String[] args) {
ArrayList<Integer[]> rotatedZeros = new ArrayList();
rotatedZeros.add(new Integer[]{1, 3, 4});
rotatedZeros.add(new Integer[]{1, 2, 5});
rotatedZeros.add(new Integer[]{1, 2, 3});
rotatedZeros.add(new Integer[]{0, 1, 2});
HashMap<Integer, String> things = new HashMap<>();
things.put(1, "vous");
things.put(2, "le");
things.put(3, "vous");
things.put(4, "couche");
things.put(5, "avec");
things.put(6, "moi");
for (Integer[] rotatedZeroArray : rotatedZeros) {
StringBuilder sb = new StringBuilder();
for (Integer integer : rotatedZeroArray) {
sb.append(things.get(integer)).append(" ");
}
System.out.println("output:" + sb.toString().trim());
}
// or weirder...
ArrayList<String> courses = new ArrayList<>();
courses.add("\"Vue\"");
courses.add("\"Mathematics\"");
courses.add("\"Geography\"");
courses.add("\"Physics\"");
courses.add("\"Sport\"");
courses.add("\"Literature\"");
courses.add("\"Design\"");
courses.add("\"C++\"");
courses.add("\"Java\"");
courses.add("\"C#\"");
HashMap<Integer, String> things2 = new HashMap();
int counter = 0;
for (String course : courses) {
things2.put(counter++, course);
}
for (Integer[] rotatedZeroArray : rotatedZeros) {
StringBuilder sb = new StringBuilder();
for (Integer integer : rotatedZeroArray) {
sb.append(things2.get(integer)).append(" ");
}
System.out.println("output:" + sb.toString().trim());
}
}
I suddenly get struck to initiate String array in the part of a program. The idea is to read String input from the Scanner and make an array of String. I wrote it as following,
Scanner sc = new Scanner(System.in);
String parts [] ;
while(sc.hasNext() ){
String str = sc.nextLine();
// the str value suppose to be *1, 2, 3, 4, 5, 99, 1, 2, 3, 4, 5*
parts = new String[] { str.split(", ")}; // need correction
}
I actually need an Integer array, but, I would better do it in next iteration using
Ingeter.valueOf(str_value)
How to write properly the String array generation inside the while loop ?
split is already returning String[] array so simply assign it to your String parts [] reference:
parts = str.split(", ");
Seeing some confusion in comments, it may be more appropriate for you to use a List, rather than an array. Here's a working example:
List parts = new ArrayList();
while (sc.hasNext())
{
String str = sc.readLine();
for (String i : str.split(", "))
{
parts.add(Integer.valueOf(Integer.parseInt(i)));
}
}
I provided the entire solution below where you can get one single element which is not in a pair.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean bol = false;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
while(sc.hasNext() ){
String str = sc.nextLine();
for (String s: str.split(", ") ){
int t = Integer.valueOf(s);
map.put(t, map.containsKey(t) ? map.get(t) + 1 : 1);
}
}
if (bol){
for (Map.Entry<Integer, Integer> entry : map.entrySet() ){
if ( entry.getValue() == 1){
System.out.println(entry.getKey());
}
}
}
else {
Iterator it = map.entrySet().iterator();
while ( it.hasNext() ){
Map.Entry pair = (Map.Entry) it.next();
if ( pair.getValue() == 1 ){
System.out.println(pair.getKey());
}
}
}
}
I have 2 arrays which values are words, each word in the first table is associated with a text (String), now each word from second table is showing how many times (int) is repeating in text (String). The expected table should to be like:
This is the code that I've written so far:
keyW = txtKeyword.getText();
search = textField.getText();
System.out.println("String for car = " + search);
System.out.println("String keyword = " + keyW);
btnUpload.setEnabled(false);
btnNewButton_1.setEnabled(false);
btnNewButton.setEnabled(false);
txtKeyword.setEnabled(false);
textField.setEditable(false);
//waitLabel.setVisible(true);
int iar = 0;
int item;
Map<String, Integer> dictionary = new HashMap<String, Integer>();
String[] searchArray = search.split(",");
String[] itemsFromArray1 = new String[searchArray.length];
//Keyword1 = ("Searched Key"+ "\r\n\t ");
//listKeys.add(Keyword1);
for (iar = 0; iar < searchArray.length; iar++) {
itemsFromArray1[iar] = searchArray[iar].trim();
Keyword1 = (searchArray[iar]);
//listKeys.add(Keyword1);
}
String[] items = keyW.split(",");
for (item = 0; item < searchArray.length; item++) {
WebDriver driver = new HtmlUnitDriver();
((HtmlUnitDriver) driver).setJavascriptEnabled(true);
driver.get("https://en.wikipedia.org/wiki/" + searchArray[item]);
tstr1 = driver.findElement(By.xpath("//*[#id='content']")).getText();
driver.quit();
String[] itemsFromArray = new String[items.length];
for (int i = 0; i < items.length; i++) {
itemsFromArray[i] = items[i].trim();
}
for (String string : itemsFromArray) {
int i = countWords(tstr1, string);
dictionary.put(searchArray[item].concat(string), i);
System.out.println("ARRAY " + dictionary);
}
}
private static int countWords(String tstr1, String string) {
tstr1 = tstr1.toLowerCase();
string = string.toLowerCase();
int posCount = 0;
String positive = string;
Pattern positivePattern = Pattern.compile(positive);
Matcher matcher = positivePattern.matcher(tstr1);
while (matcher.find()) {
posCount++;
}
return posCount;
}
I tried to achieve this with Map<String, Integer> dictionary = new HashMap<String, Integer>(); but the results (dictionary.put(searchArray[item], i);) are wrong. Can anyone give me an idea how to solve this. Thanks!
****UPDATE****
Now the results in the console is something like this:
ARRAY { boyanimal=4, catfree=18, catanimal=60, boyfree=2, catgender=0, boygender=6, windowfree=5}
ARRAY { boyanimal=4, catfree=18, catanimal=60, boyfree=2, windowanimal=4, catgender=0, boygender=6, windowfree=5}
ARRAY { boyanimal=4, catfree=18, catanimal=60, boyfree=2, windowanimal=4, catgender=0, boygender=6, windowgender=0, windowfree=5}
There are values that are repeting. How to make to show just like a table?
Try using this:
Map<String, Integer> tableMap = new HashMap<String, Integer>();
keep the key as:
tableMap.put("Word1-Search1",23);
Using this, you will always have a unique combination for each key.
I hope you don't want to store the data in a data structure? Instead you should use a 2 dimensional String array to store it.
Answering your latest update:
I think you're getting multiple copies because of this line.
dictionary.put(searchArray[item].concat(string), i);
I think the concat is being applied to the entire row of elements. I would use my debugger to analyze this and see what the value of searchArray[item] is and what the value of string is.
I have a method which takes in parameters in the form of a vector from another vector. This vector can be of the size 2, 3 or 4 elements.
I want to count the frequency of every word in that vector. For example, if the vector contained the strings : "hello", "my" , "hello" , I want to output an array that is
[2, 1] where 2 is the frequency of hello and 1 is the frequency of my.
Here is my attempt after reading a few questions on this website:
int vector_length = query.size();
int [] tf_q = new int [vector_length];
int string_seen = 0;
for (int p = 0; p< query.size(); p++)
{
String temp_var = query.get(p);
for (int q = 0; q< query.size(); q++)
{
if (temp_var == query.get(q) )
{
if (string_seen == 0)
{
tf_q[p]++;
string_seen++;
}
else if (string_seen == 1)
{
tf_q[p]++;
string_seen = 0;
query.remove(p);
}
}
}
}
System.out.print(Arrays.toString(tf_q));
What is the right direction to go?
Use a HashMap of type to track the unique string values you encounter that count each word
String[] vector // your vector
Map<String, Integer> stringMap = new HashMap<String, Integer>();
for (int i = 0; i < vector.length; i++) {
if (stringMap.containsKey(vector[i]) {
Integer wordCount = stringMap.get(vector[i]);
stringMap.put(vector[i], new Integer(wordCount + 1));
}
else {
stringMap.put(vector[i], new Integer(1));
}
}
String[] input = {"Hello", "my", "Hello", "apple", "Hello"};
// use hashmap to track the number of strings
HashMap<String, Integer> map = new HashMap<String, Integer>();
// use arraylist to track the sequence of the output
ArrayList<String> list = new ArrayList<String>();
for (String str : input){
if(map.containsKey(str)){
map.put(str, map.get(str)+1);
} else{
map.put(str, 1);
list.add(str); // if the string never occurred before, add it to arraylist
}
}
int[] output = new int[map.size()];
int index = 0;
for (String str : list){
output[index] = map.get(str);
index++;
}
for (int i : output){
System.out.println(i);
}
This should be your answer! Result is in "int[] output"
If you want to maintain the relation between each word and the frequency of that word, then I suggest that you use a HashMap instead. For example:
Map<String,Integer> histogram = new HashMap<String,Integer>();
for (String word : query)
{
Integer count = histogram.get(word);
if (count == null)
histogram.put(word,1);
else
histogram.put(word,count+1);
}
At this point, you can (for example) print each word with the corresponding frequency:
for (String word : histogram.keySet())
System.out.println(word+" "+histogram.get(word));
Or you can obtain an array which contains only the frequencies, if that's all you want:
Integer[] array = histogram.values().toArray(new Integer[histogram.size()]);
Or even a collection, which is just as useful and convenient as any native array:
Collection<Integer> collection = histogram.values();
I have
String add_data[] = new String[6];
with datas at 0,1,2,3,4,5 indexes.
Also I have
ArrayList<String> data = new ArrayList<String>();
now I need to put the values in all the indexes in add_data at data[0].
How can i do this? please guide me.
Eg. add_data[0]="a";
add_data[0]="b";
data[0] should have "ab"
use Arrays.asList(array) method to copy array to List. In your case - String[] to List<String>.
String result = "";
for (int i = 0; i < add_data.length: i++) {
result += add_data[i];
}
data.add(result);
I'm not sure to understand what you want to do, but try this :
String temp = "";
for(String s : add_data) {
temp += s;
}
data.put(temp);
You need:
Catenate all Strings from your array
Put this at 0 index in your ArrayList
Something like this:
String addData[] = new String[6];
ArrayList<String> data = new ArrayList<String>();
addData[0] = "a";
addData[1] = "b";
// 1. catenate all strings
String str = "";
for (String s : addData) {
str += (s != null)?s:"";
}
// 2. put it into 0 index in your arraylist
data.add(0, str);
System.out.println(data.get(0));