detecting same variable in a method Java JDT parser - java

I've been implementing a Java parser with JDT and i have a problem with detect same variable declaration in same method. For example, i have class such as below:
public double method(double[] data) {
int _ii = 0;
int _ii = 0; //same variable name, data type and value
for (int _ii = 0; _ii < _dimensi; _ii++) {
_temp += data[_ii];
}
_output = _temp / _dimensi;
return _output;
}
Above class has two variable with the same name (int _ii = 0), then my goal is find duplicate variable in same method and remove one of them. So that the code will be:
public double method(double[] data) {
int_ii = 0;
for (int _ii = 0; _ii < _dimensi; _ii++) {
_temp += data[_ii];
}
_output = _temp / _dimensi;
return _output;
}
My code so far:
public static void main(String args[]){
String str = "public class Classname{"
+ "public double method(double[] data) {\n" +
" int _ii = 0;\n" +
" int _ii = 0; //same variable name, data type and value\n" +
"\n" +
" for (int _ii = 0; _ii < _dimensi; _ii++) {\n" +
" _temp += data[_ii];\n" +
" }\n" +
" _output = _temp / _dimensi;\n" +
"\n" +
" return _output;\n" +
"}"
+ "}";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(str.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
public boolean visit(MethodDeclaration method){
Block block = method.getBody();
block.accept(new ASTVisitor() {
public boolean visit(VariableDeclarationFragment var) {
System.out.println("Variable " + var.getName()+", in Method "+method.getName()+ "' Method line " + cu.getLineNumber(method.getStartPosition()));
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, var.getName()); // variable name
multimap.put(1, cu.getLineNumber(method.getStartPosition())); // method line
multimap.put(1, method.getName()); // method name
//Then what should i do if found variable name, method line and method name more than one in the Multimap?
return false;
}
});
return false;
}
});
}
Anyone please help me, thanks :)

Related

How to convert string of the form {a=2 ,b=5} to JSON of the form {"a":2 , "b":5} in java?

I am getting result in the form {a=2 ,b=5} after spel expression evaluation.
I want to convert it to json.
How do I do it?
Please help!
here is your solution:
public static void main(String[] args) {
String something = "{a=2 ,b=5}";
something = something.replace("{", "");
something = something.replace("}", "");
String[] pairs = something.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String pair : pairs) {
list.add(pair);
}
for (int i = 0; i < list.size(); i++) {
String[] temp = list.get(i).split("=");
temp[0] = "\"" + temp[0] + "\"";
list.set(i, temp[0] + ":" + temp[1]);
}
String contents = "";
for (int i = 0; i < list.size(); i++) {
contents = contents + ", " + list.get(i);
}
contents = contents.replaceFirst(", ", "");
contents = "{" + contents + "}";
System.out.println("Contents: " + contents);
}
And here is your result:
Contents: {"a":2 , "b":5}

Replace characters with substring using a loop Java

I am trying to replace each instance of what is between two brackets using a loop and an array. array1a and array1b are the indices of where the brackets open and close. I want to get the number between the two brackets and increment it by one and replace the value currently there, but as the string text is currently a list (such as "list item (0) list item (10) list item (1023)" I want to use a loop to increment the value of each rather than to set all the values within brackets to the same value. I hope this makes sense!
String text = myString.getText();
for (int x = 0; x < 10; x++) {
array2[x] = text.substring(array1a[x], array1b[x]);
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
String text2 = text.replaceAll("\\(.*\\)", array3[x]);
myString.setText(text2);
}
Full Code:
public class CreateVideoList extends JFrame implements ActionListener {
JButton play = new JButton("Play Playlist");
JButton addVideo = new JButton("Add Video");
TextArea playlist = new TextArea(6, 50);
JTextField videoNo = new JTextField(2);
private int x = 0;
#Override
public void actionPerformed(ActionEvent e) {
String key = videoNo.getText();
String name = VideoData.getName(key);
String director = VideoData.getDirector(key);
Integer playCount = VideoData.getPlayCount(key);
String text = playlist.getText();
String rating = CheckVideos.stars(VideoData.getRating(key));
String output = name + " - " + director + "\nRating: "
+ rating
+ "\nPlay Count: " + playCount;
String newItem = key + " " + name + " - " + director + " ("
+ playCount + ") " + "\n";
String addToList = "";
String[] array3 = new String[100];
if ("Add Video".equals(e.getActionCommand())) {
if (Character.isDigit(text.charAt(0)) == false) {
playlist.setText("");
}
if (addToList.indexOf(key) == -1) {
addToList += addToList + newItem;
playlist.append(addToList);
array3[x] = key;
x++;
} else if (addToList.indexOf(key) != -1) {
JOptionPane.showMessageDialog(CreateVideoList.this,
"This video is already in the playlist. Please select a"
+ " different video.", "Add to playlist error", JOptionPane.INFORMATION_MESSAGE);
}
}
if ("Play Playlist".equals(e.getActionCommand())) {
Integer length = (text.length());
int counta = 0;
Integer[] array1a = new Integer[100];
Integer[] array1b = new Integer[100];
String strPlayCount = "";
for (x = 0; x < length; x++) {
if (text.charAt(x) == '(') {
counta++;
array1a[counta - 1] = x;
array1a[counta - 1] = array1a[counta - 1] + 1;
}
if (text.charAt(x) == ')') {
array1b[counta - 1] = x;
array1b[counta - 1] = array1b[counta - 1];
}
}
String[] array2 = new String[counta];
String[] array4 = new String[100];
for (int y = 0; y < counta; y++) {
array2[y] = text.substring(array1a[y], array1b[y]);
array2[y] = array2[y] + 1;
playCount = Integer.parseInt(array2[y]);
array4[y] = "(" + array2[y] + ")";
String text2 = text.replaceAll("\\(.*\\)", array4[y]);
playlist.setText(text2);
}
}
}
Replace
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
with
Integer n = Integer.parseInt(array2[x]) + 1;
array3[x] = "(" + n.toString() + ")";

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive

import java.util.Random;
import java.util.StringTokenizer;
public class FortuneCookie {
private String subjList;
private String objList;
private String verbList;
private int sWords = 0;
private int oWords = 0;
private int vWords = 0;
private Random random = new Random();
public FortuneCookie() {
subjList = "i#You#He#She#It#They";
objList = "me#you#him#her#it#them";
verbList = "hate#love#deny#find#hear#forgive#hurt#win#teach";
}
public void setSubject(String subj) {
subjList = subj;
}
public void setObjectList(String obj) {
objList = obj;
}
public void setVerbList(String verb) {
verbList = verb;
}
public String genFortuneMsg() {
String v = " ";
String o = " ";
String s = " ";
StringTokenizer st1 = new StringTokenizer(subjList, "#");
StringTokenizer st2 = new StringTokenizer(objList, "#");
StringTokenizer st3 = new StringTokenizer(verbList, "#");
while (st1.hasMoreTokens()) {
s = st1.nextToken();
sWords = st1.countTokens();
int no = random.nextInt(sWords);
if (no == sWords) {
break;
}
}
while (st2.hasMoreTokens()) {
o = st2.nextToken();
oWords = st2.countTokens();
int no2 = random.nextInt(oWords);
if (no2 == oWords) {
break;
}
}
while (st3.hasMoreTokens()) {
v = st3.nextToken();
vWords = st3.countTokens();
int no3 = random.nextInt(vWords);
if (no3 == vWords) {
break;
}
}
String gen = s + " " + v + " " + o;
return gen;
}
public void print() {
System.out.println("Tokens");
System.out.println("Subject List:" + subjList + " count = " + sWords);
System.out.println("verb List:" + verbList + " count = " + vWords);
System.out.println("object List:" + objList + " count = " + oWords);
}
}
Exception in thread "main" java.lang.IllegalArgumentException: bound
must be positive at java.util.Random.nextInt(Random.java:388) at
FortuneCookie.genFortuneMsg(FortuneCookie.java:42) at
FortuneCookieTest.main(FortuneCookieTest.java:6)
Your case is not negative it is zero.
From the docs of countToken method
/**
* Calculates the number of times that this tokenizer's
* <code>nextToken</code> method can be called before it generates an
* exception. The current position is not advanced.
*
In a while loop when your count token return zero, you run into an exception. Well that error message should be reformatted to negative or zero.
Add 1 to your result or check for zero. Should work.

Error message for StorageResource type

I've been trying to work on this problem for a while now but to no avail. When I run the code I get this error message: incompatible types: edu.duke.StorageResource cannot be converted to java.lang.String on line String geneList = FMG.storeAll(dna);. Does this mean I'm trying to make edu.duke object work with a java.lang.String type object? What would we go about resolving this issue?
Here's my code so far:
package coursera_java_duke;
import java.io.*;
import edu.duke.FileResource;
import edu.duke.StorageResource;
import edu.duke.DirectoryResource;
public class FindMultiGenes5 {
public int findStopIndex(String dna, int index) {
int stop1 = dna.indexOf("TGA", index);
if (stop1 == -1 || (stop1 - index) % 3 != 0) {
stop1 = dna.length();
}
int stop2 = dna.indexOf("TAA", index);
if (stop2 == -1 || (stop2 - index) % 3 != 0) {
stop2 = dna.length();
}
int stop3 = dna.indexOf("TAG", index);
if (stop3 == -1 || (stop3 - index) % 3 != 0) {
stop3 = dna.length();
}
return Math.min(stop1, Math.min(stop2, stop3));
}
public StorageResource storeAll(String dna) {
//CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCAdna = "CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCA";
String geneAL = new String();
String sequence = dna.toUpperCase();
StorageResource store = new StorageResource();
int index = 0;
while (true) {
index = sequence.indexOf("ATG", index);
if (index == -1)
break;
int stop = findStopIndex(sequence, index + 3);
if (stop != sequence.length()) {
String gene = dna.substring(index, stop + 3);
store.add(gene);
//index = sequence.substring(index, stop + 3).length();
index = stop + 3; // start at the end of the stop codon
}else{ index = index + 3;
}
}
return store;//System.out.println(sequence);
}
public void testStorageFinder() {
DirectoryResource dr = new DirectoryResource();
StorageResource dnaStore = new StorageResource();
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
String s = fr.asString();
dnaStore = storeAll(s);
printGenes(dnaStore);
}
System.out.println("size = " + dnaStore.size());
}
public String readStrFromFile(){
FileResource readFile = new FileResource();
String DNA = readFile.asString();
//System.out.println("DNA: " + DNA);
return DNA;
}//end readStrFromFile() method;
public float calCGRatio(String gene){
gene = gene.toUpperCase();
int len = gene.length();
int CGCount = 0;
for(int i=0; i<len; i++){
if(gene.charAt(i) == 'C' || gene.charAt(i) == 'G')
CGCount++;
}//end for loop
System.out.println("CGCount " + CGCount + " Length: " + len + " Ratio: " + (float)CGCount/len);
return (float)CGCount/len;
}//end of calCGRatio() method;
public void printGenes(StorageResource sr){
//create a FindMultiGenesFile object FMG
FindMultiGenes5 FMG = new FindMultiGenes5();
//read a DNA sequence from file
String dna = FMG.readStrFromFile();
String geneList = FMG.storeAll(dna);
//store all genes into a document
StorageResource dnaStore = new StorageResource();
System.out.println("\n There are " + geneList.size() + " genes. ");
int longerthan60 = 0;
int CGGreaterthan35 = 0;
for(int i=0; i<geneList.size(); i++){
if(!dnaStore.contains(geneList.get(i)))
dnaStore.add(geneList.get(i));
if(geneList.get(i).length() > 60) longerthan60++;
if(FMG.calCGRatio(geneList.get(i)) > 0.35) CGGreaterthan35++;
}
System.out.println("dnaStore.size: " + dnaStore.size());
System.out.println("\n There are " + dnaStore.size() + " genes. ");
System.out.println("There are " + longerthan60 + " genes longer than 60.");
System.out.println("There are " + CGGreaterthan35 + " genes with CG ratio greater than 0.35.");
}//end main();
}
I found your post as I am also doing a similar course at Duke using those edu.duke libraries.
When I get that error message it is because I'm using the wrong method to access it.
Try FMD.data() to get an iterable of all of the gene strings.

JPA wrapper to convert unchecked exceptions into checked exceptions?

Before I wander off and re-create the wheel, does anyone know of a JPA wrapper that turns the unchecked exceptions JPA throws into checked exceptions?
Not looking for an argument about why I should not want checked exceptions, I do want them :-)
You can do 99% of rolling your own using the code below. It will leave you with two compile errors due to the members of a Collection needing to be encapsulated, but it does take you past the point where it is no longer worth automating.
package so;
import javax.persistence.*;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.*;
public class CheckedPersistenceMaker {
static final String PACKAGE = "stackoverflow.javax.persistence";
static final String PACKAGE_DIR = PACKAGE.replace('.', '/');
static Class<?>[] CLASSES = new Class<?>[] { Cache.class,
EntityManager.class, EntityManagerFactory.class,
EntityTransaction.class, Parameter.class,
PersistenceUnitUtil.class, PersistenceUtil.class,
Persistence.class, Query.class, Tuple.class, TupleElement.class,
TypedQuery.class };
private static String getName(Class<?> c) {
String name = c.getName();
for(Class<?> p:CLASSES) {
if (p.equals(c))
return PACKAGE + ".Checked"
+ name.substring(name.lastIndexOf('.') + 1);
}
return c.getName();
}
static void generateWrapper(Class<?> c) throws Exception {
String name = c.getName();
TypeVariable<?>[] genType = c.getTypeParameters();
String varNames = "";
if (genType != null && genType.length != 0) {
StringBuilder b = new StringBuilder();
b.append("<");
for(int i = 0;i < genType.length;i++) {
if (i > 0) b.append(",");
b.append(genType[i].getName());
}
b.append(">");
varNames = b.toString();
}
name = "Checked" + name.substring(name.lastIndexOf('.') + 1);
File javaFile = new File(PACKAGE_DIR + "/" + name + ".java");
javaFile.getParentFile().mkdirs();
FileWriter w = new FileWriter(javaFile);
w.write("package " + PACKAGE + ";\n");
w.write("public class " + name + varNames + " {\n");
w.write(" private final " + c.getName() + varNames
+ " wrapped;\n\n ");
w.write(name + "(" + c.getName() + varNames
+ " original) {\nwrapped=original;\n}\n\n");
w.write(" public " + c.getName() + varNames
+ " getOriginal() { return wrapped; }\n\n");
Method[] ms = c.getDeclaredMethods();
for(Method m:ms) {
if (!Modifier.isPublic(m.getModifiers())) continue;
w.write(" ");
String s = m.toGenericString();
s = s.replace(" abstract ", " ");
s = s.replace(c.getName() + ".", "");
String q = s.substring(0, s.indexOf('('));
if (q.indexOf('<',10) != -1) q = q.substring(0, q.indexOf('<',10));
boolean needsTranslate = false;
for(Class<?> cc:CLASSES) {
String ccn = cc.getName();
if (q.indexOf(ccn) != -1) needsTranslate = true;
String ccc = ccn.replace(cc.getPackage().getName() + ".",
PACKAGE + ".Checked");
s = s.replace(ccn, ccc);
}
int pc = 0;
int p = s.indexOf('(');
if (s.charAt(p + 1) != ')') {
StringBuilder b = new StringBuilder(s);
int g = 0;
char ch;
do {
ch = b.charAt(p);
switch (ch) {
case '<': {
g++;
break;
}
case '>': {
g--;
break;
}
case ',':
case ')': {
if (g == 0) {
String pa = " p" + pc;
b.insert(p, pa);
pc++;
p += pa.length();
}
break;
}
}
p++;
} while( ch != ')' );
s = b.toString();
}
w.write(s);
w.write(" throws CheckedPersistenceException");
Class<?>[] excs = m.getExceptionTypes();
for(Class<?> e:excs) {
w.write(", " + e.getName());
}
w.write(" {\n try {\n ");
Class<?> ret = m.getReturnType();
if (!ret.equals(Void.TYPE)) {
w.write("return ");
if (needsTranslate) {
String retName = ret.getName();
retName = retName.replace(c.getPackage().getName() + ".",
PACKAGE + ".Checked");
w.write("new " + retName + "(");
}
}
if (Modifier.isStatic(m.getModifiers())) {
w.write(c.getName() + "." + m.getName() + "(");
} else {
w.write("wrapped." + m.getName() + "(");
}
Class<?> paramTypes[] = m.getParameterTypes();
for(int i = 0;i < pc;i++) {
if (i > 0) w.write(',');
boolean isChecked = false;
for(int j=0;j<CLASSES.length;j++) {
if( CLASSES[j].equals(paramTypes[i]) ) isChecked=true;
}
w.write("p" + i);
if(isChecked) w.write(".getOriginal()");
}
w.write(')');
if (needsTranslate) w.write(')');
w.write(";\n } catch ( javax.persistence.PersistenceException e ) { throw new CheckedPersistenceException(e); }\n }\n\n");
}
w.write("}\n");
w.close();
}
public static void main(String[] args) throws Exception {
for(Class<?> c:CLASSES) {
generateWrapper(c);
}
}
}

Categories

Resources