Categories
discuss

Why do I get garbage output when printing an int[]?

My program is suppose to count the occurrence of each character in a file ignoring upper and lower case. The method I wrote is:

public int[] getCharTimes(File textFile) throws FileNotFoundException {

  Scanner inFile = new Scanner(textFile);

  int[] lower = new int[26];
  char current;
  int other = 0;

  while(inFile.hasNext()){
     String line = inFile.nextLine();
     String line2 = line.toLowerCase();
     for (int ch = 0; ch < line2.length(); ch++) {
        current = line2.charAt(ch);
        if(current >= 'a' && current <= 'z')
           lower[current-'a']++;
        else
           other++;
     }
  }

  return lower;
 }

And is printed out using:

for(int letter = 0; letter < 26; letter++) {
             System.out.print((char) (letter + 'a'));
       System.out.println(": " + ts.getCharTimes(file));
            }

Where ts is a TextStatistic object created earlier in my main method. However when I run my program, instead of printing out the number of how often the character occurs it prints:

a: [I@f84386 
b: [I@1194a4e 
c: [I@15d56d5 
d: [I@efd552 
e: [I@19dfbff 
f: [I@10b4b2f 

And I don’t know what I’m doing wrong.

Answer

ts.getCharTimes(file) returns int array.

print ts.getCharTimes(file)[letter]

Categories
discuss

What is the main-stream Java alternative to ASP.NET / PHP

I’ve heard something and seen some examples of web application built using ASP.NET / PHP and I’m wondering what would be the equivalent way of doing similar things in Java world. Looking on the Wikipedia I have found a lot of frameworks and I’m kind of confused which one is the best.

Answer

The Java equivalent of PHP and “Classic” ASP would be JSP (JavaServer Pages) with scriptlets (embedded raw Java code). Scriptlets are considered poor practice in Java web development world. Taglibs and EL (Expression Language) should be preferred above scriptlets. The Java equivalent of ASP.NET (MVC) would be a Java MVC framework. There are a lot of Java-based MVC frameworks out, mostly providing a Servlet/Filter-based controller and taglibs to interact with the model (usually a Javabean) and the view (usually a JSP page, but XHTML is also possible).

To start, the Java EE API provides JSF (JavaServer Faces) for this, which in turn comes along with XHTML based templated view technology known as Facelets. Facelets is seen as a replacement of the good old JSP. Further, there are a lot of open source Java MVC frameworks which are built on top of the JSP/Servlet API and which are intended as an alternative/competition to JSF. You can find little information of all of them here, the popular ones being Spring MVC, Struts2 and Stripes.

As to which one to choose, I suggest having a look at this answer which I strongly agree.

Categories
discuss

How can you get an Android user’s email address?

I have android.permission.READ_OWNER_DATA but I can’t find any reliable code that would explain how can I read email address of device’s owner. How can I do this?

Answer

Why you wanna do that?

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;

/**
 * This class uses the AccountManager to get the primary email address of the
 * current user.
 */
public class UserEmailFetcher {

  static String getEmail(Context context) {
    AccountManager accountManager = AccountManager.get(context); 
    Account account = getAccount(accountManager);

    if (account == null) {
      return null;
    } else {
      return account.name;
    }
  }

  private static Account getAccount(AccountManager accountManager) {
    Account[] accounts = accountManager.getAccountsByType("com.google");
    Account account;
    if (accounts.length > 0) {
      account = accounts[0];      
    } else {
      account = null;
    }
    return account;
  }
}

In your AnroidManifest.xml

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Categories
discuss

best way to compare between two-dimension integer arrays in java

I would like to know what is the best, fastest and easiest way to compare between 2-dimension arrays of integer.
the length of arrays is the same. (one of the array’s is temporary array)

Answer

Edan wrote:

just need to see if the value is the same

If you want to check that a[i][j] equals b[i][j] for all elements, just use Arrays.deepEquals(a, b).

Categories
discuss

java phone number validation

Here is my problem:

Create a constructor for a telephone number given a string in the form xxx-xxx-xxxx or xxx-xxxx for a local number. Throw an exception if the format is not valid.

So I was thinking to validate it using a regular expression, but I don’t know if I’m doing it correctly. Also what kind of exception would I have to throw? Do I need to create my own exception?

    public TelephoneNumber(String aString){
        if(isPhoneNumberValid(aString)==true){
            StringTokenizer tokens = new StringTokenizer("-");
            if(tokens.countTokens()==3){
                areaCode = Integer.parseInt(tokens.nextToken());
                exchangeCode = Integer.parseInt(tokens.nextToken());
                number = Integer.parseInt(tokens.nextToken());
            }
            else if(tokens.countTokens()==2){
                exchangeCode = Integer.parseInt(tokens.nextToken());
                number = Integer.parseInt(tokens.nextToken());
            }
            else{
                //throw an excemption here
            }
        }

    }


 public static boolean isPhoneNumberValid(String phoneNumber){
     boolean isValid = false;

     //Initialize reg ex for phone number.
    String expression = "(\d{3})(\[-])(\d{4})$";
    CharSequence inputStr = phoneNumber;
    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(inputStr);
    if(matcher.matches()){
        isValid = true;
     }
        return isValid;
    }

Hi sorry, yes this is homework. For this assignments the only valid format are xxx-xxx-xxxx and xxx-xxxx, all other formats (xxx)xxx-xxxx or xxxxxxxxxx are invalid in this case.

I would like to know if my regular expression is correct

Answer

So I was thinking to validate it using a regular expression, but I don’t know if I’m doing it correctly.

It indeed looks overcomplicated. Also, matching xxx-xxx-xxxx or xxx-xxxx where x is a digit can be done better with "(\d{3}-){1,2}\d{4}". To learn more about regex I recommend to go through http://regular-expressions.info.

Also what kind of exception would I have to throw? Do I need to create my own exception?

A ValidatorException seems straight forward.

public static void isPhoneNumberValid(String phoneNumber) throws ValidatorException {
    if (!phoneNumber.matches(regex)) {
        throws ValidatorException("Invalid phone number");
    }
}

If you don’t want to create one yourself for some reasons, then I’d probably pick IllegalArgumentException, but still, I don’t recommend that.

That said, this validation of course doesn’t cover international and/or external telephone numbers. Unless this is really homework, I’d suggest to rethink the validation.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..