Java: Need Some Way to Shorten This Code

Java: Need some way to shorten this code

If it's the same syntax as C# and the flags are set properly, you could do this:

PackageManager p = context.getPackageManager(); 
final List<PackageInfo> appinstall =
p.getInstalledPackages(PackageManager.GET_PERMISSIONS |
PackageManager.GET_PROVIDERS)

Language Tricks to Shorten My Java Code?

There are at least two possible built-in ways to shorten your code:

You could use Collection.addAll(Collection) that appends each element in the collection passed as parameter to the end of the collection.:

List<Looper> allLoopers = new ArrayList<Looper>();

...

allLoopers.addAll(looperTracks);
allLoopers.add(this);

for(Looper looper : allLoopers) {
...
}

or you can use a constructor that takes a collection as a parameter:

List<Looper> allLoopers = new ArrayList<Looper>(looperTracks);

Due to the change of question: All arrays can easily be converted to collections using java.util.Arrays e.g.

List<Looper> someLooperTracks = Arrays.asList(looperTracks). 

This will wrap the array in a fixed-size list.

Is there anyway to shorten this Java code?

Defining a common code into a single function and Using ternary operator to inline if condition.

    public static double takeInput(String heightOrWeight, int lowConstraint, int highConstraint) {
Scanner input = new Scanner(System.in);
double validDouble = 0;
boolean isValid = false;

while(!(isValid)){
System.out.print(heightOrWeight + ": ");
input.nextLine();

validDouble = input.hasNextDouble() ? input.nextDouble(): Integer.MIN_VALUE;

if (validDouble > lowConstraint && validDouble <= highConstraint) {
isValid = true;
}

if (!isValid) {
System.out.println("Invalid input\nPlease try again\n");
}
}
return validDouble;
}

Calling above method with appropriate parameters.

        double height = takeInput("Height(cm)", 5,500);
double weight = takeInput("Weight(kg)", 0,500);

How to shorten the code for an image in java

You have a good start already. You can change the variable easily by setting a different variable equal to the call of the method.

public static void main(String args[]){
JLabel someVariable = createImage("dump.jpg");
JLabel anotherVariable = createImage("dump2.jpg");
}

public static JLabel createImage(String imgName){
return new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/"+imgName))));
}

How to shorten an if else statement in java?

That was a good idea, unfortunately, you are trying to parse a string with non-numeric characters as an int. You need to substring the Int from the string like so:

if(userCom.startsWith("/dive")){
String str = userCom.subString(6);
int howDeep = Integer.parseInt(str);
myFish.dive(howDeep);
}

Shorten java source code

always use methods to shorten the code. and when you need to do same work several times, just call your method and pass true arguments to it.

here is some changes on your code, i removed your Repetitious code which was printing some data from data base, and i created a method called doPrint which takes four arguments.

  • string array named keys, which it's values will be assigned to BasicDBObject's.
  • a value that will be assigned to BasicDBObject's.
  • the db that you are connected with it.
  • and the collection (table) name that you want to read data from it.

then all you need to printing is to call doPrint

doPrint(keys , regex , db , "titles");

hope it helps.

package kelas_java;
public class searchingDariSemuaKolom {

static void doPrint(String keys, Object value, DB db, String collectionName) {
BasicDBList or = new BasicDBList();
for (String key : keys) {
or.add(new BasicDBObject(key, value));
}
DBObject query = new BasicDBObject("$or", or);
DBCollection table = db.getCollection(collectionName);

try {
DBCursor cur = table.find(query);
while (cur.hasNext()) {
System.out.println(cur.next().get("title"));
}
} catch (MongoException e) {
System.out.println("Error: "+e.getMessage());
} finally {
cur.close();
}
}
public static void main(String[] args) {
BasicDBObject sortOrder = new BasicDBObject();
MongoClient mongoClient;
DB db;

String strs[] = {
"link",
"title",
"body",
"date",
};
try {
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("face");
boolean auth = db.authenticate("aku", "kamu".toCharArray());
Pattern regex = Pattern.compile("1");

//start1
doPrint(keys , regex , db , "titles");
//start2
doPrint(keys , regex , db , "news");
} catch (Exception e) {
System.out.println("Error: "+e.getMessage());
}
}
}

Need assistance to remember a way to shorten code in ANSI-C using # signs

You're probably thinking of macros.

For example:

#define INCREMENT(x) x++

However, macros are literally expanded to- meaning unless they're aggressively parenthesised, they can produce unexpected behaviour.



Related Topics



Leave a reply



Submit