2017-03-12 19 views
1

我正在對JOptionePane執行雙輸入來計算矩形的面積。所以我需要用戶把length然後width。但是,在第一次輸入之後,我立即將一個閱讀器放入,第二個JOptionPane的寬度不會彈出。我意識到這需要很多工作。JOptionPane在讀取器之後消失

import java.util.Scanner; 
import javax.swing.JOptionPane; 


public class Project3_1 { 

public static void main(String[] args) { 

     Scanner reader = new Scanner(System.in); 
     int length; 
     int width; 
     int surfacearea; 

     JOptionPane.showInputDialog("Enter the length of the edge: "); 
     length = reader.nextInt(); // doesnt work past this 
     JOptionPane.showInputDialog("Enter the width of the edge: "); 
     width = reader.nextInt(); 

     surfacearea = length * width; 

     JFrame someFrame = new JFrame(); // how to insert surfacearea?? 
     JLabel label = new JLabel(); 
     someFrame.add(label); 
     someFrame.setSize(230, 230); 
     someFrame.setVisible(true); 
    } 
} 
+0

你有什麼問題嗎?或者你想要什麼? –

+0

@Yohannes問題是爲什麼它不需要第二個輸入:) – minigeek

+0

請參閱下面的minigeek的答案。另外,「插入表面積」是什麼意思? –

回答

1

您正在混合輸入數據到程序的方式。讓我們開始吧:

Scanner reader = new Scanner(System.in);

線之上,您可以捕捉數據從鍵盤輸入命令行。

JOptionPane.showInputDialog("Enter the length of edge: "); 

此選項窗格顯示正確,您將一個值,然後沒有任何反應。這是因爲你的程序等待輸入的東西在命令行

length=reader.nextInt(); 

當程序到達上面的線,直到你把東西在命令行中reader.nextInt()停止程序。

正確的方法應該是這樣的:

length = Integer.parseInt(JOptionPane.showInputDialog("Enter the length of the edge: ")); 
width = Integer.parseInt(JOptionPane.showInputDialog("Enter the width of the edge:")); 

,並刪除:

length = reader.nextInt(); 
width = reader.nextInt(); 
+0

謝謝!我明白 – albanian

+0

不客氣:) – minigeek

1

你必須處理JOptionPane這樣的輸入:

String inputLength = JOptionPane.showInputDialog("Enter the length of the edge: "); 
int length = Integer.parseInt(inputLength); 

取出Scanner,因爲他正在等待在控制檯輸入。

+0

我認爲你誤解了變量'width'和'length',這些變量可能與'JFrame'的大小無關,而是作爲計算任務的一部分。 –

+0

確實我會刪除這部分 –