【发布时间】:2013-03-31 21:22:41
【问题描述】:
我只需要将因子输出为素数。
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number:");
int theNum = keyboard.nextInt();
int i;
System.out.println("\nThe prime factors of " + theNum + " are:");
for(i=1; i <= theNum/2; i++)
if(theNum % i == 0)
{
System.out.print(i + " ");
}
}
}
【问题讨论】:
-
永远不要使用
.nextInt(),因为它很可能会在以后给您带来问题。始终使用.nextLine()并将其解析为int。 -
我是编程新手,您可以将那行作为代码输入,以便我知道您的意思吗?
-
@syb0rg 您可能想要包含一个原因 - (类似的)...问题,例如如果您在同一个
Scanner上使用nextInt和nextLine,nextInt不会' t 包括下一个行尾字符,因此您将在下一个nextLine调用中得到一个空行。 -
@Dukeling 我根本看不出使用
nextInt()的理由,而我可以使用nextLine并从中解析我需要的所有信息。 -
@user2230190
String nextIntString = keyboard.nextLine();(获取单行数字)int nextInt = Integer.parseInt(nextIntString);(将字符串转换为整数)
标签: java