-2
對於這個問題,我聽起來確實很愚蠢,但我對我的for循環有困難。爲什麼我的代碼運行for循環超過5次?
這是我遇到的麻煩的部分代碼。
Scanner input = new Scanner(System.in);
int number;
for(int i = 0;i < 5;i++) {
System.out.print("Enter 5 integers:");
number = input.nextInt();
}
當我運行它打印輸出循環超過5次。
public class BarGraph extends JPanel
{
public void paintComponent(Graphics g)
{
Scanner input = new Scanner(System.in);
// super.paintComponent(g);
int number;
for(int i = 0;i < 5;i++)
{
System.out.print("Enter 5 integers:");
number = input.nextInt();
// g.drawRect(10 * i, 10 * i, 100 * number, 10);
}
}
}
運行BarGraphTest
public class BarGraphTest
{
public static void main(String[] args)
{
BarGraph panel = new BarGraph();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(300, 300);
application.setVisible(true);
}
}
基本上我想要做的是閱讀5點的整數,只是顯示他們的JPanel線條形圖。
罪魁禍首是'input.nextInt();'。使用'input.nextLine();'代替。 – Tiny
比5還要多少倍? –
打印出來的值'i' – Rogue