Why isnt this loop working?
I am trying to fill an array with the Fibonacci sequence.
Oh and, I know its very silly to use 'long i' instead of 'int i' as my incrementor in the for loop. But... I have a reason.
import java.math.*;
public class euler20{
public static void main (String arghp[]){
BigInteger a[]=new BigInteger [1000000];
a[1]=new BigInteger("1");
a[2]=new BigInteger("2");
for(long i=3;i<10;i++)
System.out.println(a[(int)i]);
a[(int)i]=new BigInteger(""+a[(int)i-1].add(a[(int)i-2]));
Tell me I am doing something REALLY stupid..
uhm well, I imporvised my code a little..
replace a[(int)i]=new BigInteger(""+a[(int)i-1].add(a[(int)i-2]));with
a[(int)i]=a[(int)i-1].add(a[(int)i-2]);However, the problem persists.
Similar Messages
-
HT4113 why isnt this thing working
why isnt this working
Because of the actions of an unsympathetic deity.
Try to ask a sensible question with a clue or two, and us folk might be able to help you. With your present standard of asking, you have no hope. -
Why isnt this working urgent please help
why isnt this working im trying to connect a panel to a scrollpane the panel will contain several dozen text fields
the scrollpane shouls be about 350, 450 , but the pane is 350
by 1200 the problem now is that the scorllbar isnt created and even when I explictly create it it contains no knob, and it will
not scroll up or down please someone help this is urgent
import java.awt.*;
import com.sun.java.swing.*;
public class ScrollDemo extends JPanel {
private Rule columnView;
private Rule rowView;
private ScrollablePicture picture;
class UnitsListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// Turn it to metric.
rowView.setIsMetric(true);
columnView.setIsMetric(true);
} else {
// Turn it to inches.
rowView.setIsMetric(false);
columnView.setIsMetric(false);
picture.setMaxUnitIncrement(rowView.getIncrement());
public ScrollDemo() {
Two t = new Two(columnView.getIncrement());
JScrollPane pictureScrollPane = new JScrollPane(t);
pictureScrollPane.setPreferredSize(new Dimension(300, 250));
pictureScrollPane.setColumnHeaderView(columnView);
pictureScrollPane.setRowHeaderView(rowView);
public static void main(String s[]) {
JFrame frame = new JFrame("ScrollDemo");
frame.setContentPane(new ScrollDemo());
frame.setVisible(true);
import java.awt.*;
import com.sun.java.swing.*;
public class Two extends JPanel implements Scrollable{
private JPanel ivjJPanel3 = null;
private JScrollPane ivjJScrollPane1 = null;
private int maxUnitIncrement = 1;
public Two(int m)
getJPanel1();
maxUnitIncrement = m;
setSize(300,1200);
private void getJPanel1() {
setLayout(null);
setSize(250,1200);
add(getJLabel1(), getJLabel1().getName());
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation,
int direction) {
if (orientation == SwingConstants.HORIZONTAL)
return visibleRect.width - maxUnitIncrement;
else
return visibleRect.height - maxUnitIncrement;
public boolean getScrollableTracksViewportHeight() {
return false;
public boolean getScrollableTracksViewportWidth() {
return false;
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction) {
//Get the current position.
int currentPosition = 0;
if (orientation == SwingConstants.HORIZONTAL)
currentPosition = visibleRect.x;
else
currentPosition = visibleRect.y;
//Return the number of pixels between currentPosition
//and the nearest tick mark in the indicated direction.
if (direction < 0) {
int newPosition = currentPosition -
(currentPosition / maxUnitIncrement) *
maxUnitIncrement;
return (newPosition == 0) ? maxUnitIncrement : newPosition;
} else {
return ((currentPosition / maxUnitIncrement) + 1) *
maxUnitIncrement - currentPosition;
public void setMaxUnitIncrement(int pixels) {
maxUnitIncrement = pixels;I personally didn't play with swing components when they were in the com.sun.java.swing state, but I have a strong feeling it is very buggy and could be causing your problem.
Before posting gui issues, please use a newer API, even jdk1.1 would be fine, anything would be better than what your using.
you wrote: I dont care if its javax.swing or
com.sun.java.swing
I would also gather from this statement that your attitude could be one of your other issues. -
Why isnt my sound working on my ipod
why isnt my sound working on my ipod only when i have headphones in
If you confirmed the headphones are not the problem.
- Try cleaning out/blowing out the headphone jack. Try inserting/removing the plug a dozen times or so.
Try the following to rule out a software problem
- Reset the iPod. Nothing will be lost
Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
least ten seconds, until the Apple logo appears.
- Reset all settings
Go to Settings > General > Reset and tap Reset All Settings.
All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
- Restore from backup
- Restore to factory settings/new iPod.
- Make an appointment at the Genius Bar of an Apple store. Seems you have a bad headphone jack.
Apple Retail Store - Genius Bar
If not under warranty Apple will exchange your iPod for a refurbished one for this price. They do not fix yours.
Apple - iPod Repair price
A third-party place like the following will replace the jack for less. Google for more.
iPhone Repair, Service & Parts: iPod Touch, iPad, MacBook Pro Screens
Replace the jack yourself
iPod Touch Repair – iFixit -
Why isnt my ringtone working with facetime?
why isnt my ringtone working with facttime?
If you confirmed the headphones are not the problem.
- Try cleaning out/blowing out the headphone jack. Try inserting/removing the plug a dozen times or so.
Try the following to rule out a software problem
- Reset the iPod. Nothing will be lost
Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
least ten seconds, until the Apple logo appears.
- Reset all settings
Go to Settings > General > Reset and tap Reset All Settings.
All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
- Restore from backup
- Restore to factory settings/new iPod.
- Make an appointment at the Genius Bar of an Apple store. Seems you have a bad headphone jack.
Apple Retail Store - Genius Bar
If not under warranty Apple will exchange your iPod for a refurbished one for this price. They do not fix yours.
Apple - iPod Repair price
A third-party place like the following will replace the jack for less. Google for more.
iPhone Repair, Service & Parts: iPod Touch, iPad, MacBook Pro Screens
Replace the jack yourself
iPod Touch Repair – iFixit -
I have many projects made in imovie HD that are not updating to iMovie 10 on my new iMac. Why is this not working as stated on the article HT202853? How do I get my projects back from backup after old iMac crashed?
According to:
Update projects and events from previous versions of iMovie in iMovie (2014) - Apple Support
you can update from iMovie versions 7, 8 and 9, but iMovie HD is iMovie 6.
Maybe you can update in two steps, first from iMovie 6 to iMovie 7, 8 or 9 then to iMovie 10.
Geoff. -
Hypertext links are not always preserved from Word to PDF, using Aperçu or Adobe, depending on OS 10 or Lion. Why? This generally works perfectly in Windows. Why are Apple and Adobe unable to correctly handle links when converting from Word to PDF?
Depending on the system version, and Office Word version:
- a pure URL link starting with http or even www sometimes works in PDF, either produced by Aperçu or Adobe, sometimes does not work;
- other kind of links where the text under display is not a URL, never work!
I like everything with Apple computers and software, except PDF generation. Output files are usually bigger in size, and no better quality, than under Windows. Furthermore, it is weird that something as common as hyperlinks does not work correctly!
I related this question with Mac OS X Snow Leopard, but the problem is still there with Mac OS Lion.
This problem seems to have been around for years, without any proper solution from Apple and/or Adobe! To me, this is very embarrassing!Greetings NoNameGiven,
If I understand the problem correctly (I’m not sure I do) you would prefer ‘iii’ to be read as “eye eye eye” rather than “three”? The alt text property is the only way that I know of to make this happen. Hope this helps.
a ‘C’ student -
Why is this form so compliacated to nagiveate?
what a piece of trash apple!
I paid 600 dollar for a phone that doesnt work
The Voice Text isnt working at alll
I speak it does the 3 dots then nothing
Nothing is working here. Fix this PLEASEthis is a user forum, apple does not offer fixes through this medium. Other users can help you out if you will give us more details.
What country are you in?
Who is your carrier?
Are you indeed using the iphone 4s?
have you attempted using the speech to text feature with wifi, or only using cellular data?
How long has this problem been present? Was it working any time before?
thanks -
Why is this loop incorrect please
Hello,
Im trying to get a 5x5 grid of images to display on fullscreen mode.
The only code that renders these 5 images is below. Please note, ive been testing this section out to try to fix the problem, using r + c for coords, and x and y to show the 5x5. To me, this loop goes through each y, 0 - 4 , and should display a 5 x 5 grid of images. Instead, only one row of 5, (the last one_ is shown. I really dont understand so if you can help, please do :)
// draw the visible tiles
int r = 1;
int c =1;
for (int y=0; y<5; y++) {
for (int x=0; x <5; x++) {
r = r+10;
c=c+10;
Tile tile = map.getTile(x, y);
if (tile != null) {
g.drawImage(tile.base,r,c,
null);
}Thankyou,
L28Hello,
thankyou for your reply. I used your code and unfortunately the output displays as 5 images, going down (eg 0,0 1,0 2,0 3,0 4,0). Swapping the x and y results in it showing 5 images left to right. Ive had a look and think the problem could be how the loop is called.
here is how the code to render the 5x5 grid is used.
GameLoop
// draw the screen
Graphics2D g = screen.getGraphics();
draw(g);
g.dispose();
screen.update();
// take a nap
try {
Thread.sleep(20);...callable code
public void draw(Graphics2D g) {
renderer.draw(g, map,
screen.getWidth(), screen.getHeight());
}Using System.out.println, instead of being 25 outputs (ie the 5x5 grid), there are hundreds ( i think) of outputs (probably limited by how many lines System.out.println can display.
Thankyou
L28
edit
Hard coding the grid (replacing the loop code) produces expected output
Tile tile1 = new Tile("GrassTile1");
Tile tile2 = new Tile("GrassTile1");
Tile tile3 = new Tile("GrassTile1");
Tile tile4 = new Tile("GrassTile1");
g.drawImage(tile1.base,0,0,
null);
g.drawImage(tile2.base,0,64,
null);
g.drawImage(tile3.base,0,128,
null);
g.drawImage(tile4.base,0,192,
null);Edited by: Lance28 on Mar 29, 2008 11:54 AM -
After a big loss of out-pulled hair here is the code:
setInterval() calls getNewMess function but it happens
nothing with onNewMess function.
Instead, if i click refresh-button, it gives me result
correctly.evt.target._parent
is just using the event argument that is dispatched to and
therefore received by your listener function. It is dispatched/sent
by your button component instance. The event object from components
- in as2 - normally contains at least two properties. A type
property... in this case that's "click" , because its a click event
and a target property. The target property is a reference to the
component instance from which the event originated. It can be
particularly useful if you have one listener handling events from
many sources. So.....
evt.target._parent is referring to the container clip of the
instance that sent the event. i.e. The _parent of the button in
this case.
That's why I replaced it with t (=this) which is a reference
to the timeline that the button is running in. Now it doesn't need
to get that reference from checking the _parent of the evt.target
property from the evt argument. Which means the argument that the
newMess function receives can be ignored and its no longer reliant
on it. Sounds confusing but once you "get" it, it all makes sense.
Eventually, lol.
And of couse you don't need to have a button if you don't
want one. -
HT204380 Why isnt this working
I have an Ipad2, every single time i facetime with someone using a iphone 4s, i can hear what they are saying but they can't hear what i am saying.how do i fix this?...i enjoy having to write down what i think on paper, but i would rather talk =)
Using FaceTime http://support.apple.com/kb/ht4319
Troubleshooting FaceTime http://support.apple.com/kb/TS3367
The Complete Guide to FaceTime: Set-up, Use, and Troubleshooting Problems
http://tinyurl.com/32drz3d
I saw one post where a user said dust got inside the small microphone hole. Using a vacuum cleaner removed the dust and restored the audio.
Cheers, Tom -
Why isnt this working? add container to frame..
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MortgageCalcFrame {
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Mortgage calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add's a container in the frame
Container content = new Container();
frame.getContentPane().add(content, BorderLayout.SOUTH);
JButton btn = new JButton("test");
content.add(btn, BorderLayout.EAST);
JTextField input = new JTextField(5);
frame.getContentPane().add(input, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}Well the problem you got is that the layout of a Container is null. You've got several options here.
1. You set a layout for your container like this
Container content = new Container();
content.setLayout(new FlowLayout());2. You use a different container that inherits from container like Panel or JPanel since this one already got a FlowLayout set.
Panel content = new Panel();or
JPanel content = new JPanel(); //better since you're currently mixing Swing components and AWT. -
Why isnt this working?? - I really need this!!!
Hi, can you please have a go at this problem? Thnx!!
Here is the code:
import java.io.*;
public class Main {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private String newname=null;
public void setName ()throws Exception{
System.out.print("Hello, please enter your attribute");
newname = in.readLine();}
public String getName(){
return newname;}
public Main()throws Exception{
Main m = new Main();
m.setName();
import java.io.*;
public class Main2 {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private String newname=null;
public void setName ()throws Exception{
System.out.print("Please enter your sign");
newname = in.readLine();}
public String getName()throws Exception{
Main z = new Main();
z.setName();
if(newname.equals("=")){
return ("==" + z.getName());}
else{
return "Error";}}
public Main2()throws Exception{
Main2 p = new Main2();
p.setName();}}
import java.io.*;
public class Main3 {
public static void main(String[] args)throws Exception {
Main2 p = new Main2();
System.out.print("Hello "+p.getName());}}For one, Main2 has a recursive constructor:
public Main2() throws Exception
//Main2 p=new Main2();
//p.setName();
setName(); // You don't need another instance
}Also, there is no reason to create a new class to get every entry from standard in. You could just do:
System.out.println("Enter A: ");
a=in.readLine();
System.out.println("Enter B: ");
b=in.readLine(); -
Problem: Why does this only work for powers of 2?
I wrote this program to create a golf league schedule for, ideally, eight players. However I want it to be flexible enough to permit for other denominations, such as 10 or 12. When I run the program it works perfectly for any number that is a power of 2 (2,4,8,16,32,etc...) but it will not work for other even numbers such as 6,10, or 12. If anyone has any insights it would be most helpful.
*(This is my first post on this forum so if anything looks not quite right or if this post isn't worded exactly how it should be then I apologize in advance)*
Here's the three classes.
public class ScheduleDriver
public static void main(String[] args)
//instance variables
int max; //size of flight matches array
ScheduleMaster master;//instance of class
//get max number of players for flight
System.out.print("Max number of players in this flight:");
max = Keyboard.readInt();
master = new ScheduleMaster(max);
//create weekly schedules for season
master.createSchedule();
//display weekly schedules
master.displayWeekly();
}//end main
}//end ScheduleDriver
public class ScheduleMaster
//instance variables
int maxPlyrs;//maximum number of players in flight
Week[] weeklySchedule;//array of weekly matches
public ScheduleMaster(int plyrs)
//set up instance data and declare array size
maxPlyrs = plyrs;
weeklySchedule = new Week[plyrs];
//set up the size of each week's matches array
for (int pos = 0; pos < plyrs; pos++)
weeklySchedule[pos] = new Week(plyrs);
}//end for
}//end constructor
public void createSchedule()
int count = 0;//index of weeklySchedule array
final int QUIT = -1; //quit value for loop
int flag = 0; //value to continue or exit loop
//for each player A
for (int a = 1; a < maxPlyrs; a++)
//for each opponent of player A
for (int b = (a + 1); b <=maxPlyrs;b++)
//set count/index and reset flag to zero
count = (a - 1);
flag = 0;
//while still haven't found correct week for this match
while (flag != QUIT)
//if at least one of these players are already scheduled
//for a match this week
if (weeklySchedule[count].checkPlayers(a,b) == true)
//if last valid index of array has been reached
if (count == (maxPlyrs - 2))
//reset count/index to zero
count = 0;
else
//incriment count
count++;
}//end if
else
//assign this match to array of matches for week
//and then exit loop
weeklySchedule[count].setMatch(a,b);
flag = -1;
}//end else
}//end while
}//end for
}//end for
//fill in last week/position night
for (int pos = 0; pos < maxPlyrs;pos++)
//set up position match
weeklySchedule[maxPlyrs - 1].setMatch(pos + 1, pos + 2);
//incriment pos
pos++;
}//end for
}//end createSchedule
public void displayWeekly()
//for each week in schedule
for (int pos = 0; pos < maxPlyrs;pos++)
//display header
System.out.print("WEEK " + (pos + 1));
//if pos/index is 0 or even, flight plays front 9
if ((pos % 2) == 0)
System.out.println(" [FRONT 9]");
//else flight plays back 9
else
System.out.println(" [BACK 9]");
//display lines
System.out.println("----------------");
//display week's matches
weeklySchedule[pos].display();
//skip a line
System.out.println("\n");
}//end for
}//end displayWeekly
}//end ScheduleMaster
public class Week
int[] schedule; //array of players involved in matches for week
int max; //max number of players
int count = 0; //number of players currently involved in matches
public Week(int size)
//set up instance data and size of array
max = size;
schedule = new int[size];
}//end constructor
public boolean checkPlayers(int playerA, int playerB)
boolean flag = false; //flag to determine if at least one of
//the players to check are already playing
//this week
//for each element of array
for (int pos = 0; pos < max; pos++)
//if player A matches player already playing this week
if (schedule[pos] == playerA)
flag = true;
}//end for
//for each element of array
for (int pos = 0; pos < max; pos++)
//if player B matches player already playing this week
if (schedule[pos] == playerB)
flag = true;
}//end for
return flag;
}//end checkPlayers
public void setMatch(int playerA, int playerB)
//if array can take more matches
if (count <= (max - 2))
//insert players into array of active players for week
schedule[count] = playerA;
schedule[count + 1] = playerB;
//incriment count of players playing this week by 2
count = count + 2;
}//end if
else
System.out.print("No more matches can be entered!!!");
}//end setMatch
public void display()
//for every even numbered index starting at zero
for (int num = 0;num < max;num++)
//display the player at that position and the next consecutive
//player who will be his opponent for the week
System.out.println(schedule[num] + "VS" + schedule[num + 1] +
//incriment num
num++;
}//end for
}//end display
}//end WeekAh, I have discovered the problem. The reason for the infinite loop was because of the resetting of the counter/index after every successful match entry back to (a - 1). This was causing matches to be put into weeks where they didn't belong, which caused the program to infinitely loop because it couldn't find an appropriate week to place it's next match. The only time the count should be reset back to zero is when a new player A is being processed or the last valid array index has been referenced before an out of bounds exception would be thrown. I'm still not entirely sure why this doesn't occur on powers of 2 but theh again I haven't put too much thought into it having solved the initial problem! :)
Anyways thanks for the input all who posted, much appreciated.
Happy programming!!!! -
Why is this loop infinite?
I only want it to iterate once and prompt the user again, until they hit enter.
public class assignment5
public static void main(String[] args)
System.out.println("Please type in a sentence.\nTo quit at any time hit enter.");
String sentence = SavitchIn.readLine();
String sentenceTrim = sentence.trim();
int quit = sentence.length();
int questionIndex = sentenceTrim.indexOf("?");
int exclamationIndex = sentenceTrim.indexOf("!");
int length = sentenceTrim.length();
int evenOdd = length % 2;
do
if ((evenOdd == 0) && (questionIndex != -1))
System.out.println("Yes ");
else if ((evenOdd != 0) && (questionIndex != -1))
System.out.println("No ");
else if (exclamationIndex != -1)
System.out.println("Wow ");
else System.out.println("You always say \"" + sentenceTrim + "\" ");
while (length > 0);
[/colde]Doesn't this question have a little homework
feeling??? No, not at all. His question is not "How do I make a program that returns when the user hits enter?" His question is "Why doesn't this work?"
He has already tried and is clearly not getting what he predicted. What do you expect him to do? If he didn't feel this was the time to ask a question, then he has no hope.
I think it is a very good question, although it probably belonged in the beginner forum.
To answer the original poster, just follow your code one line at a time and when it starts to do things that you don't want it to, it's time to rethink the placement of your lines and loop points (start and stop). And think about what the other posters have written.
Maybe you are looking for
-
How can I mix calendars from Exchange and the one on iCloud
I have different calendars on my iPad as a result of having my Outlook Exchange email from the company I woked for synchronized in it. Now, I don't work there anymore but when I turned on iCloud, the only calendar on iCloud is another one but the one
-
Using iMac 27in as a display for my pc
I would like to connect my hdmi PC to my iMac and display the PC screen on my iMac. I know thunderbolt doesn't generally allow this, even though you can buy physical cables to allow hdmi to thunderbolt. Is there any third party software that will a
-
Tried several times to download Firefox 6 as upgrade to Firefox 4 and near end of download I get error message that I need Windows 2000 or newer. I have windows XP 2002. Cannot find error in my system.
-
Exception in thread "main" java.lang.UnsatisfiedLinkError: - fresh Install
Pls can someone help me out. I have a similar problem to the one raised in this thread. I want to install 10g Release 2 on a RHEL AS4 Production IBM server. I've followed the installation guide to the letter! I keep getting this error: [oracle@pencom
-
Where can I upgrade to use DV capture?
Where can I upgrade to use DV capture?