Java Map with ArrayList weirdness - java

I need another pair of eyes, because I am missing something. This is my code:
...
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.*;
import java.nio.file.*;
public class TestMap {
private Map<String, ArrayList<String>> validCommands = new HashMap<String, ArrayList<String>>();
public TestMap( ) throws Exception {
getCommands();
}
private void getCommands() throws Exception {
Map<String,ArrayList<String>> dataMap = new HashMap<>();
String nameFile = "." + File.separator + "TestMap.txt";
FileInputStream fis = new FileInputStream( nameFile );
Scanner input = new Scanner( fis );
ArrayList<String> sub = new ArrayList<>();
while(input.hasNext()) {
String[] tt = {""};
tt[0] = input.nextLine().replace( " ", "" ).toUpperCase();
// Debug next 1 line
System.out.println( "\nRead: " + tt[0] );
CharSequence divider = ",";
sub.clear();
if( tt[0].contains( divider ) ) {
tt = tt[0].split( ",", 2 );
// Debug next 2 lines
System.out.print( "Split to " );
for( int i = 0; i<tt.length; i++ ) System.out.print( tt[i] + "/" );
if( tt.length > 1 ) {
for( int i = 1; i<tt.length; i++ ) {
sub.add( tt[i] );
}
}
}
// Debug next 2 lines
System.out.println( "\nsub is now " + sub );
System.out.println( "Now putting " + tt[0] + sub );
dataMap.put( tt[0], sub );
}
input.close();
// Debug next 3 lines
System.out.println( "\nFinal result:" );
for( String s : dataMap.keySet() ) System.out.println( s + "/" + dataMap.get( s ) );
System.out.println();
}
public static void main( String[] args ) {
try {
TestMap testmap = new TestMap();
}
catch ( Exception e ) {
System.exit( 1 );
}
}
}
...
I am using Windows and it compiles without a problem.
& 'C:\Program Files\java\jdk1.8.0_271\bin\javac' -Xlint:unchecked .\TestMap.java
The input file is:
Replace, Title, Description, Language
Create
Delete
Change, Title, Description**
The result I expect would be in the order of key, array of strings like:
DELETE/[]
CREATE/[]
CHANGE/[TITLE,DESCRIPTION]
REPLACE/[TITLE,DESCRIPTION,LANGUAGE]
The result I get (with debug print statements):
java TestMap
Read: REPLACE,TITLE,DESCRIPTION,LANGUAGE
Split to REPLACE/TITLE,DESCRIPTION,LANGUAGE/
sub is now [TITLE,DESCRIPTION,LANGUAGE]
Now putting REPLACE[TITLE,DESCRIPTION,LANGUAGE]
Read: CREATE
sub is now []
Now putting CREATE[]
Read: DELETE
sub is now []
Now putting DELETE[]
Read: CHANGE,TITLE,DESCRIPTION
Split to CHANGE/TITLE,DESCRIPTION/
sub is now [TITLE,DESCRIPTION]
Now putting CHANGE[TITLE,DESCRIPTION]
Final result:
DELETE/[TITLE,DESCRIPTION]
CREATE/[TITLE,DESCRIPTION]
CHANGE/[TITLE,DESCRIPTION]
REPLACE/[TITLE,DESCRIPTION]
Why am I getting the same ArrayList for all keys?

Put ArrayList sub = new ArrayList<>(); inside the loop, you are updating the same array. That is causing the issue. If you notice you are using the same array and clearing the array also putting the same array reference inside the map value. so the map value will contain the last value of array for all keys.
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.*;
import java.nio.file.*;
public class TestMap {
private Map<String, ArrayList<String>> validCommands = new HashMap<String, ArrayList<String>>();
public TestMap( ) throws Exception {
getCommands();
}
private void getCommands() throws Exception {
Map<String,ArrayList<String>> dataMap = new HashMap<>();
String nameFile = "." + File.separator + "TestMap.txt";
FileInputStream fis = new FileInputStream( nameFile );
Scanner input = new Scanner( fis );
while(input.hasNext()) {
ArrayList<String> sub = new ArrayList<>();
String[] tt = {""};
tt[0] = input.nextLine().replace( " ", "" ).toUpperCase();
// Debug next 1 line
System.out.println( "\nRead: " + tt[0] );
CharSequence divider = ",";
if( tt[0].contains( divider ) ) {
tt = tt[0].split( ",", 2 );
// Debug next 2 lines
System.out.print( "Split to " );
for( int i = 0; i<tt.length; i++ ) System.out.print( tt[i] + "/" );
if( tt.length > 1 ) {
for( int i = 1; i<tt.length; i++ ) {
sub.add( tt[i] );
}
}
}
// Debug next 2 lines
System.out.println( "\nsub is now " + sub );
System.out.println( "Now putting " + tt[0] + sub );
dataMap.put( tt[0], sub );
}
input.close();
// Debug next 3 lines
System.out.println( "\nFinal result:" );
for( String s : dataMap.keySet() ) System.out.println( s + "/" + dataMap.get( s ) );
System.out.println();
}
public static void main( String[] args ) {
try {
TestMap testmap = new TestMap();
}
catch ( Exception e ) {
System.exit( 1 );
}
}
}

Related

How would I compare jumbled words to dictionary words in two files using HashMaps in Java?

So I constructed some simple code to compare two text files. One with a jumbled list of words that are supposed to match up to words in the dictionary file. Basically finding which jumbled words match to their dictionary word. Some words have a few jumbled words that match to them, some don't have any matches. I'm looking to change this code to be much simpler, using HashMaps to make the program simpler and faster, but I'm not very good with HashMaps at all and could use the help.
Here is the code I currently have for the non-hashmap version if it helps:
import java.util.*;
import java.io.*;
public class Project6
{
public static void main(String[] args) throws Exception
{
if (args.length < 2 ) die( "Must give name of two input files on cmd line." );
BufferedReader dFile = new BufferedReader( new FileReader( args[0] ) );
BufferedReader jFile = new BufferedReader( new FileReader( args[1] ) );
ArrayList<String> jWordList= new ArrayList<String>();
ArrayList<String> dWordList= new ArrayList<String>();
long startTime = System.currentTimeMillis();
while (dFile.ready())
{
String word = dFile.readLine();
dWordList.add( word );
}
dFile.close();
while (jFile.ready())
{
String word = jFile.readLine();
jWordList.add( word );
}
jFile.close();
Collections.sort( dWordList );
Collections.sort( jWordList );
String[] dArray = dWordList.toArray(new String[dWordList.size()]);
String[] jArray = jWordList.toArray(new String[jWordList.size()]);
dArray = canonArray( dArray );
jArray = canonArray( jArray );
for(int i = 0 ; i < jWordList.size() ; i++)
{
String jWord = jArray[i];
System.out.print(jWordList.get(i) + " ");
for(int c = 0 ; c < dWordList.size() ; c++)
{
String dWord = dArray[c];
if(jWord.equals(dWord))
{
System.out.print(dWordList.get(c) + " ");
}
}
System.out.println();
}
long endTime = System.currentTimeMillis();
long ms = endTime-startTime;
System.out.println("Elapsed time in seconds: " + ms/1000.0 + "\n"); // 1 ms is a 1,000th of a second
}
private static void die( String errmsg )
{
System.out.println( "\nFATAL ERROR: " + errmsg + "\n" );
System.exit(0);
}
private static String toCanonical( String word )
{
char[] charArray = word.toCharArray();
Arrays.sort(charArray);
String charNewString = new String(charArray);
return charNewString;
}
private static String[] canonArray( String[] Arr )
{
String[] newArr = new String[Arr.length];
for(int i = 0 ; i < Arr.length ; i++)
{
String temp = toCanonical(Arr[i]);
newArr[i] = temp;
}
return newArr;
}
}
It produces the following output, which I would like to keep exactly the same (minus the print of elapsed time):
What you want is to define a HashMap such that the key's hash and equals method will come out the same regardless of the order and case of the string's characters. The following takes a String and converts it to lowercase and sorts the characters.
import java.util.*;
import java.io.*;
public class Project6 {
public static void main(String[] args) throws Exception {
if (args.length < 2) die("Must give name of two input files on cmd line.");
BufferedReader dFile = new BufferedReader(new FileReader(args[0]));
BufferedReader jFile = new BufferedReader(new FileReader(args[1]));
HashMap<String, List<String>> dWordMap = new HashMap<String, List<String>>();
long startTime = System.currentTimeMillis();
while (dFile.ready()) {
String word = dFile.readLine();
if (word == null) break;
addWord(word, dWordMap);
}
dFile.close();
while (jFile.ready()) {
String jWord = jFile.readLine();
if (jWord == null) break;
List<String> dWords = dWordMap.get(createKey(jWord));
if (dWords != null) {
System.out.println(jWord + " " + dWords);
}
}
jFile.close();
long endTime = System.currentTimeMillis();
long ms = endTime - startTime;
System.out.println("Elapsed time in seconds: " + ms / 1000.0 + "\n");
}
private static void die(String errmsg) {
System.out.println("\nFATAL ERROR: " + errmsg + "\n");
System.exit(0);
}
private static String createKey(String word) {
char[] chword = word.toLowerCase().toCharArray();
Arrays.sort(chword);
return new String(chword);
}
private static void addWord(String word, Map<String, List<String>> map) {
String key = createKey(word);
List<String> list = map.get(key);
if(list==null) {
list = new ArrayList<String>();
map.put(key, list);
}
list.add(word);
}
}

What is Java result:3? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently learning programming (java) and I've been using a program that runs on command prompt but as an exercise, I've been asked to run it on netbeans and to find out how it can work on it. When I run the program this is the output that I got.
run:
Please specify a path to a pricing catalogue file
Java Result: 3
BUILD SUCCESSFUL (total time: 0 seconds)
I've spent several hours on this issue but I was not able to sort it out. Can anybody help me with it please.
Here is the codes.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class Grocery {
private static Catalogue pricingCatalogue;
private static HashMap<String, Double> inputItemList = new HashMap<String, Double>();
private static ArrayList<PurchasedProduct> purchasedItemList;
public static void main(String[] args) {
if( args.length != 1 )
{
System.err.println( "" );
System.exit( 3 );
}
generateCatalogue( args[0] );
gatherUserInput();
rateItem();
printItemizedBill();
}
private static void generateCatalogue( String inputFile ) {
try {
List<String> lines = Files.readAllLines(
Paths.get(inputFile),
Charset.defaultCharset() );
pricingCatalogue = new Catalogue();
Boolean compareIgnoreCase = false;
for (String line : lines) {
StringTokenizer token = new StringTokenizer( line, "|" );
String productName = (String)token.nextElement();
String rateName = (String)token.nextElement();
String rateDescr = (String)token.nextElement();
Double effectiveQuantity = new Double( (String)token.nextElement() );
Double effectivePrice;
String tierPrice;
Rate newRate;
Product newProduct;
if( effectiveQuantity == -1 )
{
tierPrice = (String)token.nextElement();
newRate = new Rate( rateName, rateDescr, tierPrice );
}
else
{
effectivePrice = new Double( (String)token.nextElement() );
newRate = new Rate( rateName, rateDescr, effectiveQuantity, effectivePrice );
}
if( true == pricingCatalogue.productIsInCatalogue( productName, compareIgnoreCase ) )
{
pricingCatalogue.addRateToExistingProduct( productName, newRate );
}
else
{
newProduct = new Product( productName );
newProduct.addRate( newRate );
pricingCatalogue.addProduct( newProduct );
}
} // end reading input file
}
catch (IOException e) {
e.printStackTrace();
}
//pricingCatalogue.printCatalogue();
System.out.println( "Price catalogue loaded sucessfully from [" + inputFile + "]\n" );
}
private static void gatherUserInput()
{
BufferedReader br = new BufferedReader(new InputStreamReader( System.in ) );
String inStr = new String();
String magicWord = "CHECK OUT";
Boolean readyToCheckOut = false;
Boolean compareIgnoreCase = false;
StringTokenizer item_tok = null;
String tok = null;
String itemName = new String();
Double itemQuantity = new Double( 0 );
inputItemList.clear();
System.out.println( "Please enter an item with quantity in a format like '2 apple'" );
System.out.println( "When you are done entering item(s), type 'CHECK OUT' to get an itemized bill" );
while( false == readyToCheckOut )
{
System.out.print( ">> ");
try {
inStr = br.readLine();
}catch( IOException ioe ) {
System.err.println("Failed to read line item");
}
item_tok = new StringTokenizer( inStr );
while( false == inStr.equals( magicWord )
&&
true == item_tok.hasMoreTokens() )
{
try
{
tok = item_tok.nextElement().toString();
itemQuantity = new Double( tok );
tok = item_tok.nextElement().toString();
}
catch( NumberFormatException nfe )
{
System.err.println( "[" + tok + "] is not something I recognize. Try something like '2 apple'" );
break;
}
catch( Exception e )
{
System.err.println( "Oops I did not understand that. Try something like '2 apple'" );
break;
}
itemName = tok;
//System.out.println( "--- ITEM [" + itemName + "] QUANTITY [" + ItemQuantity + "]" );
if( false == pricingCatalogue.productIsInCatalogue( itemName, compareIgnoreCase ) )
{
System.err.println( "Item [" + itemName + "] does not exist in the catalogue" );
continue;
}
if( true == inputItemList.containsKey( itemName ) ) {
itemQuantity = itemQuantity + inputItemList.get( itemName );
inputItemList.remove( itemName );
inputItemList.put( itemName, itemQuantity );
}
else {
inputItemList.put( itemName, itemQuantity );
}
}
if( true == inStr.equals( magicWord ) ) {
readyToCheckOut = true;
}
}
//System.out.println( "inputItemList [" + inputItemList + "]" );
}
private static void rateItem()
{
purchasedItemList = new ArrayList<PurchasedProduct>();
Product aProduct;
Rate bestRate;
PurchasedProduct pp;
double purchasedQuantity = 0;
for( Map.Entry<String, Double> entry : inputItemList.entrySet() )
{
String prodName = entry.getKey();
Double prodQuantity = entry.getValue();
aProduct = pricingCatalogue.getProduct( prodName );
bestRate = aProduct.getBestRate( prodQuantity );
purchasedQuantity = bestRate.getEffectiveQuantity();
pp = new PurchasedProduct( prodName, purchasedQuantity, bestRate );
purchasedItemList.add( pp );
prodQuantity = prodQuantity - purchasedQuantity;
/*
* Keep finding the best rate for the same product until we
* have filled the quantity
*/
while( prodQuantity > 0 )
{
bestRate = aProduct.getBestRate( prodQuantity );
purchasedQuantity = bestRate.getEffectiveQuantity();
pp = new PurchasedProduct( prodName, purchasedQuantity, bestRate );
purchasedItemList.add( pp );
prodQuantity = prodQuantity - purchasedQuantity;
}
}
}
private static void printItemizedBill()
{
PurchasedProduct pp = null;
Double totalDue = new Double( 0 );
Double lineTotal = new Double( 0 );
System.out.println( "\nHere is your invoice:" );
Iterator ite = purchasedItemList.iterator();
while( ite.hasNext() )
{
pp = (PurchasedProduct)ite.next();
lineTotal = pp.getPurhcasedCost();
System.out.format( "%10s%20s%10.2f\n", pp.getPurchasedProductName(), pp.getPurchasedRateDescr(), lineTotal );
totalDue += lineTotal;
}
System.out.format( "\n%10s%20s$%9.2f\n", "TOTAL DUE", "", totalDue );
}
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class Catalogue
{
private ArrayList<Product> productList;
Catalogue()
{
this.productList = new ArrayList<Product>();
}
/*
* Returns a boolean if a product exists in the catalogue. Use the second
* argument to set whether the comparsion should take case-sensitivity into accoun
*
*/
public boolean productIsInCatalogue( String inProdName, Boolean compareIgnoreCase )
{
HashSet<String> currentProductSet = new HashSet<String>();
/*
* Get list of pricing product names
*/
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
if( true == compareIgnoreCase )
{
currentProductSet.add( ( (Product)ite.next() ).getProductName().toUpperCase() );
}
else
{
currentProductSet.add( ( (Product)ite.next() ).getProductName() );
}
}
if( true == compareIgnoreCase )
{
return currentProductSet.contains( inProdName.toUpperCase() );
}
else
{
return currentProductSet.contains( inProdName );
}
}
public void addProduct( Product inProduct )
{
this.productList.add( inProduct );
}
public void addRateToExistingProduct( String inExistingProdName, Rate inRate )
{
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
Product currentProd = (Product)ite.next();
String currentProdName = currentProd.getProductName();
if( 0 == currentProdName.compareTo( inExistingProdName ) )
{
currentProd.addRate( inRate );
break;
}
}
}
public Product getProduct( String inExistingProdName )
{
Product foundProduct = null;
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
Product aProduct = (Product)ite.next();
if( true == aProduct.getProductName().equals( inExistingProdName ) )
{
foundProduct = aProduct;
break;
}
}
return foundProduct;
}
public void printCatalogue()
{
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
( (Product)ite.next() ).printProduct();
}
}
}
import java.util.HashSet;
import java.util.Iterator;
public class Product
{
private String productName;
private HashSet <Rate> productRate;
Product()
{
this( "N/A" );
}
Product( String inProductName )
{
this.productName = inProductName;
this.productRate = new HashSet <Rate>();
}
/*
* Add a rate to this product
*/
public void addRate( Rate inRate )
{
this.productRate.add( inRate );
}
public void printProduct()
{
System.out.println( "*** PRODUCT NAME [" + this.productName + "] ***\n" );
if( this.productRate.size() > 0 )
{
Iterator ite = this.productRate.iterator();
while( ite.hasNext() )
{
((Rate)ite.next()).printRate();
}
}
else
{
System.out.println( "This product does not have rates defined");
}
System.out.println( "" );
}
public String getProductName()
{
return this.productName;
}
public Rate getBestRate( Double inQuantity )
{
Rate lowestRate = null;
HashSet <Rate> applicableRate = new HashSet <Rate>();
Iterator ite = this.productRate.iterator();
while( ite.hasNext() )
{
Rate aRate = (Rate)ite.next();
if( inQuantity >= aRate.getEffectiveQuantity() )
{
applicableRate.add( aRate );
}
}
/*
* Amongst the available rates, pick the rate with
* the lowest cost per unit
*/
ite = applicableRate.iterator();
while( ite.hasNext() )
{
Rate appRate = (Rate)ite.next();
if( null == lowestRate )
{
/*
* Handle first time entering the loop
*/
lowestRate = appRate;
}
if( lowestRate.getCostPerUnit() > appRate.getCostPerUnit() )
{
lowestRate = appRate;
}
}
return lowestRate;
}
}
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PurchasedProduct
{
private String purchasedProdName;
private double purchasedQuantity;
private Rate purchasedRate;
private double purchasedCost;
PurchasedProduct( String inProdName, double inQuantity, Rate inRate )
{
//this.purchasedProdName = Character.toUpperCase( inProdName.charAt(0) ) + inProdName.substring( 1 );
this.purchasedProdName = inProdName;
this.purchasedQuantity = inQuantity;
this.purchasedRate = inRate;
this.purchasedCost = this.getCost();
}
public String getPurchasedProductName()
{
return this.purchasedProdName;
}
public String getPurchasedRateDescr()
{
return this.purchasedRate.getRateDescr();
}
public double getPurhcasedCost()
{
return this.purchasedCost;
}
private double getCost()
{
double lineCost = 0;
if( false == this.purchasedRate.isTiered() )
{
lineCost = this.purchasedRate.getEffectivePrice();
}
else
{
lineCost = this.purchasedRate.getTierPrice( new Double( this.purchasedQuantity ) );
}
return round( lineCost, 2 );
}
private double round( double value, int places )
{
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
/*
* Rate class represents the detail on how to rate a specific product
* A product may have many rates
*/
public class Rate
{
private String rateName;
private String rateDescr; // bill invoice display
private double effectiveQuantity; // the total quantity applicable to take advantage of this rate
private double effectivePrice; // the total price applicable
private double costPerUnit; // average cost per unit
private ArrayList<Map> tiers; // ONLY applicable if this is tierd pricing
Rate()
{
this( "N/A", "N/A", 0, 0 );
}
/*
* Non-tier rate constructor
*/
Rate( String inRateName, String inRateDesc, double inEffQ, double inEffPr )
{
this.rateName = inRateName;
this.rateDescr = inRateDesc;
this.effectiveQuantity = inEffQ;
this.effectivePrice = inEffPr;
this.tiers = new ArrayList<Map>();
this.costPerUnit = this.getCostPerUnit();
}
/*
* Tier rate constructor
*/
Rate( String inRateName, String inRateDesc, String tier_val )
{
this.rateName = inRateName;
this.rateDescr = inRateDesc;
this.effectiveQuantity = -1; // this is calculated later in getCostPerUnit
this.effectivePrice = -1;
this.tiers = new ArrayList<Map>();
/*
* Example tier_val "1-1,0.50,1;2-2,0.50,0.50"
* Each tier is separated by ';'
* A token within a tier is operated by ','
*/
StringTokenizer more_tiers = new StringTokenizer( tier_val, ";" );
while( more_tiers.hasMoreTokens() )
{
StringTokenizer tier_detail = new StringTokenizer( (String)more_tiers.nextElement(), "," );
Map<String, Double> tier_map = new HashMap<String, Double>();
/*
* First token is the min to max quantity e.g. 1-1 or 1-5
*/
String[] minMaxVal = tier_detail.nextElement().toString().split("-");
tier_map.put( "MIN", new Double( minMaxVal[0] ) );
tier_map.put( "MAX", new Double( minMaxVal[1] ) );
/*
* Second token is the quantity price per unit so 1.50 mean charge each unit for 1.50
*/
tier_map.put( "PRICE", new Double( (String)tier_detail.nextElement() ) );
/*
* Third token is the discount scale, e.g 1 means 100% no discount and 0.5 means 50% discount
*/
tier_map.put( "SCALE", new Double( (String)tier_detail.nextElement() ) );
tiers.add( tier_map );
}
this.costPerUnit = this.getCostPerUnit();
}
public String getRateDescr()
{
return this.rateDescr;
}
public double getEffectiveQuantity()
{
return this.effectiveQuantity;
}
public double getEffectivePrice()
{
return this.effectivePrice;
}
public Boolean isTiered()
{
return ( this.effectivePrice == -1 );
}
/*
* Calculate the total cost with the input quantity
*/
public double getTierPrice( double inQuantity )
{
Iterator ite = this.tiers.iterator();
Double min = new Double( 0 );
Double max = new Double( 0 );
Double price = new Double( 0 );
Double scale = new Double( 0 );
Double total_cost = new Double( 0 );
Double total_quan = new Double( 0 );
Double tierMaxQ = new Double( 0 );
Double toRateQuan = new Double( inQuantity );
/*
* Step through each tier
*/
while( ite.hasNext() )
{
Map tier_map = (Map)ite.next();
min = (Double)tier_map.get( "MIN" );
max = (Double)tier_map.get( "MAX" );
price = (Double)tier_map.get( "PRICE" );
scale = (Double)tier_map.get( "SCALE" );
/*
* Get the tier applicable units
*/
tierMaxQ = max - min + 1;
if( 0 >= toRateQuan )
{
break;
}
else if( toRateQuan >= tierMaxQ )
{
/*
* The incoming to-to-rated quantity is greater than
* the tier total units. Rate it with the
* maximum units in this tier
*/
total_cost = total_cost + ( tierMaxQ * price * scale );
toRateQuan = toRateQuan - tierMaxQ;
continue;
}
else
{
/*
* The incoming to-be-rated quantity is less than
* the tier total units. Rate it with the to-be-rated
* quantity
*/
total_cost = total_cost + ( toRateQuan * price * scale );
break;
}
}
return total_cost;
}
/*
* Calculate the 'average' cost per unit
*
* For a non-tiered rate, the average cost is price over quantity
*
* For a tiered rate, we calculate each tier cost, add them up and
* divide by the total quantity to get the average cost
*
*/
public double getCostPerUnit()
{
if( false == this.isTiered() )
{
/*
* Simple pricing; individual or bulk
*/
return ( this.effectivePrice / this.effectiveQuantity );
}
else
{
/*
* Tier pricing. Calculate the total cost then divide by the quantity to
* get the average cost
*/
Iterator ite = this.tiers.iterator();
Double min = new Double( 0 );
Double max = new Double( 0 );
Double price = new Double( 0 );
Double scale = new Double( 0 );
Double total_cost = new Double( 0 );
Double total_quan = new Double( 0 );
Double costPerUnit = new Double( 0 );
while( ite.hasNext() )
{
Map tier_map = (Map)ite.next();
min = (Double)tier_map.get( "MIN" );
max = (Double)tier_map.get( "MAX" );
price = (Double)tier_map.get( "PRICE" );
scale = (Double)tier_map.get( "SCALE" );
if( 0 >= ( max - min + 1 ) )
{
break;
}
total_quan = total_quan + ( max - min + 1 );
total_cost = total_cost + ( ( max - min + 1 ) * price * scale );
}
this.effectiveQuantity = total_quan;
costPerUnit = total_cost / total_quan;
return costPerUnit;
}
}
/*
* DEBUG
*/
public void printRate()
{
System.out.println( "\tRATE NAME [" + this.rateName + "]" );
System.out.println( "\tRATE DESC [" + this.rateDescr + "]" );
System.out.println( "\tQUANTITY [" + this.effectiveQuantity + "]" );
System.out.println( "\tCOST PER UNIT [" + this.costPerUnit + "]" );
if( false == this.isTiered() )
{
System.out.println( "\tPRICE [" + this.effectivePrice + "]" );
}
else
{
int num_tiers = this.tiers.size();
for( int i = 0; i < num_tiers; ++i )
{
System.out.println( "\t--- TIER [" + ( i + 1 ) + "]" );
System.out.println( "\t\t --- MIN [" + this.tiers.get( i ).get( "MIN") + "]" );
System.out.println( "\t\t --- MAX [" + this.tiers.get( i ).get( "MAX") + "]" );
System.out.println( "\t\t --- PRICE [" + this.tiers.get( i ).get( "PRICE") + "]" );
System.out.println( "\t\t --- SCALE [" + this.tiers.get( i ).get( "SCALE") + "]" );
}
}
System.out.println( "\n\n");
}
}
This
System.exit( 3 );
Causes your process to return (in Java parlance it exits) with a value to the operating system. It's equivalent to the int returned by main in c and c++. On unix style systems you can access the return value with
echo $?
It looks like you are supposed to call this program with a file-path to some catalogue as the first argument (args[0]), otherwise it exits.

Tokenize an arraylist

I have a text file with values like :
[2014-08-19 00:00:21,702] REC|SRC:923142676343|DST:9900|CNT:1|OPR:zong|\nADD BBCLANDAN\n
[2014-08-19 00:01:02,958] REC|SRC:923138824807|DST:9900|CNT:1|OPR:zong|ADD TRIXXS
[2014-08-19 00:01:12,799] REC|SRC:923125473547|DST:9900|CNT:1|OPR:zong|ADD SahafatMedia
[2014-08-19 00:01:32,894] REC|SRC:923142676343|DST:9900|CNT:1|OPR:zong|ADD BBCMEDIA\n\n
[2014-08-19 00:02:42,754] REC|SRC:923119511824|DST:9900|CNT:1|OPR:zong|ADD sMs
[2014-08-19 00:01:43,753] REC|SRC:923119511824|DST:9900|CNT:1|OPR:zong|ADD RIDAsMs
i have raed the text file and stored it into an arraylist with the output:
output:
923119511824|DST:9900|CNT:1|OPR:zong|ADD RIDAsMs
923119511824|DST:9900|CNT:1|OPR:zong|ADD sMs
923125473547|DST:9900|CNT:1|OPR:zong|ADD SahafatMedia
923138824807|DST:9900|CNT:1|OPR:zong|ADD TRIXXS
923142676343|DST:9900|CNT:1|OPR:zong|ADD BBCMEDIA\n\n
923142676343|DST:9900|CNT:1|OPR:zong|\nADD BBCLANDAN\n
[2014-08-19 00:01:02,958] REC|
[2014-08-19 00:01:12,799] REC|
[2014-08-19 00:01:32,894] REC|
[2014-08-19 00:01:43,753] REC|
[2014-08-19 00:02:42,754] REC|
[2014-08-19 00:00:21,702] REC|
Now i want to tokenize this arraylist to display only the duplicate contact numbers which are in output e.g 923142676343 and their content which are after ADD e.g TRIXXS
I need help please ???
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class pring
{
public static final String FILE_LOCATION = "C:/Users/DfroJaCk DB/Desktop/zongrecv.txt";
public static void main ( String [ ] args )
{
//Your reader
BufferedReader in = null;
//Where you store the Strings
ArrayList < String > al = new ArrayList < String > ();
try
{
//Open the file and give it to the reader
in = new BufferedReader ( new FileReader ( FILE_LOCATION ) );
String line;
//As long as the file has more lines read a line at a time
while ( ( line = in.readLine () ) != null )
{
//Split the line and stoe it in an array
String [ ] splitLine = line.split ( "SRC:" );
for ( int i = 0; i < splitLine.length; i++ )
{
//Add each element of the split array into an ArrayList
al.add ( splitLine [ i ] );
}
}
//Catch your possible problems
} catch ( FileNotFoundException fnfe )
{
fnfe.printStackTrace ();
} catch ( IOException ioe )
{
ioe.printStackTrace ();
}
//Sort your list
Collections.sort ( al );
for ( String s : al )
{
//spit it out
System.out.println ( s );
}
}
}
You could use java StringTokenizer. Since your arraylist is already sorted, you only have to check consecutive positions. Use | as a delimiter, get the first token for each entry that contains a number and compare it to the first token of the following entry. If they are equal, get the index of the space in the last token and print what is after it.
Be carefull to consider the case when more that 2 entries contain the same phone number, don't print them twice.
But you might rethink your approach, the way you store the Strings in the ArrayList looks pretty messy.
List<String> myList = new ArrayList();
myList.add("923119511824|DST:9900|CNT:1|OPR:zong|ADD RIDAsMs");
myList.add("923119511824|DST:9900|CNT:1|OPR:zong|ADD sMs");
myList.add("923125473547|DST:9900|CNT:1|OPR:zong|ADD SahafatMedia");
Collections.sort(myList);
System.out.println(myList.toString());
for (int i = 0; i < myList.size() - 1; i++) {
String currentEntry = myList.get(i);
String nextEntry = myList.get(i + 1);
StringTokenizer tokenizer = new StringTokenizer(currentEntry, "|");
String currentNumber = tokenizer.nextToken();
tokenizer = new StringTokenizer(nextEntry, "|");
String nextNumber = tokenizer.nextToken();
String lastToken = "";
if (currentNumber.equals(nextNumber)) {
System.out.println(currentNumber + " duplicate");
while (tokenizer.hasMoreTokens()) {
lastToken = tokenizer.nextToken();
}
System.out.println("last token: " + lastToken);
int index = lastToken.indexOf(" ");
System.out.println("What you probably want: " + lastToken.substring(index + 1));
}
}
And the output for this would be:
[923119511824|DST:9900|CNT:1|OPR:zong|ADD RIDAsMs, 923119511824|DST:9900|CNT:1|OPR:zong|ADD sMs, 923125473547|DST:9900|CNT:1|OPR:zong|ADD SahafatMedia]
923119511824 duplicate
last token: ADD sMs
What you probably want: sMs

Email Id exists or not in real through MX records via socket connection in java

I m trying to verify whether an email id exists or not in real. after doing some RND , was able to find out a code to check the existence of email id and i m doing this through MX records. It works fine for the local servers but i am not able to connect to some standard mail servers using sockets.I m trying to connect via port no. 25 but fails every time. Should any body tells me what is the problem ? your help would be really appreciated. below is the class file .
package com.wm.restful.webservices.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class SMTPMXLookup {
private static int hear( BufferedReader in ) throws IOException {
String line = null;
int res = 0;
while ( (line = in.readLine()) != null ) {
String pfx = line.substring( 0, 3 );
try {
res = Integer.parseInt( pfx );
}
catch (Exception ex) {
res = -1;
}
if ( line.charAt( 3 ) != '-' ) break;
}
return res;
}
private static void say( BufferedWriter wr, String text )
throws IOException {
wr.write( text + "\r\n" );
wr.flush();
return;
}
private static ArrayList getMX( String hostName )
throws NamingException {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes
( hostName, new String[] { "MX" });
Attribute attr = attrs.get( "MX" );
if (( attr == null ) || ( attr.size() == 0 )) {
attrs = ictx.getAttributes( hostName, new String[] { "A" });
attr = attrs.get( "A" );
if( attr == null )
throw new NamingException
( "No match for name '" + hostName + "'" );
}
ArrayList res = new ArrayList();
NamingEnumeration en = attr.getAll();
while ( en.hasMore() ) {
String mailhost;
String x = (String) en.next();
String f[] = x.split( " " );
if (f.length == 1)
mailhost = f[0];
else if ( f[1].endsWith( "." ) )
mailhost = f[1].substring( 0, (f[1].length() - 1));
else
mailhost = f[1];
res.add( mailhost );
}
return res;
}
public static boolean isAddressValid( String address ) {
int pos = address.indexOf( '#' );
if ( pos == -1 ) return false;
String domain = address.substring( ++pos );
ArrayList mxList = null;
try {
mxList = getMX( domain );
}
catch (NamingException ex) {
return false;
}
if ( mxList.size() == 0 ) return false;
for ( int mx = 0 ; mx < mxList.size() ; mx++ ) {
boolean valid = false;
try {
int res;
Socket skt = new Socket( (String) mxList.get( mx ), 995 );
BufferedReader rdr = new BufferedReader
( new InputStreamReader( skt.getInputStream() ) );
BufferedWriter wtr = new BufferedWriter
( new OutputStreamWriter( skt.getOutputStream() ) );
res = hear( rdr );
if ( res != 220 ) throw new Exception( "Invalid header" );
say( wtr, "EHLO rgagnon.com" );
res = hear( rdr );
if ( res != 250 ) throw new Exception( "Not ESMTP" );
say( wtr, "MAIL FROM: <tim#orbaker.com>" );
res = hear( rdr );
if ( res != 250 ) throw new Exception( "Sender rejected" );
say( wtr, "RCPT TO: <" + address + ">" );
res = hear( rdr );
say( wtr, "RSET" ); hear( rdr );
say( wtr, "QUIT" ); hear( rdr );
if ( res != 250 )
throw new Exception("Address is not valid!");
valid = true;
rdr.close();
wtr.close();
skt.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if ( valid ) return true;
}
}
return false;
}
public static void main( String args[] ) {
String testData[] = {
"xyz#gmail.com", //take an example
};
for ( int ctr = 0 ; ctr < testData.length ; ctr++ ) {
System.out.println( testData[ ctr ] + " is valid? " +
isAddressValid( testData[ ctr ] ) );
}
return;
}
}
I am able to connect to the mail servers which runs on port no.25 but as i tried to connect to some standard mail servers using their MX records like of gmail.com,google.com,yahoo.com etc, not be able to connect to their servers.Your help would be really appreciated..

Can you add a number to a number in a Array?

package javaapplication1;
import java.io.*;
/**
*
* #author simon
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
NotSimple[] objArray;
BufferedReader stdin = new BufferedReader(
new InputStreamReader( System.in ) );
System.out.println( "Enter a number of objects:" );
int size;
size = Integer.parseInt( stdin.readLine() );
//Initialize objArray
objArray = new NotSimple[size];
//TODO: Implement following functions
initializeObj(objArray);
increaseData(objArray);
printObjData(objArray);
//TODO: Explain all outputs of the below function
explainOutputs();
return;
}
//TODO
//initialize every Notsimple object in the array 'a'
//to NotSimple()
//Hint: using the for loop, assign a[i] = new NotSimple();
static void initializeObj(NotSimple[] a){
//TODO: FILL ME
for (int i = 0; i < a.length; i++)
{
a[i] = new NotSimple();
}
}
//TODO:
//Increase the ‘data’ member of every NotSimple object
//in the array ‘a’ by 1
static void increaseData(NotSimple[] a) {
//TODO: FILL ME
for (int i = 0; i < a.length; i++)
{
a[i].setData(a[i].getData()+1);
}
}
//TODO:
//Print the data of every NotSimple object in the array ‘a’
static void printObjData(NotSimple[] a) {
//TODO: FILL ME
for (int i = 0; i < a.length; i++)
{
System.out.println (a[i].getData());
}
}
//TODO explain all the outputs 1a-1f
static void explainOutputs() {
NotSimple nsObj1 = new NotSimple();
//1a
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
NotSimple nsObj2 = new NotSimple( 50,
"Another immutable string!" );
//1b
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj2 = nsObj1;
nsObj2.setData(10);
nsObj1.setData(100);
//1c
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj1 = new NotSimple();
//1d
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj2 = new NotSimple();
//1e
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj2.setData(10);
//1f
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
}
}
class NotSimple
{
NotSimple()
{
data = 5;
str = new String( "Initialized!" );
}
NotSimple( int i, String str1 )
{
data = i;
str = str1;
}
void setData( int i )
{
data = i;
return;
}
int getData()
{
return data;
}
void setStr( String str1)
{
str = str1;
return;
}
String getStr()
{
return str;
}
private int data;
private String str;
}
I want to add 1 to the array but it doesn't work. I get the following compilation error:
operator ++ cannot be applied to javaapplication1.NotSimple
Use
for (int i = 0; i < a.length; i++)
{
a[i].setData(a[i].getData()+1);
}
Since Java does not support operator overloading, you'll need to retrieve the old value (i.e. the getData() call), add 1 to it, and set it as the new value (i.e. the setData() call).
What does the NotSimple class look like?
Is NotSimple a numeric type that can be incremented so?
If NotSimple has a field called 'data' then replace a[i]++ with a[i].data++

Categories

Resources