P25 4-1 for循环-1
表达累积的结果应该初始化为1.
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int i=1;
int factor=1;
while(i<=n)
{
factor=factor*i;
i=i+1;
}
System.out.println(factor);
}
}
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int i=1;
int factor=1;
for(i=1;i<=n;i++)
{
factor=factor*i;
}
System.out.println(factor);
}
}
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int factor=1;
int n=in.nextInt();
for(int i=1;i<=n;i++)
{
factor=factor*i;
}
System.out.println(factor);
}
}
for while do while
P26 4-1 for循环-2
P27 4-2 循环控制-1
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int isPrime=1;
for(int i=2;i<n;i++)
{
if(n%i==0)
{
isPrime=0;
break;
}
}
if(isPrime==1)
{
System.out.println(n+"是素数");
}
else
{
System.out.println(n+"不是素数");
}
}
}
P28 4-2 循环控制-2
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
for(int n=2;n<100;n++)
{
int isPrime=1;
for(int i=2;i<n;i++)
{
if(n%i==0)
{
isPrime=0;
break;
}
}
if(isPrime==1)
{
System.out.print(n+" ");
}
else
{
// System.out.println(n+"不是素数");
}
}
}
}
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int amount= in.nextInt();
for(int one=0;one<=amount;++one)
{
for(int five=0;five<=amount/5;++five)
{
for(int ten=0;ten<=amount/10;++ten)
{
for(int twenty=0;twenty<=amount/20;++twenty)
{
if(one+five*5+ten*10+twenty*20==amount)
{
System.out.println(one+"张1元,"+five+"张5元,"+ten+"张10元,"+twenty+"张20元")
}
}
}
}
}
}
}
break只能跳出当前层循环。
P29 4-2 循环控制-3
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n=in.nextInt();
boolean isPrime=true;
for(int i=2;i<n;i++)
{
if(n%i==0)
{
isPrime=false;
break;
}
}
if(isPrime)
{
System.out.println(n+"是素数");
}
else
{
System.out.println(n+"不是素数");
}
}
}
P30 4-3 循环控制-1
System.out.printf("%.2f",sum);//四舍五入保留两位小数