How to format data from EditText - java

I'm programming an app and trying to figure out how to format data from an EditText field
The data will look something like this
somename 123 445.46
somename2 56 234
somename3 34 42.65
What I want to do is move the first set of numbers to the left side
123 somename 445.46
56 somename2 234
34 somename3 42.65

Something like this will work:
public static String formatData(String str){
String[] temp = str.split(" ");
if(temp.length > 2){
return temp[1]+" "+temp[0]+" "+temp[2];
}else{
// can't perform.
return str;
}
}

Related

Finding two specific numbers in a list using string tokenizer

I'm trying to find two specific numbers (25,55) in a input list by converting them to tokens. e.g. below - string list = (52 98 55 86 42 25 87 566 56 843).
Just for context, the numbers are prices for books bought in a week for a library.
If they are both in a line only then I want to know (print "both"). If only one of them is in the line or something like 5562 or 3259 (part of another number), i want a return of "no". I guess that's why I'm converting them to tokens.
This code below is not working unless i remove the else statement and even when i do remove it, it prints out "both" no matter what I numbers i put in, even if there's no 25 or 55. Sorry if this seems like a dumb question, pretty new to coding.
package part;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
public class Part {
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
StringTokenizer tokenizer = new StringTokenizer(list);
String rp = tokenizer.nextToken();
if (rp.equals("25") && rp.equals ("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer works like ResultSet when fetching queries in DB side. Considering it, you should do something like this:
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
List<String> tokenList = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(list);
while(tokenizer.hasMoreTokens()){
tokenList.add(tokenizer.nextToken());
}
if(tokenList.contains("25") && tokenList.contains("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).
Try using below code if you want to check that the contains both of them.
String list = "52 98 55 86 42 25 87 566 56 843";
String[] strarr = list.split("\\s+");
boolean first;
boolean second;
for(String str:strarr){
if(str.equals("25")) first=true;
if(str.equals("55")) second=true;
if(first && second) break;
}
if(first && second) System.out.println("both");
else System.out.println("no");

Why do I keep receiving an inputmismatchexception on my array?

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];`

Need to print out line of array if the first word matched the user input

i have an array that contains courses that was made from a txt file:
arr[1] = CSC 110 Fundamentals of Programming I
arr[2] = PHYS 102 General Physics
arr[3] = MATH 100 Calculus I
arr[4] = CSC 167 Video Game Interaction and Design
arr[5] = ECON 103 Principles of Microeconomics
My method:
public static void listCoursesInDept(String targetDept, UvicCourse[] arr){}
takes a department name (ex: csc) and searches through the array to find a line that contains the department. If the depatement name matches the one in the array the entire line (department, number and name) gets printed.
I am wondering how I can compare the targetDept to the first word or each line in the array.
A better approach would be to store them in a map and get the value using the key.
Map<String, String> departments = new HashMap<String, String>();
String findKey = "CSC1";
departments.put("CSC", "CSC 110 Fundamentals of Programming I");
departments.put("PHYS", "PHYS 102 General Physics");
departments.put("MATH", "MATH 100 Calculus I");
if(departments.containsKey(findKey))
{
System.out.println( findKey + " --- " + departments.get(findKey));
}
else
{
System.out.println("Invalid Couse");
}
UPDATE
using arrays is similar, you have to exploit string methods.
List<String> departments = new ArrayList<String>();
String findKey = "CSC1";
departments.add("CSC 110 Fundamentals of Programming I");
departments.add("PHYS 102 General Physics");
departments.add("CSC 167 Video Game Interaction and Design");
boolean found = false;
for(String department : departments)
{
if(department.startsWith(findKey))
{
found = true;
System.out.println(department);
}
}
if(!found)
{
System.out.println("Invalid Cource");
}

Token and line processing Java

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...*/
}

Collections.frequency not working correctly in Android

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

Categories

Resources