java程序设计基础_陈国君版第五版_第三章习题

11.编写程序,从键盘上输入一个浮点数,然后将该浮点数的整数部分输出。

import java.util.Scanner;
public class Main3_11 {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		float num = scanner.nextFloat();
		System.out.println((int)num);
	}
}

改进:

import java.util.Scanner;
public class Main3_11 {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		if(scanner.hasNextFloat()){
		float num = scanner.nextFloat();
		System.out.println((int)num);
		}else
		{
			System.out.println("输入的数据类型有误!");
		}
	}
}




第二种办法:

import java.io.*;
/**
 * 编写程序,从键盘上输入一个浮点数,然后将该浮点数的整数部分输出
 * @author Richard
 *
 */
public class Main3_11 {
	public static void main(String[] args)throws IOException{
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		String s = buf.readLine();
		float num =Float.parseFloat(s);
		System.out.println((int)num);
		
	}
}


3.12 编写程序,从键盘上输入两个整数,然后计算他们相除后得到的结果并输出。

import java.util.Scanner;
public class Main3_12 {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入两个整数:");
		int num1,num2;
		if(scanner.hasNextInt()){
			num1 = scanner.nextInt();
			num2 = scanner.nextInt();
			if(num2!=0)
			System.out.println(num1+" / "+num2+" = "+((float)num1/num2));
			else
			{
				System.out.println("输入错误!");
			}
		}else
		{
			System.out.println("输入错误!");
		}
	}
}

第二种:

import java.io.*;
public class Main3_12 {
	public static void main(String[] args)throws IOException{
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("请输入两个整数:");
		String s1,s2;
		int num1,num2;
		s1 = buf.readLine();
		s2 = buf.readLine();
		num1 = Integer.parseInt(s1);
		num2 = Integer.parseInt(s2);
		if(num2!=0)
			System.out.println(num1+" / "+num2+" = "+((float)num1/num2));
		else
		{
			System.out.println("输入错误!");
		}

	}
}


3.13编写程序,从键盘上输入圆柱体的底半径r和高h,然后计算其体积并输出。

import java.util.Scanner;
public class Main3_13 {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		float radius,height;
		System.out.println("请输入圆柱体的底半径:");
		if(scanner.hasNextFloat()){
		radius = scanner.nextFloat();
		System.out.println("请输入圆柱体的底半径:");
		height = scanner.nextFloat();
		System.out.println("体积运算结果:"+(Math.pow(radius,2))*height);
		}
	}

}


第二种:

import java.io.*;
public class Main3_13 {
	public static void main(String[] args)throws IOException{
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		float radius,height;
		String r,h;
		System.out.println("请输入圆柱体的底半径:");
		r = buf.readLine();
		System.out.println("请输入圆柱体的底半径:");
		h = buf.readLine();
		radius = Float.parseFloat(r);
		height = Float.parseFloat(h);
		System.out.println("体积运算结果:"+(Math.pow(radius,2))*height);
	}

}






你可能感兴趣的:(java_patest乙级真题,JAVA程序设计基础,程国君版第五版)