请原谅我这个问题是否真的很明显,但我已经尝试了一切。
我正在尝试制作一个计算数字百分比的计算器。
但是当我使用这段代码时,它会继续为输出输出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");
}
}
}
答案 0 :(得分: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;
答案 1 :(得分:1)
int
是自然数(或者是负数......等等, int
是整数),它不能是0或1之间的任何数字。你必须使用如果您想查看float
double
或0,25
答案 2 :(得分:1)
尝试使用float
代替int
float repercent = Float.parseFloat(rpercent);
float number = Float.parseFloat(rnumber);
float percent = repercent / 100;
答案 3 :(得分:0)
int percent = repercent / 100;
无效。 Use float
或double
数据类型。
答案 4 :(得分: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);
}
}