0

如果这个问题真的很明显,请原谅我,但我已经尝试了一切。

我正在尝试制作一个计算数字百分比的计算器。

但是当我使用此代码时,它会一直为输出输出 0:

import java.io.*;

class pCalc {
     public static void main(String args[])
     {
          InputStreamReader istream = new InputStreamReader(System.in) ;
          BufferedReader bufRead = new BufferedReader(istream) ;

          System.out.println("Hello...");

          try {
               System.out.println("Please Enter In The Percentage You Want To Find (e.g 25): ");
               String rpercent = bufRead.readLine();

               System.out.println("Please Enter In The Number You Wish To Find The Percentage Of (e.g 200): ");
               String rnumber = bufRead.readLine();


               int repercent = Integer.parseInt(rpercent);
               int number = Integer.parseInt(rnumber);
               int percent = repercent / 100;

               int awnswer = number * percent ;

               System.out.println("Percent is: " + percent);
               System.out.println("Awnswer is: " + awnswer);
          }
          catch (IOException err) {
               System.out.println("Error reading line");
          }
          catch(NumberFormatException err) {
               System.out.println("Error Converting Number");
          }         
     }
}
4

5 回答 5

2

你的问题出在这里:

       int repercent = Integer.parseInt(rpercent);
       int number = Integer.parseInt(rnumber);
       int percent = repercent / 100;

整数除法的结果最终将是一个整数,因此,例如,如果计算产生0.2,它将更改为0.

这样做应该可以解决它:

   double repercent = Double.parseDouble(rpercent);
   double number = Double.parseDouble(rnumber);
   double percent = repercent / 100.0;
于 2012-04-30T09:56:51.457 回答
1

int是自然数(或者它是负数......等等,int是 Integer),它不能是 0 或 1 之间的任何东西。你必须使用float或者double如果你想看到类似的东西0,25

于 2012-04-30T09:58:05.460 回答
1

尝试使用float而不是int

float repercent = Float.parseFloat(rpercent);
float number = Float.parseFloat(rnumber);
float percent = repercent / 100;
于 2012-04-30T09:59:05.590 回答
0

int percent = repercent / 100;不会工作。使用floatordouble数据类型。

于 2012-04-30T09:57:39.930 回答
0

我已经清理了你的代码。正如其他人所指出的,主要问题是过早的整数除以 100。删除了异常处理,因为它是多余的,并掩盖了默认异常处理程序将打印的完整堆栈跟踪。

package test;

import static java.lang.Integer.parseInt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
  public static void main(String args[]) throws Exception {
    final BufferedReader bufRead = new BufferedReader(new InputStreamReader(System.in)) ;
    System.out.println("Hello...");
    System.out.println("Please Enter In The Percentage You Want To Find (e.g 25): ");
    final int percent = parseInt(bufRead.readLine());
    System.out.println(
        "Please Enter In The Number You Wish To Find The Percentage Of (e.g 200): ");
    final int number = parseInt(bufRead.readLine());
    final int answer = number * percent / 100; // or use a floating-point type here
    System.out.println("Percent is: " + percent);
    System.out.println("Answer is: " + answer);
  }
}
于 2012-04-30T10:03:05.290 回答