I have a code in my android phone to find duplicate numbers via collections.frequency. This code works fine in a java program only on android. But not as an app on android. Here is what I have as a code in android.
ArrayList<String> ll = new ArrayList<String>();
String item = inputText.getText().toString();
ll.add(item);
HashSet<String> set = new HashSet<>(ll);
for (String temp : set)
{
answertext.setText(temp + "shows that many times: " + Collections.frequency(ll, temp));
}
The output is as follows:
33 44 33 44 shows that many times: 1
It does not find any duplicates if the numbers are input by user via textbox.
However, if a take the userinput away in the code and replace it with this input:
ll.add("33");
ll.add("44");
ll.add("33");
ll.add("44");
ll.add("24");
ll.add("24");
the output will be like so:
44 shows that many times: 2
So here with this input the collections.frequency is working to find a duplicate number. But why only one number? And why 44 and not 33? And why is it not outputting all duplicate numbers like it does as a java program only on the phone. Without Android involved?
I'd like to make it work with userinput from a textbox.
On the Java side where it works fine I got this code:
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the amount of numbers you want to input: Input numbers separated by a space.");
int n = stdin.nextInt();
for (int i = 0; i < n; i++)
{
list.add(stdin.next());
}
System.out.println("\nCount all with frequency");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet)
{
System.out.println(temp + " shows that many times : " + Collections.frequency(list, temp));
}
//Enter the amount of numbers you want to input
12 //hit the return key
22 33 44 22 33 44 22 33 44 22 33 44
//the output is like so:
Count all with frequency
33 shows that many times: 4
44 shows that many times: 4
22 shows that many times: 4
Why is this code working in Java but not on android?
String item = inputText.getText().toString();
ll.add(item);
This adds one item to the list. I'm guessing you wanted to add each word separately, which you can do like this:
// split the input apart at the spaces
String[] items = inputText.getText().toString().split(" ");
// then add each part separately to the list
for(String item : items)
ll.add(item);
Your second problem is that setText... sets the text. It doesn't add to the end of the text, it replaces what's already there. I don't know how you intended to display multiple strings, but you could do something like this:
// clear answertext
answertext.setText("");
for (String temp : set)
{
// set the text to <whatever was already there> followed by this item
answertext.setText(answertext.getText() + temp + "shows that many times: " + Collections.frequency(ll, temp) + "\n");
}
Related
I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`
I'm writing a program that reads data from a text file with various basketball sports statistics. Each line (after the two header lines) corresponds to one particular game and the scores of each team, with some other strings in there. I'm trying to use scanners to read the int scores of each game, store them in variables, and then compare them to determine which team won that game so that I can increment the wins later in the program. I figured out how to read all the ints in sequence, but I can't figure out how to read two ints in a line, store them as variables, compare them, and then move on to the next line/game.
Here is the relevant method:
public static void numGamesHTWon(String fileName)throws FileNotFoundException{
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
input1.nextLine();
input1.nextLine();
while (input1.hasNext()) {
if (input1.hasNextInt()) {
int x = input1.nextInt();
System.out.print(x);
input1.next();
} else {
input1.next();
}
}
A few lines from the text file:
NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 #Winthrop 54 O1
2007-11-11 #S Dakota St 93 UC Riverside 90 O2
2007-11-11 #Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT
read the file line by line. then split the line into a String[]. since you know where the scores are located on each line, you can then easily parse those values from the array and compare. can you please share a few lines form your input? then i can show you the exact code
you can try something like
String[] parts = str.split("\\D+");
where str is the line that you just read. now parts array will have all the numbers in your string. just read through the array, parse to int and make the comparison. note that the first three entries in this array would correspond to the date, so just ignore those.
for example
String[] parts = "2007-11-11 Mississippi St 76 Centenary 57".split("\\D+");
for (String g: parts)
System.out.println(g);
prints out
2007
11
11
76
57
so now you can just take the last two values and compare
while (input1.hasNextLine()) {
String line = input1.nextLine();
String[] parts = line .split("\\D+");
int score1 = Integer.parseInt(parts[parts.length-2]);
int score2 = Integer.parseInt(parts[parts.length-1]);
/*now compare score1 and score2 and do whatever...*/
}
The problem requires to input different values for each attribute.Ex:
Color Black White
Water Cool Hot Medium
Wind Strong Weak
I made ArrayList of ArrayList of String to store such thing as no. of values of each attribute is not fixed.The user inputs Black White and on hitting new line the program has to start taking values of NEXT attribute( Cool Hot Medium).The no. of attributes has been already specified.I followed some (almost related) answers here and wrote the following code:
ArrayList<ArrayList<String>> attributes = new ArrayList<ArrayList<String>>();
String input;
for(i=0; i<num_of_Attributes ;i++)
{ System.out.print(" Enter attribute no." + i+1 + " : ");
ArrayList<String> list = new ArrayList<String>();
while(! input.equals("\n"))
{
list.add(input);
input = sc.nextLine();
}
attributes.add(list);
}
The program prints "Enter Attribute 1 : " but even after new line it doesn't print "Enter attribute 2 : ".It goes into infinite loop. How can I achieve what the program requires to do? sc is my Scanner object.
You should read:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29
specifically the part that states:
This method returns the rest of the current line, excluding any line separator at the end
So, if the user inputs an empty line with only the line separator \n, you will read an empty line without such line separator.
Check while (!input.isEmpty()) or, even better, while (!input.trim().isEmpty())
As a more general rule, you can debug your program (or even just print input) to try to find out yourself what is the actual value you are checking.
As a quick-Hack you can do sth. like
for (i = 0; i < num_of_Attributes; i++) {
input = " ";
System.out.print(" Enter attribute no." + (i + 1) + " : ");
ArrayList<String> list = new ArrayList<String>();
while (!input.isEmpty()) {
list.add(input);
input = sc.readLine();
}
attributes.add(list);
}
not nice but it works. Please also watch out for calculating in String concaternation. In you code it will print 01, 11, 21 and so on. With brackets it will work.
I want to save multiple strings in one. Thing is, I don't know how many strings it may be.
I'm creating a program that reads calories from a text file and stores them in corresponding arrays.
Here are parts of the text:
Description of food Fat Food Energy Carbohydrate Protein Cholesterol Weight Saturated Fat
(Grams) (calories) (Grams) (Grams) (Milligrams) (Grams) (Grams)
APPLES, RAW, PEELED, SLICED 1 CUP 0 65 16 0 0 110 0.1
APPLES, RAW, UNPEELED,2 PER LB1 APPLE 1 125 32 0 0 212 0.1
APPLES, RAW, UNPEELED,3 PER LB1 APPLE 0 80 21 0 0 138 0.1
APRICOT NECTAR, NO ADDED VIT C1 CUP 0 140 36 1 0 251 0
Now for the food name, I have an array foodName. I will read the whole string until I reach an int which is the amount.
Here is what I've done so far:
Scanner input = new Scanner("Calories.txt");
while (input.hasNext()) {
String[] words = input.next().split(" ");
int lastI;
for (int i=0; i < words.length; i++) {
if (isNumeric(words[i])) {
lastI = i;
for(int j=lastI; j>=0; j++){
//What should I put here?
}
}
}
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
for the inner most for loop, I kept track of the last index so I could start from it and go backwards.
Problem 1: If I go backwards in the second line, I will copy both lines.
Problem 2: How to save all the strings of the name in one index of foodName?
All help is appreciated :)
What you are looking for in Java is called a StringBuilder. You can use this essentially like a string and keep appending onto it.
File file = new File("output.txt");
Scanner input = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
String[] words = input.nextLine().split(" ");
for (int i = 0; i < words.length; i++) {
if (isNumeric(words[i])) {
break;
}
sb.append(words[i] + " ");
}
System.out.println(sb);
sb = new StringBuilder();
}
input.close();
What this does is read the file line by line, creating an array of strings splitting the line on " ". Then, it iterates over each of the strings in the array and checks if it is a number, if it is, it will break the current loop and move onto the next line.
I had the StringBuilder print after each line, and then reset, you should replace this with whatever functionality that you want.
A couples suggestions also for you:
Use a CSV file. Separate everything with commas instead of spaces, it makes parsing extremely easy.
Use regex to check if the string is a number instead of catching exceptions, it is more elegant.
The output of this comes out a little funny because of how you formatted your file. You are parsing on " ", but you added a bunch of extra " " characters in the file to make the format look nice. This messes up your parsing very badly. BUT, this method will parse for you correctly when you fix the format of your flat file.
Output from this was: (note that each line is a separate string. You can see how the file formatting messed up the output)
Description of food Fat Food Energy Carbohydrate Protein Cholesterol Weight Saturated Fat
(Grams) (calories) (Grams) (Grams) (Milligrams) (Grams) (Grams)
APPLES, RAW, PEELED, SLICED
APPLES, RAW, UNPEELED,2 PER LB1 APPLE
APPLES, RAW, UNPEELED,3 PER LB1 APPLE
APRICOT NECTAR, NO ADDED VIT C1 CUP
I have a program that will read a text file starting on line number 29. If the line contains the words "n.a" or "Total" the program will skip those lines.
The program will get the elements [2] and [6] from the array.
I need to get element [6] of the array and print it underneath its corresponding value.
Element[2] of the array is where all the analytes are and element[6] contains the amount of each analyte.
The files that the program will read look like this:
12 9-62-1
Sample Name: 9-62-1 Injection Volume: 25.0
Vial Number: 37 Channel: ECD_1
Sample Type: unknown Wavelength: n.a.
Control Program: Anions Run Bandwidth: n.a.
Quantif. Method: Anions Method Dilution Factor: 1.0000
Recording Time: 10/2/2013 19:55 Sample Weight: 1.0000
Run Time (min): 14.00 Sample Amount: 1.0000
No. Ret.Time Peak Name Height Area Rel.Area Amount Type
min µS µS*min % mG/L
1 2.99 Fluoride 7.341 1.989 0.87 10.458 BMB
2 3.88 Chloride 425.633 108.551 47.72 671.120 BMb
3 4.54 Nitrite 397.537 115.237 50.66 403.430 bMB
4 5.39 n.a. 0.470 0.140 0.06 n.a. BMB
5 11.22 Sulfate 4.232 1.564 0.69 13.064 BMB
Total: 835.213 227.482 100.00 1098.073
The program needs to read that type of files and stores the element[6] of the array under a heading in a separate file in a folder. That file will have a heading like this:
Fluoride,Chloride,Nitrite,Sulfate,
The amount of fluoride should go under fluoride, the amount of chloride should go under chloride and so on and if there isn`t Nitrite or any other analyte it should put a zero for each analyte.
I just need to know how to match that and then I know I have to make write to the file which I will do later, but for know I need help matching.
The final output should looe like this.
The first line will be written in the textfile and then the second line will be values that will be match under its corresponding analyte like this:
Sample#,Date,Time,Fluoride,Chloride,Nitrite,Sulfate,9-62-1,10/2/2013,19:55,10.458,671.120,403.430,13.064,
Also again if an analyte isnt present on the file or it is null it should put a 0.
Here is my code:
//Get the sample#, Date and time.
String line2;
while ((line2 = br2.readLine()) != null) {
if (--linesToSkip2 > 0) {
continue;
}
if (line2.isEmpty() || line2.trim().equals("") || line2.trim().equals("\n")) {
continue;
}
if (line2.contains("n.a.")) {
continue;
}
if (line2.contains("Total")) {
continue;
}
String[] values2 = line2.split("\t");
String v = values2[2];//Stored element 2 in a string.
String v2 = values2[6];//Stored element 6 in a string.
String analytes = "Fluoride,Chloride,Nitrite,Sulfate";//Stored the analytes into an array.
if (analytes.contains(v)) {
System.out.println(v2);
}
int index2 = 0;
for (String value2 : values2) {
/*System.out.println("values[" + index + "] = " + value);*/
index2++;
}
System.out.print(values2[6] + "\b,");
/*System.out.println(values[6]+"\b,");*/
br.close();
}
Thanks in advance!
So if i understand your task right and every element is in new line.
Where is a lot of ways how to solve this, but with your code simpliest way to solve it in my opinion would be with StringBuffer.
//In your code i saw you have to arrays one of them with element name
//other with element code or smth
StringBuffer firstLine = new StringBuffer();
StringBuffer secondLine = new StringBuffer();
public static void printResult(String[] Name, String[] Code){
//First we gona make first line
//Here we are adding data before Names
firstLine.append("Stuff before Names");
for(int i =0;i<name.length;i++){
//Here we gona add all names in the list which is good
//Dont forget spaces
firstLine.append(name[i]+ " ");
}
//And same goes for second line just change loop array and data added before loop.
//And in the end this should print out your result
System.out.println(firstLine+"\n" + secondLine);
}
Call this method after all file reading is done.
Hope it helps!