Help with insertion into an array
I'm trying to create a method that inserts a number at an index of an array, but throws an exception if the index is out of range or if there is already an element stored at that index of the array.
void insert (R x, int i) with x being the number inserted, and i the index. Any help is greatly appreciated.
BigDaddyLoveHandles wrote:
sethaw wrote:
1. Create a new array that is big enough to hold all the numbers from the old array plus the new element.
2. Copy the values from the old array to the correct position in the new array. You may want to use 2 different for loops, one to copy the values before the new element and one to copy the values after the new element.
3. Set the array variable that is pointing to the old array to be the new array that you just created.Why not attempt to do 1, then 2, then 3? The code you posted in reply #3 was worthless, I hope you can see this: it assigned the value x to every position in the array!And there are curly braces missing!!! :)
I hate when people omit the braces...lazy bastages.
Similar Messages
-
Hi,
I have 2 tables. In 1st one, I insert a record, and a PRE-INSERT based trigger modify value of columns CODE. I then need to insert a record in my 2nd table with the value insert in TABLE1.CODE (FK/PK). I tried to use returning clause like this :
PROCEDURE CONVERTIR_DOCVENTE(PCODE IN CHAR) IS
VCODE TABLE1.CODE%TYPE;
BEGIN
INSERT INTO TABLE1 ... RETURNING CODE INTO VCODE;
INSERT INTO TABLE2 VALUES(VCODE);
END;
It does not work (ORA-00933: SQL command not properly ended at line 4)
any idea ?
nullTABLE1 : CODE CHAR(10) PK,DESIG VARCHAR2(100)
TABLE2 : CODE CHAR(10) PK,TABLE1_CODE CHAR(10) FK,DESIG VARCHAR2(100)
Both have a sequence on CODE
I need to insert in TABLE1 'My master record' and in TABLE2 'Child record 1' and 'Child record 2'.
When I insert 'My master record' in TABLE 1 (INSERT into TABLE1(DESIG) values('My master record')), a trigger query my sequence and fetch CODE column. When I then insert 'Child record 1' and 'Child record 2', I need to know the value inserted in TABLE1.CODE to insert it in TABLE2.TABLE1_CODE (INSERT into TABLE2(TABLE1_CODE,DESIG) values(??????,'Child record X')). That's why I need to use RETURNING clause in the first INSERT order.
But it doesn't works (ORA-00933: SQL command not properly ended at line 4)
Note : All my orders are in a stored procedure.
<BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by Riaz Shahid ([email protected]):
Hi!
Would u clearifiy ur point please so that i can advise you. Feel free to mail me.
Regards
<HR></BLOCKQUOTE>
null -
Need help with INSERT and WITH clause
I wrote sql statement which correctly work, but how i use this statment with INSERT query? NEED HELP. when i wrote insert i see error "ORA 32034: unsupported use of with clause"
with t1 as(
select a.budat,a.monat as period,b.vtweg,
c.gjahr,c.buzei,c.shkzg,c.hkont, c.prctr,
c.wrbtr,
c.matnr,
c.menge,
a.monat,
c.zuonr
from ldw_v1.BKPF a,ldw_v1.vbrk b, ldw_v1.bseg c
where a.AWTYP='VBRK' and a.BLART='RV' and a.BUKRS='8431' and a.awkey=b.vbeln
and a.bukrs=c.bukrs and a.belnr=c.belnr and a.gjahr=c.gjahr and c.koart='D'
and c.ktosl is null and c.gsber='4466' and a.gjahr>='2011' and b.vtweg='01'
,t2 as(
select a.BUKRS,a.BELNR, a.GJAHR,t1.vtweg,t1.budat,t1.monat from t1, ldw_v1.bkpf a
where t1.zuonr=a.xblnr and a.blart='WL' and bukrs='8431'
,tcogs as (
select t2.budat,t2.monat,t2.vtweg, bseg.gjahr,bseg.hkont,bseg.prctr,
sum(bseg.wrbtr) as COGS,bseg.matnr,bseg.kunnr,sum(bseg.menge) as QUANTITY
from t2, ldw_v1.bseg
where t2.bukrs=bseg.bukrs and t2.belnr=bseg.BELNR and t2.gjahr=bseg.gjahr and BSEG.KOART='S'
group by t2.budat,t2.monat,t2.vtweg, bseg.gjahr,bseg.hkont,bseg.prctr,
bseg.matnr,bseg.kunnr
,t3 as
select a.budat,a.monat,b.vtweg,
c.gjahr,c.buzei,c.shkzg,c.hkont, c.prctr,
case when c.shkzg='S' then c.wrbtr*(-1)
else c.wrbtr end as NTS,
c.matnr,c.kunnr,
c.menge*(-1) as Quantity
from ldw_v1.BKPF a,ldw_v1.vbrk b, ldw_v1.bseg c
where a.AWTYP='VBRK' and a.BLART='RV' and a.BUKRS='8431' and a.awkey=b.vbeln
and a.bukrs=c.bukrs and a.belnr=c.belnr and a.gjahr=c.gjahr and c.koart='S'
and c.ktosl is null and c.gsber='4466' and a.gjahr>='2011' and b.vtweg='01'
,trevenue as (
select t3.budat,t3.monat,t3.vtweg, t3.gjahr,t3.hkont,t3.prctr,
sum(t3.NTS) as NTS,t3.matnr,t3.kunnr,sum(t3.QUANTITY) as QUANTITY
from t3
group by t3.budat,t3.monat,t3.vtweg, t3.gjahr,t3.hkont,t3.prctr,t3.matnr,t3.kunnr
select NVL(tr.budat,tc.budat) as budat,
NVL(tr.monat,tc.monat) as monat,
NVL(tr.vtweg,tc.vtweg) as vtweg,
NVL(tr.gjahr, tc.gjahr) as gjahr,
tr.hkont as NTS_hkont,
tc.hkont as COGS_hkont,
NVL(tr.prctr,tc.prctr) as prctr,
NVL(tr.MATNR, tc.MATNR) as matnr,
NVL(tr.kunnr, tc.kunnr) as kunnr,
NVL(tr.Quantity, tc.Quantity) as Quantity,
tr.NTS as NTS,
tc.COGS as COGS
from trevenue TR full outer join tcogs TC
on TR.BUDAT=TC.BUDAT and TR.MONAT=TC.MONAT and TR.GJAHR=TC.GJAHR
and TR.MATNR=TC.MATNR and TR.KUNNR=TC.KUNNR and TR.QUANTITY=TC.QUANTITY
and TR.VTWEG=TC.VTWEG and TR.PRCTR=TC.PRCTR
Edited by: user13566113 on 25.03.2011 5:26Without seeing what you tried it is hard to say what you did wrong, but this is how it would work
SQL> create table t ( n number );
Table created.
SQL> insert into t
2 with test_data as
3 (select 1 x from dual union all
4 select 2 x from dual union all
5 select 3 x from dual union all
6 select 4 x from dual)
7 select x from test_data;
4 rows created.
SQL> -
Help with inserting values to sql database
Hello everyone I am having this problem with how to fill my values in my sql statement, if you look below you will notice i have set up the values to be the length of the arr (arrayList).
could someone please let me now how i should put there values in.
thanks for yr time
piper3
try {
String data = "jdbc:odbc:myProject";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(data,"","");
StringBuffer sb = new StringBuffer();
Iterator it1 = arr.iterator();
while (it1.hasNext())
if (sb.length() > 0)
sb.append(",");
sb.append(it1.next());
//takes the items of the arInterim
//int iCountInterim = arInterim.size();
int er = arr.size();
String sInterim = new String();
String sql = new String();
for(int i2 = 0; i2 < er; i2++){
sInterim = sInterim + sQuestion;
if(i2 < (er-1)){
sInterim = sInterim + sComma;
sql = "INSERT into Ben (" + sb.toString() + ") values (" + sInterim + ")";
System.out.println(sql);
PreparedStatement prepStmt = con.prepareStatement(sql);
/*prepStmt.setString(1, "hello");
prepStmt.setString(2, "hi");
prepStmt.setString(3, "bye");
prepStmt.executeUpdate();
prepStmt.close();*/
con.close();
} catch (Exception e1) {
System.err.println("Got an exception! ");
System.err.println(e1.getMessage());
//System.out.println();//.size());//tempkey+"\n"+tempvalue);you should write a prepared statement like this:
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
where "?" is a placeholder for the values you want to use.
Then later when you want to actually update your database, first set the placeholders to your values (stored in your array for example) using a statement like this:
updateSales.setString(2, "Colombian");
//sets the 2. placeholder in the statement to the value "Colombian"
after having set all placeholders to a specific value, execute your statement:
updateSales.executeUpdate();
your code should like:
sql = "INSERT into Ben values (?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(sql);
prepStmt.setString(1, "hello");
prepStmt.setString(2, "hi");
prepStmt.setString(3, "bye");
prepStmt.executeUpdate();
prepStmt.close();
HTH
Christine -
Error With Insert Into From Select
Hello,
I have a problem with this query in pl sql developer with oracle 10G:
insert into ca_nrj_rem(imsi,id_gamme_vente,domaine,date_topage,id_produit)
(select a1.* from (select d.imsi, 1, 4, trunc(sysdate - 1), 'NRJ003'
from ca_evenement_vsim a, ca_forfait b, ca_forfait c, ca_vsim_associe d
where a.id_action = 'CP1'
and bao.Lecture_Parametre_XML_V2(a.valeur_parametres, 'ancienCode') = b.code_forfait
and b.code_gamme = 2
and bao.Lecture_Parametre_XML_V2(a.valeur_parametres, 'nouveauCode') = c.code_forfait
and c.code_gamme = 6
and date_trace > sysdate - 6
and a.vsimid = d.vsimid
and d.date_fin is null
group by d.imsi, trunc(sysdate - 1)) a1, ca_nrj_rem n
where a1.imsi=n.imsi(+) and n.imsi is null);
The select statement return X (163) values but the insert statement inserts Y (540) values
Can you help me please ?
Thanks Youuser511447 wrote:
The select statement return X (163) values but the insert statement inserts Y (540) valuesNot possible if the select statements are identical.
You'll have to provide more evidence and example output (format it on the forum by putting {noformat}{noformat} before and after it), so we can see exactly what you are doing.
Are you sure that the table you are inserting into has no rows initially or that you are counting the rows correctly?
Show us exactly what you are doing. -
Need help with inserting 10MB CLOB
Hi,
I have an urgent issue and desperately need some help.
There are several files on a FTP server that I need to insert their contents into a CLOB type column. One of the files has more than 10MB contents. What I've been doing is after connection is made to the FTP server, read in the contents in a file line by line into a String, then execute a SQL INSERT statement to insert a new record into the target table.
+//.... make connection, read in files and parse into a String variable called fileContents+
String psInsert = "Insert into FileTrack (Name, Contents) values";
PreparedStatment ps = conn.prepareStatement(psInsert "(?,?)");+
ps.setString(1, "some name");
ps.setObject(2, fileContents);
ps.executeUpdate();
The above works fine for all other smaller files, except the 10MB one. The error I got was SQLCODE: -302, SQLSTATE: 22001, which is about not enough space issue. So I increased the CLOB column size and made sure it doesn't exceed the initial CLOB size setting and the database has plenty of space for storing this 10MB file. Still, I got the same error.
Then I tried the following:
ps.setObject(2, fileContents, java.sql.Types.CLOB);
Failed with same error...
Then I tried this:
FileInputStream inputStream = new FileInputStream(fileContents);
ps.setAsciiStream(2, inputStream, (int)()fileContents.length()));
Still failed with the same error....
Then I changed to ps.setCharStream()... still failed....
What other options do I have to insert the 10MB contents? Can someone please help?
Thanks heaps in advance!!we're still trying to upload that CLOB. Takes a while over this 2400bps modem ;)
-
Help with printing from an array
hello there, looking for help. Basically i have read a text file into an array. I can print a sentence from the array using startsWith()...if i take that code out, and just put in the last part:
while(!(words.trim()).startsWith("slightly")) {
System.out.println(i + ":" + words[i] + ":");
i++;
this basically prints out the whole text file until it reaches the word slightly. I want to print out text that is in between two words. Now i can stop printing with this , any suggestions on how i can tell it to start printing when it finds a word....
public static void main( String[] args )
int i = 0;
// will store the words read from the file
List<String> wordList = new ArrayList<String>();
BufferedReader br = null;
try
// attempt to open the words file
br = new BufferedReader( new FileReader( "ireland.txt" ) );
String word;
while( ( word = br.readLine() ) != null )
// add the read word to the wordList
wordList.add( word );
} catch( IOException e ) {
e.printStackTrace();
} finally {
try {
// attempt the close the file
br.close();
catch( IOException ex ) {
ex.printStackTrace();
String[] words = new String[ wordList.size() ];
// wordList to our string array words
wordList.toArray( words );
System.out.println(" Returning line ");
// loop and display each word from the words array
/*while(i < words.length )
String tempWord = words[i].trim();
//area
if (tempWord.startsWith("'''Loc"))
System.out.println(i+":"+ words[i]+":" );
i++;
/*while(!(words[i].trim()).startsWith("slightly")) {
System.out.println(i + ":" + words[i] + ":");
i++;This may help, it looks like the same assignment:
http://forum.java.sun.com/thread.jspa?threadID=5144211
Yeah, and it's from the same guy.
Thanks (NOT) for posting yet another thread about the
same problem, tras.D'OH! I didn't even notice that. In what ways were the answers you got in the other thread insufficient? -
A problem with inserting into DB hebrew strings
Hi,
I am working with a 8.1.7 DB version, and use thin driver.
I have my DB Charest configured to iso 8859P8 (which is visual Hebrew)
I have no problem in making a connection and retrieving strings, using SELECT * FROM ..
and then use the ResultSet.getString(String columnName) method .
I also have no problem in inserting the Hebrew characters , and retrieving them back ( I represent them in a servlet ),
The only problem I do have, is when I try to insert into DB a row in the following manner
INSERT into table_name values( Hebrew_String_value1, Hebrew_String_value2, Hebrew_String_value3, Hebrew_String_value4)
the insertion works fine , but somehow the insertion misplaces the strings order and actually the insertion is in opposite order :
Hebrew_String_value4, Hebrew_String_value3, Hebrew_String_value2, Hebrew_String_value1.
If I use the same insert with English Strings , there is no problem.
does any one have the solution how I insert the strings in the right order ?
one solution I have is to insert only one column and then update the table for each column , but then , instead of one execute() action , I have to make ,
1 execute() + 9 executeUpdate() for a 10 column tableCan you try specify the column order in your INSERT statement, i.e.
INSERT INTO mytable( column1_name,
column2_name,
column3_name,
column4_name )
VALUES( column1_string,
column2_string,
column3_string,
column4_string)My wild guess, though I can't understand why at the moment, is that there may be a problem because Hebrew is read from right to left, that may be causing a problem.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
How do I insert into an array only if the condition is true?
I am buiding an array made up of pairs of data from a file. I am going through line by line putting the values in an array and then taking the pairs of two indexes oring them and putting the number into another array. I do not know if there is more than one set on each line so I have to do a while loop to check.The problem is I have to get the indexes in pairs, so for example I take in the element from index 0 and 1 and or them index 2 and 3 and or them, I do not need the combination of 1 and 2 or 3 and 4 and etc. I am using the "Quotient & Remainder" to check if the index is even or odd, if it is even I take that element and the very next index's element, I or them and put them in another array, but if i
t is odd I do not want to put anything into the array. How can I go about doing that? Any help would be appreciated. I am using version 6.1 Thanks, Molly
Attachments:
labview.bmp 3841 KBMolly,
Rather than running while loop which only executes code every other time you could instead just do a little more math to get your index values. Just multiply the iterator (i) terminal by 2 for the first index and then add 1 to it for the second (you'd need to run the loop half as many times of course). This would be more efficient and easier to read in your code. One other tip is that when you are running a loop a specified number of times it's cleaner to use a for loop rather than a while loop.
Regards,
Ryan K.
NI -
Pl/sql block with "insert into" and schema qualified table throws "error"
Simplified test case:
Oracle9i EE Release 9.2.0.3.0
Oracle JDeveloper 9.0.3.2 Build 1145
create user u1 identified by u1
default tablespace users
quota unlimited on users;
grant connect, resource to u1;
revoke unlimited tablespace from u1;
create user u2 identified by u2
default tablespace users
quota unlimited on users;
grant connect, resource to u2;
revoke unlimited tablespace from u2;
As user u2:
create table u2.t
c1 number
grant select, update, insert, delete on u2.t to u1;
As user u1:
create or replace package test_pkg as
procedure do_insert (p_in number);
end;
create or replace package body test_pkg as
procedure do_insert (p_in number) is
begin
insert into u2.t values (p_in);
commit;
end;
end;
All of the above works fine using command-line sql*plus, and is clearly a simplified version of the actual code to demonstrate the issue at hand. Using JDeveloper, it complains about 'expected ;' at the 'values' keyword in the insert statement. Removing the schema qualification from the table name allows JDeveloper to not flag the statement as an error, but I do not want to create synonyms (private or public) to point to all the tables in the real packages. Since JDeveloper flags the insert statement as an error, I can not browse the package structure etc, even though it compiles with no problems. What gives?
Thanks in advance for any suggestions, etc...Hi Bryan,
Thanks for following up on this. I will look for the bug fix to be published.
- Mark -
Issue with INSERT INTO, throws primary key violation error even if the target table is empty
Hi,
I am running a simple
INSERT INTO Table 1 (column 1, column 2, ....., column n)
SELECT column 1, column 2, ....., column n FROM Table 2
Table 1 and Table 2 have same definition(schema).
Table 1 is empty and Table 2 has all the data. Column 1 is primary key and there is NO identity column.
This statement still throws Primary key violation error. Am clueless about this?
How can this happen when the target table is totally empty?
ChintuNope thats not true
Either you're not inserting to the right table or in the background some other trigger code is getting fired which is inserting into some table which causes a PK violation.
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Need Help with Inserting Timeline Markers
Friends,
I have not use my premiere element 3.2 since 2008 and forgot some of the procedures. now, I need help with the insertion of Timeline Markers. I did what the Help Page showed me. But the markers were not effective in the resulting DVD, or, even when viewing the video in the editing page as if thye were not there! Here is what I did:.
1) Click the Timeline button.
2) Click in an empty space in a video or audio track in the Timeline to make the Timeline active and deselect any clips.
3) Move the current-time indicator in the Timeline to the frame where I need the marker.
4) Click the Add Marker icon in the Timeline to place the Marker 5 times where I want them.
5) Verified that each Timeline Marker is present at the intended place.
6) Burned DVD
7) Can NOT jump to any of the intended Marker in the Resulting DVD during playback.
The question is "What did I do wrong or didn't do?" It seems that I did the same before and worked! Please advise!
Also, what are the significance of the Red line just below the Timeline and the yellow bars inside the video and audio frames. But after preforming Timeline/Render Work Area, they were all gone? What purposes do they serve and what is the significance of Rendering? Thank you for your help!
I repeat the process and did a Rendering before making the DVD also. It did not help!
Andy LimSteve,
Long time no talk! You used to help me out many times when the PE-1 through PE-3 came out. I was HOPING you would still be around and you are! You came through again this time! Many thanks to you.
I use the Add DVD Scene button to insert the Markers. They are Green. Made a DVD and the markers work OK although ythey are "effective" during play back using the editing window.
While that problem was solved, will you come back and answer the other two questions concerning Rendering and the Red/Yellow lines? I would appreciate it very much!
Andy Lim
~~~~~~~~~~~~~~~~ -
Help with inserting values -- ORA-00984 error
Hello!
This time we have a problem with inserting values and we really can't find what's wrong!
The table was created as such
CREATE TABLE PASSAGER
(NO_PERSONNE INTEGER,
NO_PASSAGER INTEGER NOT NULL,
NO_PASSEPORT INTEGER NOT NULL,
NATIONALITE VARCHAR2(30) NOT NULL,
LIEU_EMISSION VARCHAR2(30) NOT NULL,
DATE_EMISSION DATE NOT NULL,
NO_TEL INTEGER,
NO_CC INTEGER,
NO_VENTE INTEGER NOT NULL,
CONSTRAINT PK_PASSAGER PRIMARY KEY (NO_PERSONNE),
CONSTRAINT FK_PASSAGER_PERSONNE FOREIGN KEY (NO_PERSONNE) REFERENCES PERSONNE (NO_PERSONNE),
CONSTRAINT FK_PASSAGER_VENTE FOREIGN KEY (NO_VENTE) REFERENCES VENTE (NO_VENTE));
We created a sequence..
CREATE SEQUENCE NOPASS_SEQ
START WITH 1
INCREMENT BY 1
NOCACHE
NOCYCLE;
for inserting the values, we did...
INSERT INTO PASSAGER VALUES (500,NOPASS_SEQ.NEXTVAL, WT456789,'CANADIENNE', 'CANADA', to_date('2007/10/12','YYYY/MM/DD'),5142348756,5157981500126734,1);
but it won't work, it's our last table and all the other worked perfectly!
Thanks a ton!In your table creation, you got third column as
NO_PASSEPORT INTEGER NOT NULL,
where as you are passing varchar values (see bold)
INSERT INTO PASSAGER VALUES (500,NOPASS_SEQ.NEXTVAL, WT456789,+'CANADIENNE', 'CANADA', to_date('2007/10/12','YYYY/MM/DD'),5142348756,5157981500126734,1);
Should be like this I suppose
INSERT INTO PASSAGER VALUES (500,NOPASS_SEQ.NEXTVAL, *456789*,'CANADIENNE', 'CANADA', to_date('2007/10/12','YYYY/MM/DD'),5142348756,5157981500126734,1); -
Hi,
I am having issue in inserting value into table by using select statement.
Source table look like this
acct eff_date amt
1 03/04/2012 100
1 03/05/2012 200
1 03/06/2012 100
target table look like this
acct eff_date end_date amt
1 03/04/2012 03/05/2012 100
1 03/05/2012 03/06/2012 200
1 03/06/2012 default value (12/31/9999) 100
My query is
insert into table_tgt
select
acct,
eff_date,
end_date,
amt
from
select
acct,
eff_date,
amt,
row_number() over(partition by acct order by eff_date) as rn,
lead(eff_date) over(partition by acct order by eff_date) as end_date
from table_src
but the query returns value as
acct eff_date end_date amt
1 03/04/2012 03/05/2012 100
1 03/05/2012 03/06/2012 200
1 03/06/2012 null 100
how to get default value when the value is null.
Kindly help.
Regards,
Punitha936698 wrote:
Hi,
I am having issue in inserting value into table by using select statement.
Source table look like this
acct eff_date amt
1 03/04/2012 100
1 03/05/2012 200
1 03/06/2012 100
target table look like this
acct eff_date end_date amt
1 03/04/2012 03/05/2012 100
1 03/05/2012 03/06/2012 200
1 03/06/2012 default value (12/31/9999) 100
My query is
insert into table_tgt
select
acct,
eff_date,
end_date,
amt
from
select
acct,
eff_date,
amt,
row_number() over(partition by acct order by eff_date) as rn,
lead(eff_date) over(partition by acct order by eff_date) as end_date
from table_src
but the query returns value as
acct eff_date end_date amt
1 03/04/2012 03/05/2012 100
1 03/05/2012 03/06/2012 200
1 03/06/2012 null 100
how to get default value when the value is null.
Kindly help.
Regards,
PunithaJust Use the NVL() to handle NULL Values as
Try this..
select
acct,
eff_date,
nvl(end_date,to_date('12/31/9999','MM/DD/YYYYY'))
amt
from
select
acct,
eff_date,
amt,
row_number() over(partition by acct order by eff_date) as rn,
lead(eff_date) over(partition by acct order by eff_date) as end_date
from table_src
Thanks,
Shankar
Edited by: Shankar Viji on Jun 7, 2012 12:42 AM -
I am facing a programming issue here;
I am supposed to create an array of circle objects of random dimensions.
Next, I am supposed to check each circle and make sure it does not intersect with any other circle in the array. If it does, I am expected to remove the circles that intersect with it from the array. I have found this technique more feasible, but in the question, it is suggested to check for intersection before the circle is added to the array. To quote "Check that the new circle does not intersect a previous one. You will need to iterate through the array list and verify that the current circle does not intersect with a circle in the array list. Add the circle to the array list if it does not intersect with another one." For some reason, I think my approach is more feasible. But feel free to differ.
Then, I am supposed to draw the circles.
The program compiles but when it is run, only one circle is drawn.
Any advice would be appreciated, and as before thank you in advance.
import java.util.Random;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import java.util.ArrayList;
import java.awt.Graphics2D;
import java.awt.Graphics;
public class CirclesComponent extends JComponent
public CirclesComponent(int numberCircles)
NCIRCLES = numberCircles;
circles = new ArrayList<Ellipse2D.Double>();
final int XRANGE = 292;
final int YRANGE = 392;
final int RRANGE = 20;
generator = new Random();
double x = generator.nextInt(XRANGE) + 1;
double y = generator.nextInt(YRANGE) + 1;
double r = generator.nextInt(RRANGE) + 1;
double w = 2 * r;
double h = 2 * r;
for (int i = 1; i <= NCIRCLES; i++)
Ellipse2D anEllipse = new Ellipse2D.Double(x, y, w, h);
circles.add(anEllipse);
Test if two circles intersect.
(distance between centers is less than sum of radii)
public void circlesIntersect()
Ellipse2D zeroEllipse = (Ellipse2D)circles.get(0);
for (int v = 1; v <= circles.size(); v++)
Ellipse2D anotherEllipse = (Ellipse2D)circles.get(v);
double radius1 = zeroEllipse.getWidth() / 2;
double radius2 = anotherEllipse.getWidth() / 2;
double dx = zeroEllipse.getX() + radius1 - anotherEllipse.getX() - radius2;
double dy = zeroEllipse.getY() + radius1 - anotherEllipse.getY() - radius2;
double distance = Math.sqrt(dx * dx + dy * dy);
if (distance < radius1 + radius2)
circles.remove(v);
public void paintComponent(Graphics g)
Graphics2D g2 = (Graphics2D) g;
for (int z = 0; z < circles.size(); z++) // iterate through every circle in the list
g2.draw((Ellipse2D)circles.get(z)); // draw the circle
public void getRejection()
System.out.println("The percentage of rejected circles is " + ((circles.size() / NCIRCLES ) * 100));
System.out.println("The size of the array is " + (circles.size()));
private int NCIRCLES;
private ArrayList circles;
private Random generator;
import java.util.Scanner;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CirclesTester
public static void main(String[] args)
Scanner thescanner = new Scanner(System.in);
System.out.print("How many circles do you want? ");
int totalCircles = thescanner.nextInt();
CirclesComponent theCircle = new CirclesComponent(totalCircles);
theCircle.getRejection();
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("Non-Intersecting Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(theCircle);
frame.setVisible(true);
}homebrewed wrote:
I am supposed to create an array of circle objects of random dimensions.
Next, I am supposed to check each circle and make sure it does not intersect with any other circle in the array. If it does, I am expected to remove the circles that intersect with it from the array. I have found this technique more feasible, but in the question, it is suggested to check for intersection before the circle is added to the array. To quote "Check that the new circle does not intersect a previous one. You will need to iterate through the array list and verify that the current circle does not intersect with a circle in the array list. Add the circle to the array list if it does not intersect with another one." For some reason, I think my approach is more feasible. But feel free to differ.Gladly. It is much simpler to iterate over a List and check if the new circle is valid than to iterate over a List and remove those circles that make the new circle invalid. Note that the code you have now will skip items in the list when a circle is removed.
Then, I am supposed to draw the circles.
The program compiles but when it is run, only one circle is drawn. And why is that? Is it only drawing one of the circles? Is it drawing all the circles but they're all the same circle? Does your list only contain one circle?
You need to run your program in a debugger or add println() statements to output your program state at important points along the execution path.
Once you figure out why you're only getting one circle, it becomes much simpler to figure out how it happened.
Maybe you are looking for
-
Hello community, I edited the artists through iTunes, but it did not edit the actual mp3 file on my computer. Is it possible to convert the artists I have edited through iTunes to be able to have the artists on the actual mp3 files instead of just in
-
Won't really see a video card in the PCI slots
I have a G4 MDD 1.23 GHz. I have a 32 MB video card in the AGP slot, but I also have 2 PCI 128 MB video cards lying around. Every time I try to throw a PCI video card in, though, I have problems. The image is only 640 x 480 grayscale, nothing else. I
-
I am an amatuer at best. I am receiving an error when trying to access any part of windows explorer now. I can't open folders at all. Included in picture format is the error. I'm running XP Home edition service pack 2 more than enough ram/HD I recent
-
To add new key figure in existing info cube (BI 7.0)
I m using BI 7.0 How can I add new Key figure in my existing info cube? Thanks KS
-
I am Using Premier Pro CC 2014 release v8.1sound synch issues
I am using PP CC, I have imported an AVCHD clips through media browser (this is not the 1st time using software or importing) on this isolated occasion when files imported the sound is miles out of synch. I have done the same with Final cut X and fin