让用户输入小数的代码是什么 [英] What is the code to let the user input decimals
本文介绍了让用户输入小数的代码是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
package com.test;
import java.util.Arrays;
import java.util.Scanner;
public class SortArray
{
public static void main(String [ ] args)
{
int numArray[] = new int[5];
Scanner input = new Scanner(System.in);
for(int i=0; i<numarray.length;i++)>
{
System.out.println("Enter five decimal numbers: ");
numArray[i]= input.nextInt();
}
System.out.println("Array before sorting: " +Arrays.toString(numArray));
Arrays.sort(numArray);
System.out.println("Array after sorting: " +Arrays.toString(numArray));
}
}
我的尝试:
What I have tried:
package com.test;
import java.util.Arrays;
import java.util.Scanner;
public class SortArray
{
public static void main(String [ ] args)
{
int numArray[] = new int[5];
Scanner input = new Scanner(System.in);
for(int i=0; i<numarray.length;i++)>
{
System.out.println("Enter five decimal numbers: ");
numArray[i]= input.nextInt();
}
System.out.println("Array before sorting: " +Arrays.toString(numArray));
Arrays.sort(numArray);
System.out.println("Array after sorting: " +Arrays.toString(numArray));
}
}
推荐答案
如果你的意思是'十进制'数字,就像有'小数点'一样java中的类型可以是double或float - 所以,我会查看代码中的粗体位,如下所示并更改那些(有3个) - 您可能还需要考虑使用固定格式化输出数字#小数点
if you mean a 'decimal' number as in having a 'decimal point' the type in java could be double or float - so, I would look at the bold bits in your code as shown below and alter those (there are 3) - you may also then need to think about formatting the output number with a fixed # of decimal points
package com.test;
import java.util.Arrays;
import java.util.Scanner;
public class SortArray
{
public static void main(String [ ] args)
{
int numArray[] = new int[5];
Scanner input = new Scanner(System.in);
for(int i=0; i<numarray.length;i++)>
{
System.out.println("Enter five decimal numbers: ");
numArray[i]= input.nextInt();
}
System.out.println("Array before sorting: " +Arrays.toString(numArray));
Arrays.sort(numArray);
System.out.println("Array after sorting: " +Arrays.toString(numArray));
}
}
你也可以用字符串读取数字,但是你会有做类似的事情
you could also read the numbers in as a string, but then you'd have to do something like
String doubleAsString = "50.01";
Double myDouble = 0;
try
{
myDouble = Double.parseDouble(doubleAsString);
}
catch(NumberFormatException e)
{
//not a double
}
要解析的
要加倍的字符串
to parse the string to double
这篇关于让用户输入小数的代码是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文