Java - Parameters are not being passed into function when expected to be - java
I am attempting to run a method rgbScore() which passes in parameters from previous methods to calculate the difference between two pixels of a image. I would expect the result to be the difference between the two pixels but all I get is (0,0,0) ...
public void TypeButtonPressed()
{
filteredImage(GetType());
int type = GetType();
filteredrgbValue();
originalrgbValue();
rgbScore(originalred, filteredred, originalgreen, filteredgreen, originalblue, filteredblue); //THIS METHOD
JOptionPane.showMessageDialog(null, "Original RGB Value:" + oRGBValue + "\nFiltered RGB Value:" + fRGBValue + "\nScore:" + rgbDiff, Options[type], JOptionPane.INFORMATION_MESSAGE);
}
...
public String rgbScore(int originalred, int filteredred, int originalgreen, int filteredgreen, int originalblue, int filteredblue){
int redDiff = originalred - filteredred;
int greenDiff = originalgreen - filteredgreen;
int blueDiff = originalblue - filteredblue;
return rgbDiff = "(" + redDiff + "," + greenDiff + "," + blueDiff + ")";
}
I have declared the variables at the top of the class as follows:
public int filteredred; public int filteredgreen; public int filteredblue;
public int originalred; public int originalgreen; public int originalblue;
< Additional Information >
filteredrgbValue();
public String filteredrgbValue(){
BufferedImage filtered = filteredImage;
Color filteredRGBValue = new Color(filtered.getRGB(125, 125));
int filteredred = filteredRGBValue.getRed();
int filteredgreen = filteredRGBValue.getGreen();
int filteredblue = filteredRGBValue.getBlue();
return fRGBValue = "(" + filteredred + "," + filteredgreen + "," + filteredblue + ")";
}
originalrgbValue();
public String originalrgbValue(){
BufferedImage original = unfilteredImage;
Color originalRGBValue = new Color(original.getRGB(125, 125));
int originalred = originalRGBValue.getRed();
int originalgreen = originalRGBValue.getGreen();
int originalblue = originalRGBValue.getBlue();
return oRGBValue = "(" + originalred + "," + originalgreen + "," + originalblue + ")";
}
You are creating new variables in your methods which are hiding your member variables. Remove the type declarations, for example:
public String filteredrgbValue(){
BufferedImage filtered = filteredImage;
Color filteredRGBValue = new Color(filtered.getRGB(125, 125));
// you are declaring new variables here, hiding your member variables...
//int filteredred = filteredRGBValue.getRed();
//int filteredgreen = filteredRGBValue.getGreen();
//int filteredblue = filteredRGBValue.getBlue();
filteredred = filteredRGBValue.getRed();
filteredgreen = filteredRGBValue.getGreen();
filteredblue = filteredRGBValue.getBlue();
return fRGBValue = "(" + filteredred + "," + filteredgreen + "," + filteredblue + ")";
}
Looks like you have never initialized variables, you have just declared the vars.
defualt valu for int is 0 and until you dont initialize your vars it will have default vals.
Related
Android moving GraphView and play MediaPlayer at the same time
I'm working on a project, where I need to show the pitches of the words (from the song) in a GraphView. I wrote a program that would get the pitches from a song and create a .txt file from it. Then I wrote a class, that reads the file and creates a list from it. So in the end I would have a list that consists of words and word contains pitches. In the MakePitchesList you can see what the pitches output from a song looks like. I have 0,14:23281,61 on every line. The first part of the line is timeOccurance meaning, when this pitch was heard and the second part is the pitch itself. So in this example the timeOccurance would be 0,14 and pitch at that given time 23281,61. Here are the three classes that make a wordsList out of a pitch .txt file. public class Pitch{ float occuranceTime; float pitch; public void setOccuranceTime(float occuranceTime) { this.occuranceTime = occuranceTime; } public float getOccuranceTime() { return occuranceTime; } public void setPitch(float pitch) { this.pitch = pitch; } public float getPitch() { return pitch; } } public class MakePitchesList { String[] pitches; List<Pitch> listOfPitches = new ArrayList<Pitch>(); public List<Pitch> getListOfPitches(){ getPitches(); for (String pitchString: pitches) { Pitch pitch = new Pitch(); makeListOfPitches(pitch, pitchString); } return listOfPitches; } public void makeListOfPitches(Pitch pitch, String pitchString){ pitch.setPitch(getPitchesInfo(pitchString, 1)); pitch.setOccuranceTime(getPitchesInfo(pitchString, 0)); listOfPitches.add(pitch); } public String[] getPitches() { pitches = pitchesRaw.split("\\r?\\n"); return pitches; } private float getPitchesInfo(String pitch, int position){ String[] frequencyAndTime = pitch.split("\\:"); if(position == 0){ return Float.parseFloat(frequencyAndTime[0].replace(',', '.')); } if(position == 1){ return Float.parseFloat(frequencyAndTime[1].replace(',', '.')); } else return 0; } String pitchesRaw = "0,14:23281,61\n" + "0,23:53,65\n" + "0,37:72,53\n" + "0,56:86,09\n" + "0,60:88,58\n" + "0,65:87,45\n" + "0,70:87,11\n" + "0,74:89,56\n" + "0,79:96,22\n" + "0,84:23288,24\n" + "0,88:103,92\n" + "0,93:107,46\n" + "0,98:108,02\n" + "1,02:107,51\n" + "1,07:104,92\n" + "1,11:105,94\n" + "1,16:106,40\n" + "1,21:104,43\n" + "1,25:104,93\n" + "1,30:108,01\n" + "1,35:316,81\n" + "1,39:103,98\n" + "1,44:23297,42\n" + "1,49:23357,42\n" + "1,53:23359,74\n" + "1,58:23393,04\n" + "1,63:23244,18\n" + "1,67:23220,51\n" + "1,72:23250,06\n" + "1,76:23288,84\n" + "1,81:23241,81\n" + "1,86:23295,22\n" + "1,90:23268,04\n" + "1,95:23252,78\n" + "2,00:23224,22\n" + "2,04:23429,71\n" + "2,09:23214,58\n" + "2,14:23240,70\n" + "2,18:23237,71\n" + "2,23:23231,22\n" + "2,28:23222,77\n" + "2,32:23239,73\n" + "2,37:23235,98\n" + "2,41:23222,16\n" + "2,46:23224,01\n" + "2,51:23214,26\n" + "2,55:23223,20\n" + "2,60:23234,11\n" + "2,65:23221,65\n" + "2,69:23213,45\n" + "2,74:23217,44\n" + "2,79:23235,93\n" + "2,83:11122,79\n" + "2,88:23234,58\n" + "2,93:23229,52\n" + "2,97:23255,48\n" + "3,02:23254,44\n" + "3,07:23355,41\n" + "3,44:105,48\n" + "3,48:115,45\n" + "3,53:117,78\n" + "3,58:127,36\n" + "3,62:131,24\n" + "3,67:130,33\n" + "3,72:131,93\n" + "3,76:127,32\n" + "3,81:117,18\n" + "3,85:117,80\n" + "3,90:117,15\n" + "3,95:121,04\n" + "3,99:131,22\n" + "4,04:130,38\n" + "4,09:130,34\n" + "4,13:129,57\n" + "4,18:120,38\n" + "4,23:121,06\n" + "4,32:100,12\n" + "4,37:23483,16\n" + "4,41:112,95\n" + "4,46:23448,04\n" + "4,50:23396,09\n" + "4,55:23292,90\n" + "4,60:117,21\n" + "4,64:116,58\n" + "4,69:116,62\n" + "4,74:119,18\n" + "4,78:131,19\n" + "4,83:130,34\n" + "4,88:129,59\n" + "4,92:132,64\n" + "4,97:129,68\n" + "5,02:132,71\n" + "5,06:133,57\n" + "5,11:128,94\n" + "5,15:131,09\n" + "5,20:132,75\n" + "5,25:129,68\n" + "5,29:131,26\n" + "5,34:131,22\n" + "5,39:130,38\n" + "5,43:146,01\n" + "5,48:140,43\n" + "5,57:23450,16\n" + "5,62:130,46\n" + "5,67:132,02\n" + "5,71:23243,22\n" + "5,76:23456,28\n" + "5,85:23246,64\n" + "5,90:23274,97\n" + "5,94:23310,30\n" + "5,99:23229,71\n" + "6,08:23214,33\n" + "6,13:23221,53\n" + "6,18:23263,48\n" + "6,22:23213,17\n" + "6,27:23235,04\n" + "6,32:23222,02\n" + "6,36:23214,90\n" + "6,41:23230,05\n" + "6,46:23212,55\n" + "6,50:23221,33\n" + "6,55:23226,70\n" + "6,59:23217,07\n" + "6,64:23272,07\n" + "6,69:11102,74\n" + "6,73:23263,38\n" + "6,78:23217,53\n" + "6,97:23243,63\n" + "7,11:23214,11\n" + "7,15:23229,58\n" + "7,20:23225,70\n" + "7,24:23244,82\n" + "7,29:23243,09\n" + "7,34:23249,66\n" + "7,38:23226,67\n" + "7,43:23246,31\n" + "7,48:23258,55\n" + "7,52:23230,34\n" + "7,57:23225,60\n" + "7,62:23280,25\n" + "7,66:23238,08\n" + "7,71:23221,47\n" + "7,85:117,87\n" + "7,89:117,19\n" + "7,94:117,21\n" + "7,99:117,21\n" + "8,03:116,57\n" + "8,08:119,10\n" + "8,13:44,01\n" + "8,17:129,52\n" + "8,22:132,72\n" + "8,27:143,19\n" + "8,31:141,13\n" + "8,36:139,35\n" + "8,45:132,82\n" + "8,50:129,76\n" + "8,54:130,43\n" + "8,68:94,20\n" + "8,78:132,70\n" + "8,82:130,43\n" + "8,87:129,60\n" + "8,92:130,56\n" + "8,96:128,92\n" + "9,01:119,19\n" + "9,06:118,45\n" + "9,10:103,41\n" + "9,15:103,41\n" + "9,20:103,89\n" + "9,24:106,46\n" + "9,29:214,93\n" + "9,33:23427,95\n" + "9,38:23356,01\n" + "9,43:106,41\n" + "9,47:100,57\n" + "9,52:106,39\n" + "9,57:104,40\n" + "9,61:99,70\n" + "9,66:106,42\n" + "9,71:103,50\n" + "9,75:104,47\n" + "9,80:106,97\n" + "9,85:99,68\n" + "9,89:23454,22\n" + "9,94:23299,56\n" + "9,98:23275,30\n" + "10,03:23222,72\n" + "10,08:23246,09\n" + "10,12:23221,14\n" + "10,17:23240,54\n" + "10,22:23246,81\n" + "10,26:23224,74\n" + "10,31:23249,41\n" + "10,36:23214,79\n" + "10,40:23213,46\n" + "10,45:23259,51\n" + "10,50:23217,39\n" + "10,54:23215,36\n" + "10,59:23224,87\n" + "10,63:23242,27\n" + "10,68:23270,82\n" + "10,73:23243,19\n" + "10,77:23222,75\n" + "10,82:23268,78\n" + "10,87:23321,62\n" + "10,91:23259,65\n" + "11,05:23226,24\n" + "11,10:23222,92\n" + "11,15:23218,83\n" + "11,19:23211,71\n" + "11,24:11112,28\n" + "11,28:23261,03\n" + "11,33:23265,31\n" + "11,38:23245,92\n" + "11,42:57,09\n" + "11,61:103,45\n" + "11,66:103,91\n" + "11,70:102,02\n" + "11,75:107,96\n" + "11,80:105,43\n" + "11,84:104,46\n" + "11,89:116,64\n" + "11,94:115,99\n" + "11,98:114,77\n" + "12,03:121,72\n" + "12,07:123,16\n" + "12,12:125,12\n" + "12,17:128,85\n" + "12,21:120,37\n" + "12,26:116,52\n" + "12,31:130,55\n" + "12,35:131,06\n" + "12,40:131,89\n" + "12,45:128,88\n" + "12,49:23397,75\n" + "12,59:118,45\n" + "12,63:116,54\n" + "12,68:119,70\n" + "12,72:115,45\n" + "12,77:115,30\n" + "12,82:119,86\n" + "12,86:116,59\n" + "12,91:114,13\n" + "12,96:119,04\n" + "13,00:118,47\n" + "13,05:115,38\n" + "13,10:128,92\n"; } public class MakeWordsList { List<Pitch> pitches; public List<List<Pitch>> getWordsList(List<Pitch> pitchList) { return makeWordsList(pitchList); } List<Pitch> oneWord = new ArrayList<>(); List<List<Pitch>> wordList = new ArrayList<>(); public List<List<Pitch>> makeWordsList(List<Pitch> pitchList){ pitches = pitchList; int pauseCounter = 0; for (int i = 0; i < pitchList.size(); i++) { if(pitchList.get(i).getPitch() > 10000){ pauseCounter++; } else { if(pauseCounter > 0){ if(pauseCounter >= 5){ wordList.add(oneWord); oneWord = new ArrayList<>(); } pauseCounter = 0; } oneWord.add(pitchList.get(i)); } } if(oneWord.size() > 0){ wordList.add(oneWord); } return wordList; } } Now from that wordsList I create a scrollable GraphView that on paper would look something like this. Now I have set the boundaries for the GraphView: MinX = -0.8; MaxX = 0.4. This way I'm showing 1 sec at a time on screen. Then I start a thread so it would change the coordinates of the GraphView by 0.1 every 100ms, which should add up as 1 every sec. Here it is in code: public class SongPlayer extends AppCompatActivity { private Viewport graphViewPort; private Handler handler; private Runnable runnable; private GraphView graph; private DataPoint[] points; private LineGraphSeries<DataPoint> series; private int seriesNr; final static double GRAPH_STARTING_X = -0.8; final static double GRAPH_ENDING_X = 0.4; private double orderNr = GRAPH_STARTING_X; private List<Pitch> pitchesList; List<List<Pitch>> wordsList; #SuppressLint("ClickableViewAccessibility") #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.song_player); Intent intent = getIntent(); //Get Textview and Button playRecordButton = (ImageButton) findViewById(R.id.playRecord); //Initialize pitches and words MakePitchesList listOfPithes = new MakePitchesList(); MakeWordsList listOfWords = new MakeWordsList(); pitchesList = listOfPithes.getListOfPitches(); wordsList = listOfWords.getWordsList(pitchesList); //Initialize graph graph = (GraphView) findViewById(R.id.graph); initGraph(); //ViewPort graphViewPort = graph.getViewport(); //Handler handler = new Handler(); playRecordButton.setOnTouchListener(new View.OnTouchListener() { #Override public boolean onTouch(View view, MotionEvent motionevent) { final int action = motionevent.getAction(); if (action == MotionEvent.ACTION_DOWN) { //Start playing audio playMedia(); //Start moving graph drawAndMoveGraph(); } else if (action == MotionEvent.ACTION_UP) { //Stop moving graph and set them to the beginning resetGraph(); //Stop Playing audio stopAudio(); }//end else return false; } //end onTouch }); //end b my button } private void drawAndMoveGraph(){ runnable = new Runnable() { public void run() { System.out.println(orderNr); graphViewPort.setMinX(orderNr); graphViewPort.setMaxX(orderNr + 1); graph.invalidate(); if(pitchesList.size() != orderNr){ orderNr = orderNr + 0.1; // System.out.println(orderNr); } handler.postDelayed(this, 100); } }; runnable.run(); } private void initGraph(){ for (int i = 0; i < wordsList.size(); i++) { seriesNr = 0; points = new DataPoint[wordsList.get(i).size()]; for (Pitch pitch: wordsList.get(i)) { points[seriesNr] = new DataPoint(pitch.getOccuranceTime(), pitch.getPitch()); seriesNr++; } series = new LineGraphSeries<>(points); series.setThickness(15); graph.addSeries(series); } //VocalTestPoints PointsGraphSeries<DataPoint> series = new PointsGraphSeries<>(new DataPoint[] { new DataPoint(0, 50), new DataPoint(0, 75), new DataPoint(0, 100), new DataPoint(0, 125), new DataPoint(0, 150), new DataPoint(0, 175), new DataPoint(0, 200), new DataPoint(0, 225), new DataPoint(0, 250), new DataPoint(0, 275), }); series.setSize(5); series.setColor(Color.YELLOW); graph.addSeries(series); // set manual X bounds graph.getViewport().setYAxisBoundsManual(true); graph.getViewport().setMinY(-50); graph.getViewport().setMaxY(400); graph.getViewport().setXAxisBoundsManual(true); graph.getViewport().setMinX(GRAPH_STARTING_X); graph.getViewport().setMaxX(GRAPH_ENDING_X); //mitu korraga näeb graph.getViewport().setScrollable(true); } private void playMedia(int songIndex){ StorageUtil storage = new StorageUtil(getApplicationContext()); storage.storeAudio(audioList); storage.storeAudioIndex(songIndex); mediaPlayer = new MediaPlayer(); //Reset so that the MediaPlayer is not pointing to another data source mediaPlayer.reset(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(storage.loadAudio().get(storage.loadAudioIndex()).getData()); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.prepareAsync(); // mediaPlayer.prepare(); // might take long! (for buffering, etc) mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { #Override public void onPrepared(MediaPlayer mp) { mediaPlayer.start(); } }); } private void stopAudio(){ mediaPlayer.stop(); mediaPlayer.release(); } private void resetGraph(){ handler.removeCallbacks(runnable); graphViewPort.setMinX(GRAPH_STARTING_X); graphViewPort.setMaxX(GRAPH_ENDING_X); graph.invalidate(); orderNr = GRAPH_STARTING_X; } } To sum up what the code does: it gets the wordsList from the pitches, initializes the graph, starts listening button click. When button is clicked, it starts moving graph as described above and plays audio. The problem is that the audio and moving graphView go out of sync. For the first 10sec or so it works like it should but then the lines start falling behind. I would really appreciate if someone took their time to understand all of this mess. Maybe picture of the actual final graphView will also help. . Blue line is the first incoming word.
Building String name using concatenation with a for loop
I want to create a run time String name in Java. I tried something like using in JavaScript, but it is printing value like Status_Name_0 instead Open assigned to the String Status_Name_0 public static void GetPaymentStatusList(){ int i=0; String Status_Name_0="Open"; String Status_ID_0="0"; String Status_Name_1="Approved"; String Status_ID_1="1"; String Status_Name_2="Denied"; String Status_ID_2="2"; for(i=0; i<3; i++){ Vars.PaymentStatusName_List.add("Status_Name_"+i); Vars.PaymentStatusId_List.add("Status_ID_"+i); } }
but it is printing value like Status_Name_0 instead Open Because that's what you added to the list... add("Status_Name_"+i); The way to get what you want would be a Map<String, String> Map<String, String> map = new HashMap<>(); map.put("Status_Name_0", "Open"); // ... for (int i=0;i<map.size();i++) { String open = map.get("Status_Name_"+i); } How about you make some class instead, though? public class PaymentStatus { int id; String name; public PaymentStatus(int id, String name) { this.id = id; this.name = name; } #Override public String toString() { return String.format("%s[id: %d, name: %s]", getClass().getSimpleName(), id, name); } } And a List<PaymentStatus> would be preferred over appending integers to any variables. public static List<PaymentStatus> getPaymentStatusList() { List<PaymentStatus> list = new ArrayList<>(); paymentStatusList.add(new PaymentStatus(0, "Open")); paymentStatusList.add(new PaymentStatus(1, "Approved")); paymentStatusList.add(new PaymentStatus(2, "Denied")); return list; }
You're actually concatenating the string "Status_name_" with "0" which would result in "Status_name_0", a string, not a variable like Status_name_0. As far as I understand, you want the values of String_name_i (i= 0, 1, 2,....). To get that working, use String array. String[] string_names = { "Open", "Approved", "Denied" }; int[] string_id = { 0, 1, 2 }; :You may not need a string_id array, as you can use the values of i in the for loop. And add them in the list like: Vars.PaymentStatusName_List.add(string_name[i]);
StringBuilder param = new StringBuilder(); param.append("shopid" + "=" + shopDetails.getShopId() + "&" + "username" + "=" + userDetail.getUserName() + "&" + "userid" + "=" + userDetail.getUserId() + "&"); for (int i = 0; i < brandList.size(); i++) { param.append("brandId" + "[" + i + "]" + "=" + brandList.get(i).getBrandId() + "&" + "shortqua" + "[" + i + "]" + "=" + shortageStockList.get(i) + "&"); } param.append("lattude" + "=" + String.valueOf(latitude) + "&" + "longitude" + "=" + String.valueOf(longitude));
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() + ")";
detecting same variable in a method Java JDT parser
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 :)
Java program that outputs an XML file - multiple issues
I'm new to this so please forgive me if I tagged something incorrectly or left something out. I'm writing a java program (new to java also) - the purpose of the program is to generate an XML file with information from multiple databases. The setup - I have sql.java which is the main class and has the main method. Sql.java calls methods located in the CCReturns.java class, GBLRets.java class, and CWSReturns.java class. Each method returns a string of XML containing pertinent information and then the main method in sql.java puts them all together in one string and creates an xml file. Problem: One of my methods in CWSReturns should return a resultset containing 74 rows in all but is only returning the data from one of the rows. When I put this same code into the sql.java main method all 74 rows are returned in the console but the xml file only shows the data from one of the rows and all of the data from all of my other methods is repeated even though I only need it to output once. What would be the best way to go about fixing this issue? I'm stumped. Method in CWSReturns: public static String getUnitInfo(Connection connection, Statement stmt, ResultSet rs) throws SQLException, ClassNotFoundException { String unitinfo = null; //Get Connection connection = getCWSConnection(); //Create the SQL Query and put it into a String Variable stmt = connection.createStatement(); //Pull Policy Claim Unit Information from CLM_UNIT Table String query = "SELECT CLUT.UNIT_TYPE AS CLUNITTYPE, CLUT.UNIT_SUBTYPE AS CLUNITSUBTYPE, CLUT.UNIT_CATEGORY AS CLUNITCATEGORY, CLUT.UNIT_IDENTIFIER AS CLUNITIDENTIFIER, CLUT.UNIT_NUM AS CLUNITNUM, " + "CLUT.YEAR AS CLUNITYEAR, CLUT.MAKE AS CLMAKE, CLUT.MODEL AS CLMODEL, CLUT.VEHICLE_ID AS CLVEHICLEID, CLUT.ITEM_DESC1 AS CLITEMDESC1, CLUT.LICENSE, " + "DAM.LOCATION1, DAM.DESC1, " + "UNT.UNIT_TYPE, UNT.UNIT_SUB_TYPE, UNT.UNIT_CATEGORY, UNT.UNIT_IDENTIFIER, UNT.UNIT_NUM, UNT.YEAR, UNT.MAKE, UNT.MODEL, UNT.VEHICLE_ID, UNT.LICENSE, UNT.ITEM_DESC, " + //Pull Coverage Information from POL_COVERAGE Table "COV.COVERAGE_TYPE, COV.DED_TYPE_CODE1, COV.DEDUCTIBLE1, COV.DED_TYPE_CODE2, COV.DEDUCTIBLE2, COV.DED_TYPE_CODE3, COV.DEDUCTIBLE3, COV.LIMIT_TYPE1, COV.LIMIT1, " + "COV.LIMIT_TYPE2, COV.LIMIT2, COV.LIMIT_TYPE3, COV.LIMIT3, COV.LIMIT_TYPE4, COV.LIMIT4 " + "FROM DB2ADMIN.CLM_CLAIM CLM, DB2ADMIN.CLM_UNIT CLUT, DB2ADMIN.POL_GENERAL_REC POL, DB2ADMIN.POL_UNIT UNT, DB2ADMIN.POL_COVERAGE COV, DB2ADMIN.CLM_DAMAGE DAM " + "WHERE CLM.CLAIM_ID = CLUT.CLAIM_ID AND CLM.POLICY_ID = POL.POLICY_ID AND POL.POLICY_ID = UNT.POLICY_ID AND UNT.POL_UNIT_ID = COV.POL_UNIT_ID AND CLUT.UNIT_ID = DAM.UNIT_ID " + "AND CLM.CLAIM_ID = 14701"; //Execute the query and save it as a ResultSet rs = stmt.executeQuery(query); //Pull out all of the information and save it as a string while(rs.next()) { //Retrieve by column name //Claim Unit Info String CL_UNIT_YEAR = "<CL_UNIT_YEAR>" + rs.getString("CLUNITYEAR") + "</CL_UNIT_YEAR>\n"; String CL_UNIT_TYPE = "<CL_UNIT_TYPE>" + rs.getString("CLUNITTYPE") + "</CL_UNIT_TYPE>\n"; String CL_UNIT_SUB_TYPE = "<CL_UNIT_SUB_TYPE>" + rs.getString("CLUNITSUBTYPE") + "</CL_UNIT_SUB_TYPE>\n"; String CL_UNIT_CATEGORY = "<CL_UNIT_CATEGORY>" + rs.getString("CLUNITCATEGORY") + "</CL_UNIT_CATEGORY>\n"; String CL_UNIT_IDENTIFIER = "<CL_UNIT_IDENTIFIER>" + rs.getString("CLUNITIDENTIFIER") + "</CL_UNIT_IDENTIFIER>\n"; String CL_UNIT_NUM = "<CL_UNIT_NUM>" + rs.getString("CLUNITNUM") + "</CL_UNIT_NUM>\n"; String CL_UNIT_MAKE = "<CL_UNIT_MAKE>" + rs.getString("CLMAKE") + "</CL_UNIT_MAKE>\n"; String CL_UNIT_MODEL = "<CL_UNIT_MODEL>" + rs.getString("CLMODEL") + "</CL_UNIT_MODEL>\n"; String CL_UNIT_VEH_ID = "<CL_UNIT_VEH_ID>" + rs.getString("CLVEHICLEID") + "</CL_UNIT_VEH_ID>\n"; String CL_UNIT_DESC1 = "<CL_UNIT_DESC1>" + rs.getString("CLITEMDESC1") + "</CL_UNIT_DESC1>\n"; String TAG_NUMBER = "<TAG_NUMBER>" + rs.getString("LICENSE") + "</TAG_NUMBER>\n"; String DAMLOC = "<DAMAGE_LOCATION>" + rs.getString("LOCATION1") + "</DAMAGE_LOCATION>\n"; String DAMDESC = "<DAMAGE_DESCRIPTION>" + rs.getString("DESC1") + "</DAMAGE_DESCRIPTION>\n"; String UNIT_TYPE = "<UNIT_TYPE>" + rs.getString("UNIT_TYPE") + "</UNIT_TYPE>\n"; String UNIT_SUB_TYPE = "<UNIT_SUB_TYPE>" + rs.getString("UNIT_SUB_TYPE") + "</UNIT_SUB_TYPE>\n"; String UNIT_CATEGORY = "<UNIT_CATEGORY>" + rs.getString("UNIT_CATEGORY") + "</UNIT_CATEGORY>\n"; String UNIT_IDENTIFIER = "<UNIT_IDENTIFIER>" + rs.getString("UNIT_IDENTIFIER") + "</UNIT_IDENTIFIER>\n"; String UNIT_NUMBER = "<UNIT_NUMBER>" + rs.getString("UNIT_NUM") + "</UNIT_NUMBER>\n"; String UNIT_YEAR = "<UNIT_YEAR>" + rs.getString("YEAR") + "</UNIT_YEAR>\n"; String UNIT_MAKE = "<UNIT_MAKE>" + rs.getString("MAKE") + "</UNIT_MAKE>\n"; String UNIT_MODEL = "<UNIT_MODEL>" + rs.getString("MODEL") + "</UNIT_MODEL>\n"; String VEH_ID = "<VEH_ID>" + rs.getString("VEHICLE_ID") + "</VEH_ID>\n"; String ITEM_DESC = "<ITEM_DESC>" + rs.getString("ITEM_DESC") + "</ITEM_DESC>\n"; //Coverage Info String COVERAGE_TYPE = "<COVERAGE_TYPE>" + rs.getString("COVERAGE_TYPE") + "</COVERAGE_TYPE>\n"; String DED_TYPE_CODE1 = "<DED_TYPE_CODE1>" + rs.getString("DED_TYPE_CODE1") + "</DED_TYPE_CODE1>\n"; String DEDUCTIBLE1 = "<DEDUCTIBLE1>" + rs.getString("DEDUCTIBLE1") + "</DEDUCTIBLE1>\n"; String DED_TYPE_CODE2 = "<DED_TYPE_CODE2>" + rs.getString("DED_TYPE_CODE2") + "</DED_TYPE_CODE2>\n"; String DEDUCTIBLE2 = "<DEDUCTIBLE2>" + rs.getString("DEDUCTIBLE2") + "</DEDUCTIBLE2>\n"; String DED_TYPE_CODE3 = "<DED_TYPE_CODE3>" + rs.getString("DED_TYPE_CODE3") + "</DED_TYPE_CODE3>\n"; String DEDUCTIBLE3 = "<DEDUCTIBLE3>" + rs.getString("DEDUCTIBLE3") + "</DEDUCTIBLE3>\n"; String LIMIT_TYPE1 = "<LIMIT_TYPE1>" + rs.getString("LIMIT_TYPE1") + "</LIMIT_TYPE1>\n"; String LIMIT1 = "<LIMIT1>" + rs.getString("LIMIT1") + "</LIMIT1>\n"; String LIMIT_TYPE2 = "<LIMIT_TYPE2>" + rs.getString("LIMIT_TYPE2") + "</LIMIT_TYPE2>\n"; String LIMIT2 = "<LIMIT2>" + rs.getString("LIMIT2") + "</LIMIT2>\n"; String LIMIT_TYPE3 = "<LIMIT_TYPE3>" + rs.getString("LIMIT_TYPE3") + "</LIMIT_TYPE3>\n"; String LIMIT3 = "<LIMIT3>" + rs.getString("LIMIT3") + "</LIMIT3>\n"; String LIMIT_TYPE4 = "<LIMIT_TYPE4>" + rs.getString("LIMIT_TYPE4") + "</LIMIT_TYPE4>\n"; String LIMIT4 = "<LIMIT4>" + rs.getString("LIMIT4") + "</LIMIT4>\n"; //Create one large string that incorporates all of the above nodes String unitinfo1 = CL_UNIT_YEAR + CL_UNIT_TYPE + CL_UNIT_SUB_TYPE + CL_UNIT_CATEGORY + CL_UNIT_IDENTIFIER + CL_UNIT_NUM + CL_UNIT_MAKE + CL_UNIT_MODEL + CL_UNIT_VEH_ID + CL_UNIT_DESC1 + TAG_NUMBER + DAMLOC + DAMDESC + UNIT_TYPE + UNIT_SUB_TYPE + UNIT_CATEGORY + UNIT_IDENTIFIER + UNIT_NUMBER + UNIT_YEAR + UNIT_MAKE + UNIT_MODEL + VEH_ID + ITEM_DESC + COVERAGE_TYPE + DED_TYPE_CODE1 + DEDUCTIBLE1 + DED_TYPE_CODE2 + DEDUCTIBLE2 + DED_TYPE_CODE3 + DEDUCTIBLE3 + LIMIT_TYPE1 + LIMIT1 + LIMIT_TYPE2 + LIMIT2 + LIMIT_TYPE3 + LIMIT3 + LIMIT_TYPE4 + LIMIT4; return unitinfo1; } stmt.close(); rs.close(); connection.close(); return unitinfo; } sql.java - main method snippet: //Get unit info String unitinfo = CWSReturns.getUnitInfo(connection, stmt, rs); String xmlStr = (Root+mainclaimnode+mainclaiminfo+lossState+clientname+clientaddress+communicationinfo+agentname+adjustername+secondaryclientname+policyinfo+cancelpendinginfo+endmainclaimnode+claimunitnode+unitinfo+OIPName+OIPAddress+rollinjuryinfo+unitaddress+endclaimunitnode+EndRoot); Document doc = convertStringToDocument(xmlStr); String str = convertDocumentToString(doc); System.out.println(str); PrintWriter writer = new PrintWriter("C:\\Temp\\TestXML.xml"); writer.println(str); writer.close(); Output when running method from CWSReturns (only one resultset returned...) <CWS_XML> <MAIN_CLAIM_INFO> <CLAIM_ID>14701</CLAIM_ID> <DATE_LOSS>2013-09-01 04:00:00.0</DATE_LOSS> <CLAIM_MADE_DATE>null</CLAIM_MADE_DATE> <CALLER_NAME>asdf asdf</CALLER_NAME> <ACTUAL_NOT_DATE>2014-02-25 10:25:00.0</ACTUAL_NOT_DATE> <METHOD_REPORT>PHONE</METHOD_REPORT> <NAME_TYPE_FLAG>I</NAME_TYPE_FLAG> <NAME_TYPE>null</NAME_TYPE> <NAME_PREFIX>null</NAME_PREFIX> <LAST_NAME>Luke</LAST_NAME> <NAME_SUFFIX>null</NAME_SUFFIX> </MAIN_CLAIM_INFO> **<CLAIM_UNIT_INFO> <CL_UNIT_YEAR>2014</CL_UNIT_YEAR> <CL_UNIT_TYPE>DRIVE_OTHR</CL_UNIT_TYPE> <CL_UNIT_SUB_TYPE>COMBO</CL_UNIT_SUB_TYPE> <CL_UNIT_CATEGORY>DRIVE_OTHR</CL_UNIT_CATEGORY> <CL_UNIT_IDENTIFIER>2014 Cadillac</CL_UNIT_IDENTIFIER> <CL_UNIT_NUM/> <CL_UNIT_MAKE>Cadillac </CL_UNIT_MAKE> <CL_UNIT_MODEL/> <CL_UNIT_VEH_ID/> <CL_UNIT_DESC1>null</CL_UNIT_DESC1> <TAG_NUMBER/> <DAMAGE_LOCATION>Unknown</DAMAGE_LOCATION> <DAMAGE_DESCRIPTION>Unknown</DAMAGE_DESCRIPTION> <UNIT_TYPE>NON_OWNED</UNIT_TYPE> <UNIT_SUB_TYPE>COMBO</UNIT_SUB_TYPE> <UNIT_CATEGORY>NON_OWNED</UNIT_CATEGORY> <UNIT_IDENTIFIER>NON OWNED</UNIT_IDENTIFIER> <UNIT_NUMBER>null</UNIT_NUMBER> <UNIT_YEAR>null</UNIT_YEAR> <UNIT_MAKE>null</UNIT_MAKE> <UNIT_MODEL>null</UNIT_MODEL> <VEH_ID>null</VEH_ID> <ITEM_DESC>null</ITEM_DESC> <COVERAGE_TYPE>ADB</COVERAGE_TYPE> <DED_TYPE_CODE1>null</DED_TYPE_CODE1> <DEDUCTIBLE1>null</DEDUCTIBLE1> <DED_TYPE_CODE2>null</DED_TYPE_CODE2> <DEDUCTIBLE2>null</DEDUCTIBLE2> <DED_TYPE_CODE3>null</DED_TYPE_CODE3> <DEDUCTIBLE3>null</DEDUCTIBLE3> <LIMIT_TYPE1>LIM</LIMIT_TYPE1> <LIMIT1>15000.000</LIMIT1> <LIMIT_TYPE2>null</LIMIT_TYPE2> <LIMIT2>null</LIMIT2> <LIMIT_TYPE3>null</LIMIT_TYPE3> <LIMIT3>null</LIMIT3> <LIMIT_TYPE4>null</LIMIT_TYPE4> <LIMIT4>null</LIMIT4> <OIP_NAME>Null</OIP_NAME> <OIP_ADDR>Null</OIP_ADDR> <ROLE_TYPE>DRIVER</ROLE_TYPE> <INJURY_TEXT>head</INJURY_TEXT> <CL_UNIT_ID>Null</CL_UNIT_ID> <CL_UNIT_HOUSE>Null</CL_UNIT_HOUSE> <CL_UNIT_ADDR1>Null</CL_UNIT_ADDR1> <CL_UNIT_ADDR2>Null</CL_UNIT_ADDR2> <CL_UNIT_CITY>Null</CL_UNIT_CITY> <CL_UNIT_STATE>Null</CL_UNIT_STATE> <CL_UNIT_ZIP>Null</CL_UNIT_ZIP> </CLAIM_UNIT_INFO>** </CWS_XML> The elements in the "CLAIM_UNIT_INFO" node should repeat upwards of 74 times...
Inside the while loop you are returning. So it iterates only one time. Make unitinfo in getUnitInfo() method as a StringBuilder and inside the while(rs.next) instead or returning append the unitinfo1 to unitinfo public static String getUnitInfo(Connection connection, Statement stmt, ResultSet rs) throws SQLException, ClassNotFoundException { StringBuilder unitinfo = new StringBuilder(); ... while(rs.next()) { ... unitinfo.append("<CLAIM_UNIT_INFO>"); //Create one large string that incorporates all of the above nodes String unitinfo1 = CL_UNIT_YEAR + CL_UNIT_TYPE + CL_UNIT_SUB_TYPE + CL_UNIT_CATEGORY + CL_UNIT_IDENTIFIER + CL_UNIT_NUM + CL_UNIT_MAKE + CL_UNIT_MODEL + CL_UNIT_VEH_ID + CL_UNIT_DESC1 + TAG_NUMBER + DAMLOC + DAMDESC + UNIT_TYPE + UNIT_SUB_TYPE + UNIT_CATEGORY + UNIT_IDENTIFIER + UNIT_NUMBER + UNIT_YEAR + UNIT_MAKE + UNIT_MODEL + VEH_ID + ITEM_DESC + COVERAGE_TYPE + DED_TYPE_CODE1 + DEDUCTIBLE1 + DED_TYPE_CODE2 + DEDUCTIBLE2 + DED_TYPE_CODE3 + DEDUCTIBLE3 + LIMIT_TYPE1 + LIMIT1 + LIMIT_TYPE2 + LIMIT2 + LIMIT_TYPE3 + LIMIT3 + LIMIT_TYPE4 + LIMIT4; unitinfo.append(unitinfo1); unitinfo.append("</CLAIM_UNIT_INFO>"); } ... return unitinfo.toString(); }
As #SyamS mentioned you are returning inside of your loop. If you don't want to combine all of the rows into one String: One way to fix this would be to store the String found in the loop into an ArrayList, and then return the ArrayList of String. You would have to change the return type of your method, and handle iterating through the resulting ArrayList when you called the method. public static ArrayList<String> getUnitInfo(...){ ArrayList<String> unitinfo = new ArrayList<String>(); ... while(...){ ... unitinfo.add(unitinfo1); // Instead of return } ... return unitinfo; // Only return at the end }
The reason this is happening is because you have return unitinfo1 inside your while loop. So it is just returning after the first row has been populated. You need to declare String unitinfo1 outside of the while loop, and append each line to the string during each iteration of the loop. String unitinfo1; while(condition) { unitinfo1.append(nextLine); } return unitinfo1;