How to initiate a String array? - java

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

Related

Java copy elements in column from String array to new int array

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

How can I get the number of count each item in association rules in java?

I want to get the number of count for each item that includes rules like that,
A==>B,C,D
B==>A,C
C==>B
In these rules,
I want to get like that A=2, B=3, D=1, C=3.
public class MDSRRC {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file =new File("C:\\sar.txt");
Scanner sc = new Scanner(file);
Set<String> leftSide = new HashSet<String>();
Set<String> rightSide = new HashSet<String>();
while (sc.hasNextLine()) {
String line=sc.nextLine();
String[] lineSplited = line.split("==>");
String[] leftStrings = lineSplited[0].split(",");
for (String string : leftStrings) {
leftSide.add(string);
}
String[] rightStrings = lineSplited[1].split(" ");
for (String string : rightStrings){
if (string.length() > 0 && string.charAt(0) == '#'){
break;
}
rightSide.add(string);
}
//System.out.println(rightSide);
}
}
}
As you are counting each character no matter if it is on the left or right side, you can use just one result structure. Datatype Set is nice if you just want to know the different kind of characters that occures but you also want the count so I suggest to change your result data type to a Map so you can keep a counter for every character.
So replace leftSide and rightSide by a single Map instance and for every character you encounter, check if it exists already in your Map. If so, add one to the value part of that entry, if not put the new character to the map with value 1.
File file = new File("D:\\sar.txt");
Scanner sc = new Scanner(file);
Map<String, Integer> resultMap = new HashMap();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lineSplited = line.split("==>");
String first = lineSplited[0];
resultMap.putIfAbsent(first, 0);
resultMap.put(first, resultMap.get(first) + 1);
String[] right = lineSplited[1].split(",");
for (String a : right) {
resultMap.putIfAbsent(a, 0);
resultMap.put(a, resultMap.get(a) + 1);
}
}

how do i count occurrence of words in a line

I am fairly new to java. I want to count the occurrences of words in a particular line. So far i can only count the words but no idea how to count occurrences.
Is there a simple way to do this?
Scanner file = new Scanner(new FileInputStream("/../output.txt"));
int count = 0;
while (file.hasNextLine()) {
String s = file.nextLine();
count++;
if(s.contains("#AVFC")){
System.out.printf("There are %d words on this line ", s.split("\\s").length-1);
System.out.println(count);
}
}
file.close();
Output:
There are 4 words on this line 1
There are 8 words on this line 13
There are 3 words on this line 16
Simplest way I can think of is to use String.split("\\s"), which will split based on spaces.
Then have a HashMap containing a word as the key with the value being the number of times it is used.
HashMap<String, Integer> mapOfWords = new HashMap<String, Integer>();
while (file.hasNextLine()) {
String s = file.nextLine();
String[] words = s.split("\\s");
int count;
for (String word : words) {
if (mapOfWords.get(word) == null) {
mapOfWords.put(word, 1);
}
else {
count = mapOfWord.get(word);
mapOfWords.put(word, count + 1);
}
}
}
Implementation you requested to skip strings that contain certain words
HashMap<String, Integer> mapOfWords = new HashMap<String, Integer>();
while (file.hasNextLine()) {
String s = file.nextLine();
String[] words = s.split("\\s");
int count;
if (isStringWanted(s) == false) {
continue;
}
for (String word : words) {
if (mapOfWords.get(word) == null) {
mapOfWords.put(word, 1);
}
else {
count = mapOfWord.get(word);
mapOfWords.put(word, count + 1);
}
}
}
private boolean isStringWanted(String s) {
String[] checkStrings = new String[] {"chelsea", "Liverpool", "#LFC"};
for (String check : checkString) {
if (s.contains(check)) {
return false;
}
}
return true;
}
Try below code, it may solve your problem, in addition you can call String.toLowerCase() before you put it into the hashmap
String line ="a a b b b b a q c c";
...
Map<String,Integer> map = new HashMap<String,Integer>();
Scanner scanner = new Scanner(line);
while (scanner.hasNext()) {
String s = scanner.next();
Integer count = map.put(s,1);
if(count!=null) map.put(s,count + 1);
}
...
System.out.println(map);
Result:
{b=4, c=2, q=1, a=3}
Fastest would be store the splitted data in a ArrayList then iterate on your ArrayList and use [Collections.frequency] (http://www.tutorialspoint.com/java/util/collections_frequency.htm)
Check Guava's Multiset. Their description starts with 'The traditional Java idiom for e.g. counting how many times a word occurs in a document is something like:'. You find some code snippets how to do that without a MultiSet.
BTW: If you only wanted to count the number of words in your string, why not just count the spaces? You could use StringUtils from the apache commons. It's much better than creating an array of the split parts. Also have a look at their implementation.
int count = StringUtils.countMatches(string, " ");
In a given String, occurrences of a given String can be counted using String#indexOf(String, int) and through a loop
String haystack = "This is a string";
String needle = "i";
int index = 0;
while (index != -1) {
index = haystack.indexOf(needle, index + 1);
if (index != -1) {
System.out.println(String.format("Found %s in %s at index %s.", needle, haystack, index));
}
}

Counting the number of unique values in a vector

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

How to Split this String and store in HashMap

String str = "id1;;name1 || id2;;name2 || id3;;name3||";
into id1 name1 ...and then store it in hashmap as id1 - key , name1- value
id2 - key , name2 - value
......
One way to reach your goal is to use a StringTokenizer.
Code example:
public static void main(String[] args) {
String input = "id1;;name1 || id2;;name2 || id3;;name3||";
Map<String, String> map = new HashMap<>();
// You have to split two times
for (String outer : splitBy(input, " || ")) {
List<String> inner = splitBy(outer, ";;"); // for example: outer="id1;;name1"
// Make sure, you have two inner input-elements
if (inner.size() == 2) {
String key = inner.get(0); // First element of List = Key
String value = inner.get(1); // Second element of List = Value
map.put(key, value);
}
}
}
private static List<String> splitBy(String toSplit, String delimiter) {
List<String> tokens = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(toSplit, delimiter);
while (tokenizer.hasMoreTokens()) {
tokens.add(tokenizer.nextToken());
}
return tokens;
}
Also take a look at this: Scanner vs. StringTokenizer vs. String.Split
for this particular case you should do something like this:
Map<String, String> yourHashMap = new HashMap<String, String>();
String input = "id1;;name1 || id2;;name2 || id3;;name3||";
// "\" is special character so it need an escape
String[] yourStrings = input.split("\\|\\|");
String[] hashObject = new String[2];
for (int i = 0; i <= yourStrings.length - 1; i++) {
//fist you have to remove the whitespaces
yourStrings[i] = yourStrings[i].replaceAll("\\s+", "");
hashObject = yourStrings[i].split(";;");
yourHashMap.put(hashObject[0], hashObject[1]);
}
Your input string have a strange format, I recommend you to change it.

Categories