2013-02-11 66 views
-3

如何將我的output += Math.pow(baseUno, powernumber)+ " ";的數字整數到最接近的整數?在Java中將雙精度舍入到最接近的整數?

他們總是給我一個output,例如,1.0或2.0。你如何圍繞這些,以便他們只會導致1和2

import javax.swing.*; 
import java.text.*; 
import java.util.*; 

public class level7Module1 
{ 

public static void main(String[] args) 
{ 

String base, power, output = " "; //user inputs, and the output variable 
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations 

DecimalFormat noDigits = new DecimalFormat("0"); 

// oneDigit.format(variablename) 


base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: \nPress 'q' to quit."); //User input 
    if (base.equals("q")) 
    { 
    JOptionPane.showMessageDialog(null,"Goodbye!"); 
    System.exit(0); //quits 
    } 

baseUno = Integer.parseInt(base); 
// basenum = noDigits.format(baseUno); 

if (baseUno <= 0) 
{ 
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me?):"); 
System.exit(0); 
} 
if (baseUno > 14) 
{ 
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk."); 
System.exit(0); 
} 

//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things 
//that would fit on my monitor :) 

power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.\nPress 'q' to quit."); 

if (power.equals("q")) 
    { 
    JOptionPane.showMessageDialog(null,"Goodbye!"); 
    System.exit(0); 
    } 

powerUno = Integer.parseInt(power); 
// powernum = noDigits.format(powerUno); 

if (powerUno <= 0) 
    { 
    JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me?):"); 
    System.exit(0); 
    } 
if (powerUno > 14) 
    { 
    JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk."); 
    System.exit(0); 
    } 

for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going. 
{ 
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above. 
} 

JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs 

} 
} 
+2

你不能只投了returnrd雙爲int? – PermGenError 2013-02-11 16:17:25

+0

[Math.round()](http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round%28double%29)?最終將結果(這是一個「長」)轉換爲「int」? – ThanksForAllTheFish 2013-02-11 16:22:52

+0

爲了讓其他用戶更容易理解您的問題,我建議減少相關部分的代碼量。 – junix 2013-02-11 16:36:09

回答

0

最簡單的辦法改變這一行:
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);

JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
只需鍵入種姓的結果int

相關問題