Input string:
-;Lokacija;-;Pozicija;Grad;-;-;
Code:
public static ArrayList<String> sortList = new ArrayList<String>();
//Load
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
String[] RowAsList;
RowAsList = Row.split(";");
sortList.add( RowAsList[0] );
// Check
StringBuffer minus = new StringBuffer( "-");
String itm = sortList.get(0);
if( !itm.contentEquals( minus ) )
// not minus
else
.....
Problem: this code says there is no minus on first item (0), subsequent minuses are recognized correctly.
Anyone has any ideas as to why ?
Thanks,
Kajko
Remove the static modifier before the sortList member:
public List<String> sortList = new ArrayList<String>();
Thats what you want
public class Test
{
public static ArrayList<String> sortList = new ArrayList<String>();
public static void main(String a[])
{
//Load
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
String[] RowAsList;
RowAsList = Row.split(";");
for(int i=0;i<RowAsList.length-1;i++) {
sortList.add(RowAsList[i]);
}
System.out.println(sortList);
// Check
StringBuffer minus = new StringBuffer("-");
String itm = sortList.get(0);
if( itm.contentEquals( minus ) )
System.out.println(sortList.get(0));
// not minus
else
System.out.println("not found...");
}
}
Try :
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
ArrayList<String> sortList = new ArrayList<String>();
String[] RowAsList= Row .split(";");
sortList.add( RowAsList[0]);
StringBuffer minus = new StringBuffer( "-");
String itm = sortList.get(0);
if( itm.equals( minus.toString())){
System.out.println("Get Here" + itm);
}
else{
System.out.println("Not Here"+ itm);
}
Related
I want to take a string input in
%d+%d
format in java.How do i do it?
I know that I can do this with string.split() method. But I feel that it is going to be way more complex if I had to deal with more strings in input. Like
%d+%d-%d
I am looking for solutions that are close to a scanf solution for c.
I tried this for %d+%d
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String first,second;
String[] arr = str.split("\\+");
first = arr[0];
second = arr[1];
scanner.close();
And this for %d+%d-%d+%d..........=%d-%d+%d.....+%d...
private final String[] splitLoL(String txt) {
LinkedList<String> strList1 = new LinkedList<String>();
LinkedList<String> strList2 = new LinkedList<String>();
LinkedList<String> strList3 = new LinkedList<String>();;
strList1.addAll(Arrays.asList(txt.split("\\+")));
for(String str : strList1) {
String[] proxy = str.split("-");
strList2.addAll(Arrays.asList(proxy));
}
for(String str : strList2) {
String[] proxy = str.split("=");
strList3.addAll(Arrays.asList(proxy));
}
String[] strArr = new String[strList3.size()];
for(int i = 0; i < strArr.length; i++) {
strArr[i] = new String(strList3.get(i));
}
return strArr;
}
Try this:
String str = scanner.nextLine();
List<String> str2 = new ArrayList();
Matcher m = Pattern.compile("\\d+").matcher(str);
while(m.find()) {
str2.add(m.group());
}
Or you can do the following using JDK 9+:
import java.util.Scanner;
public class ScannerTrial {
public static void main(String[] args) {
Scanner scanner = new Scanner(" 4 z zz ggg 22 e");
scanner.findAll("\\d+").forEach((e) -> System.out.println(e.group()));
}
}
This would print
4 22
I know there are other solutions out there but nothing is working for me.
Question: In my main method, I group together IDs by rating and make the rating the key and the rest of the info the value as a List. When I create the hashmap and put in the lists I can accurately print the contents of the hashmap. However, once I pass the map the evaluate method, the values are lost and I cannot iterate in the same way that I did in the main method, even though the logic is the same. I am not experienced with the Map class in java. Can somebody please help me figure out why when I pass the Map to my evaluate method that I can no longer iterate the Map?
import java.io.*;
import java.util.*;
public class Evaluate {
public static double grandTotal;
public static void main(String[] args) throws Exception {
FileInputStream fs = new FileInputStream("testInput.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileInputStream fs2 = new FileInputStream("testTest.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));
String line;
String line2;
String[] bloop;
String bleep;
String flooper;
String splitter;
String[] splitInput;
List<String> oneStarList= new ArrayList<String>();
List<String> twoStarList= new ArrayList<String>();
List<String> threeStarList= new ArrayList<String>();
List<String> fourStarList= new ArrayList<String>();
List<String> fiveStarList= new ArrayList<String>();
List<String> values2 = new ArrayList<String>();
try {
while ((line=br.readLine()) != null) {
bloop = new String[10];
bloop = line.split("\\s+");
bleep = bloop[1].toString();
flooper = (bloop[0]+" "+bloop[2]+" "+bloop[3]+" "+bloop[4]);
if (bleep.equals("1")){
oneStarList.add(flooper);
}
else if (bleep.equals("2")){
twoStarList.add(flooper);
}
else if (bleep.equals("3")){
threeStarList.add(flooper);
}
else if (bleep.equals("4")){
fourStarList.add(flooper);
}
else if (bleep.equals("5")){
fiveStarList.add(flooper);
}
grandTotal+=(Double.parseDouble(bloop[2]));
}
}
catch (Exception e){
}
Map<String,List<String>> hmap = new HashMap<String,List<String>>();
hmap.put("1",oneStarList);
hmap.put("2", twoStarList);
hmap.put("3", threeStarList);
hmap.put("4", fourStarList);
hmap.put("5", fiveStarList);
while ((line2=br2.readLine()) != null) {
splitInput = new String[5];
splitInput = line2.split("\\s+");
evaluate(splitInput[0],splitInput[1],hmap);
}
br.close();
br2.close();
}
public static void evaluate(String movID, String usrID, Map<String,List<String>> hash) throws Exception{
FileWriter fw = new FileWriter("outputTest.txt");
BufferedWriter bwr = new BufferedWriter(fw);
List<String> values = new ArrayList<String>();
List<String> outputList = new ArrayList<String>();
String[] floop;
String fleep;
int movIDtotal=0;
int usrIDtotal=0;
int totalValues=0;
double pmovIDStar=0;
double pusrIDStar=0;
double pmovID=0;
double pusrID=0;
double numID=0;
double keyTotalProb=0;
String keyOutputStr;
String keyHold;
final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();
for (String key : hash.keySet()){
values = hash.get(key);
System.out.println(key + ":");
for (int i=0;i<values.size();i++){
System.out.println(values.get(i));
floop = new String[5];
fleep = values.get(i);
floop = fleep.split("\\s+");
if (movID.equals(floop[0])){
movIDtotal++;
totalValues++;
}
if (usrID.equals(floop[0])){
usrIDtotal++;
totalValues++;
}
}
values.clear();
}
for (Map.Entry<String, List<String>> entry: entries){
values= entry.getValue();
keyHold = entry.getKey();
for (int j=0;j<values.size();j++){
floop = new String[5];
fleep = values.get(j);
floop = fleep.split("\\s+");
if (movID.equals(floop[0])){
pmovIDStar = Double.parseDouble(floop[3]);
numID = Double.parseDouble(floop[1]);
pmovID = (numID/movIDtotal);
}
if (usrID.equals(floop[0])){
pusrIDStar = Double.parseDouble(floop[3]);
numID = Double.parseDouble(floop[1]);
pusrID = (numID/usrIDtotal);
}
}
keyTotalProb = ((totalValues/grandTotal)*(pmovIDStar)*(pusrIDStar))/(pusrID*pmovID);
keyOutputStr = Double.toString(keyTotalProb);
outputList.add(keyHold);
outputList.add(keyOutputStr);
values.clear();
}
double max = Double.MIN_VALUE;
for (int m=0;m<outputList.size();m+=2){
double coolguy = Double.parseDouble(outputList.get(m+1));
int index = 0;
if(coolguy>max){
max = coolguy;
index = m;
}
try {
bwr.write(String.format("%-1s %-1s %-1s%n", movID,usrID,outputList.get(index)));
bwr.close();
fw.close();
}
catch(Exception e) {
}
}
}
}
Backup info: I'm trying to build a java program that essentially performs the final stage of the Naive Bayes algorithm to predict user ratings (1-5) for movies. I have used MapReduce to train data and now I have an input file where each line contains a string containing information in this order without the commas (movie or user id,rating , number of times rating and ID occur together in total, number of times ID occurs in total, probability that ID and rating occur together out of all ratings for ID). Essentially this is the classification stage.
never suppress excetions. especially when you do coding/debugging.
catch (Exception e){ } is very bad practice
When you do:
final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();
it does not copy hash.entrySet to entries. It creates another reference to it.
same is for values= entry.getValue();
then what do you expect after your first loop (and others too)?
when you do:
values.clear();
your values gone from the lists which are in hash and since entries is just a reference to hash.entrySet() you have what you've done - empty lists.
I have a list of strings. First element is:
2 helloworld 10173.991234
I've written the code below:
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.valueOf(subs));
}
This code shoud parse first id field and add it to arraylist.
But it fails on line idList.add(Integer.valueOf(subs));
Whats the problem? Any help?
Upd:
public class Solution {
public static void main(String[] args) throws Exception {
if (args[0].equals("-c")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileString = reader.readLine();
reader.close();
Scanner scanner = new Scanner(new File(fileString));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) {
list.add(scanner.nextLine());
}
String ne = list.get(list.size()-1);
scanner.close();
int maxId;
if (ne.length()>1) {
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.parseInt(subs));
}
maxId = idList.get(0);
for (int i:idList){
if (maxId<i){
maxId=i;
}
}
maxId++;
}
else {
maxId = 0;
}
String maxIdString = ""+maxId;
while (maxIdString.length()<8){
maxIdString+=" ";
}
if (maxIdString.length()>8){
maxIdString = maxIdString.substring(0,8);
}
String productName = "";
for (int i = 1; i < args.length-2; i++) {
productName+=args[i]+" ";
}
productName = productName.trim();
while (productName.length()<30){
productName+=" ";
}
if (productName.length()>30)
productName=productName.substring(0,30);
String price = args[args.length-2];
while (price.length()<8){
price+=" ";
}
if (price.length()>8)
price=price.substring(0,8);
String quantity = args[args.length-1];
while (quantity.length()<4){
quantity+=" ";
}
if (quantity.length()>4)
quantity=quantity.substring(0,4);
String outString = maxIdString+productName+price+quantity;
FileOutputStream outputStream = new FileOutputStream(fileString,true);
if (ne.length()>1)
outputStream.write("\r\n".getBytes());
outputStream.write(outString.getBytes());
outputStream.close();
}
}
}
It's the content of the file
2 helloworld 10173.991234
124 helloworld 10173.991234
125 helloworld 10173.991234
Program arguments, for example:
-c helloworld 10173.99 1234
I found what the problem was :) It was in UTF-8 coding. I understood it after starting to use Notepad++ application.
I am writing a program for a user to add a string to an ArrayList then display it.
It doesn't work and it seems there is a problem with compareTo().
Here is my code:
public class database {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String country[] = new String[100];
static String capital[] = new String[100];
static double population[] = new double[100];
static List<String> countriesList = Arrays.asList(country);
public static void main(String args[]) throws IOException {
country[0] = "Barbados";
country[1] = "France";
country[2] = "Nigeria";
country[3] = "USA";
country[4] = "Japan";
capital[0] = "Bridgetown";
capital[1] = "Paris";
capital[2] = "Abuja";
capital[3] = "Washington";
capital[4] = "Tokyo";
population[0] = 65.3;
population[1] = 315.8;
population[2] = 170.1;
population[3] = 2840;
population[4] = 126.7;
public static void searchCountry() throws IOException {
Scanner in = new Scanner(System.in);
String output;
int size, i;
System.out.println("Search Country:");
output = br.readLine();
boolean found = false;
for (i = 0; i < country.length; i++)
if (output.compareTo(country[i]) == 0) {
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i);
else
System.out.println(output + "Country not found, choose Add country to add it");
public static void listCountry() throws IOException {
for (String c : countriesList) {
if (!=null)
System.out.println(c);
}
}
}
There is also a problem with the null at the end of my code.
While writing code, you should better start from the beginning. i.e.
First, write class name and make sure it there is no problem with brackets
public class MyClass{
}
Then, write main method in it.
public class MyClass{
public static void main(String[] args){
}
}
Then, write your methods, and test it in main method.
public class MyClass{
public void mymethod(){
//do something
System.out.println("say something");
}
public static void main(String[] args){
MyClass mc = new MyClass();
mc.mymethod();
}
}
If you try to write everything in one shotm it wont work and if you are not expert it would be hard for you to solve problem.
You can't write a method in a method. Close the brackets of main() before you open the brackets of searchCountry()
You don't check anything against being null. Maybe you mean if(c != null)
Just write it this way and you should be fine:
public class database {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String country[] = new String[100];
static String capital[] = new String[100];
static double population[] = new double[100];
static List<String> countriesList = Arrays.asList(country);
public static void main(String args[]) {
country[0] = "Barbados";
country[1] = "France";
country[2] = "Nigeria";
country[3] = "USA";
country[4] = "Japan";
capital[0] = "Bridgetown";
capital[1] = "Paris";
capital[2] = "Abuja";
capital[3] = "Washington";
capital[4] = "Tokyo";
population[0] = 65.3;
population[1] = 315.8;
population[2] = 170.1;
population[3] = 2840;
population[4] = 126.7;
searchCountry();
listCountry();
}
public void searchCountry() throws IOException {
Scanner in = new Scanner(System.in);
String output;
int size, i;
System.out.println("Search Country:");
output = br.readLine();
boolean found = false;
for (i = 0; i < country.length; i++)
if (output.compareTo(country[i]) == 0) {
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i);
else
System.out.println(output + "Country not found, choose Add country to add it");
}
public void listCountry() {
for (String c : countriesList) {
if (c!=null)
System.out.println(c);
}
}
}
You forgot the c in c != null. You cannot define methods inside of methods in java. Also, use the equals method when testing forString equality, ie if (output.equals(country [i])).
I am having trouble putting text read from a file into an array list.
My text looks like this:
438;MIA;JFK;10:55;1092;447
638;JFK;MIA;19:45;1092;447
689;ATL;DFW;12:50;732;448 etc...
My code looks like this:
package filesexample;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
/**
*
* #author
*/
public class FilesExample {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
File file = new File ("/Schedule.txt");
try
{
Scanner scanner= new Scanner(file);;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
Scanner lineScanner= new Scanner(line);
lineScanner.useDelimiter(";");
while(lineScanner.hasNext()){
String part = lineScanner.next();
System.out.print(part + " ");
}
System.out.println();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
Some help on getting started would be much appreciated thank you!
You don't need to do the following
Scanner lineScanner= new Scanner(line);
lineScanner.useDelimiter(";");
Just do
String[] parts = line.split(";");
They all need to have there own array for each category, so flight
number will need its own array, origin its own array
I would say, don't. You don't need to have separate array for each of them.
I would rather create a class with attributes: -flight number, origin, destination, time, miles and price.
Now for every line, I would just split it on ;, and have a constructor in the class that takes an array as parameter. And rather than having separate ArrayList for each of those parameters, I would have an ArrayList of that class instance.
class Flight {
private int flightNumber;
private String origin;
private String destination;
... so on for `time, miles and price`
public Flight(String[] attr) {
this.flightNumber = Integer.parseInt(attr[0]);
this.origin = attr[1];
this.destination = attr[2];
... so on.
}
}
And then where you are using: -
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(";");
I would use String#split() to get individual attributes, and then create an ArrayList<Flight>, and add Flight instance to it: -
List<Flight> flights = new ArrayList<Flight>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] attributes = line.split(";");
flights.add(new Flight(attributes));
}
NOTE : -
You can improve upon how you instantiate your Flight class, and how you set different attributes. Since your attributes are of different types, and they are in String form, so you would need to use appropriate conversion from String to Integer or String to double which I have not considered here.
use String.split(delimiter) to split your String.
List<String> list = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
String[] strArr = line.split(";");
for(String s: strArr){
list.add(s); //adding a string into the list
System.out.println(s + " ");
}
}
System.out.println();
EDIT: From your comments
of the text I posted, the first number is flight number, origin, destination, time, miles and price. They all need to have
there own array for each category, so flight number will need its own
array, origin its own array etc.
you don't need an array for each property. create a class and name it Filght. and make your properties as instance variables.
class Flight {
private long filghtNo;
private String origin;
private dest;
private Date time;
private long miles;
private double price;
//setters and getters
}
List<Flight> list = new ArrayList<Flight>();
Flight flight = new Flight();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
Scanner scan = new Scanner(line);
if(scan.hasNextLong()){
flight.setFilgthNo(scan.nextlong());
}
else if // do the same for other properties
}
list.add(flight);
This way is more Object Oriented.
I re-iterate the need for a more OO approach but here is what you need for what you asked for.
public final class FlightInfoParser {
private static final String[] EMPTY_STRING_ARRAY = new String[]{};
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
List<String> flightNumbersList = new ArrayList<String>();
List<String> originsList = new ArrayList<String>();
List<String> destinationsList = new ArrayList<String>();
List<String> departureTimesList = new ArrayList<String>();
List<Integer> milesList = new ArrayList<Integer>();
List<Double> pricesList = new ArrayList<Double>();
String line;
while ((line = r.readLine()) != null) {
String[] fields = line.split(";");
flightNumbersList.add(fields[0]);
originsList.add(fields[1]);
destinationsList.add(fields[2]);
departureTimesList.add(fields[3]);
milesList.add(Integer.parseInt(fields[4]));
pricesList.add(Double.parseDouble(fields[5]));
}
String[] flightNumbersArray = flightNumbersList.toArray(EMPTY_STRING_ARRAY);
String[] originsArray = originsList.toArray(EMPTY_STRING_ARRAY);
String[] destinationsArray = destinationsList.toArray(EMPTY_STRING_ARRAY);
String[] departureTimesArray = departureTimesList.toArray(EMPTY_STRING_ARRAY);
int[] milesArray = new int[milesList.size()];
for (int i = 0, len = milesArray.length; i < len; ++i) {
milesArray[i] = milesList.get(i);
}
double[] pricesArray = new double[pricesList.size()];
for (int i = 0, len = pricesArray.length; i < len; ++i) {
pricesArray[i] = pricesList.get(i);
}
}
}