4장 수학 함수, 문자 및 문자열
목차
4장 수학 함수, 문자 및 문자열
4.2 기하학: 최대 원 거리
최대 원 거리는 구 코드의 두 점 사이의 거리입니다
.
public class Exercise04_02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter point 1 (latitude and longitude) in degrees: ");
double x1= in.nextDouble();
double y1= in.nextDouble();
System.out.print("Enter point 2 (latitude and longitude) in degrees: ");
double x2= in.nextDouble();
double y2= in.nextDouble();
in.close();
double r=6371.01;
x1=Math .toRadians(x1);
x2=Math .toRadians(x2);
y1=Math .toRadians(y1);
y2=Math .toRadians(y2);
double d=r *(Math.acos(Math.sin(x1) * Math.sin(x2) + Math.cos(x1) * Math.cos(x2) * Math.cos(y1- y2)));
System.out.printf("The distance between the two points is "+d+"km");
}}
4.5 기하학: 정다각형의 면적
일반 다각형의 영역 찾기:
코드:
import java.util.*;
public class Exercise04_05 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter the number of sides:");
int n=in.nextInt();
System.out.print("Enter the side: ");
double s=in.nextDouble();
in.close();
double area=(n*s*s)/(4.0*Math.tan(Math.PI/n));
System.out.printf("The area of the polygon is "+area);
}
}
4.6 원 위의 임의의 점
중심이 (0,0)이고 반지름이 40인 원에 3개의 임의의 점을 생성하고 이 3개의 임의의 점이 형성하는 삼각형의 세 각도의 각도를 표시합니다.
암호:
package firstprogram;
import java.util.Scanner;
public class Exercise04_06 {
public static void main(String[] args) {
float rad1;
float rad2;
float rad3;
while(true) {
//随机产生三个弧度
rad1=2*(float)(Math.PI*Math.random());
rad2=2*(float)(Math.PI*Math.random());
rad3=2*(float)(Math.PI*Math.random());
//防止弧度相等
if(rad1==rad2||rad2==rad3||rad1==rad3) {
continue;
}
else
break;
}
float x1=40*(float)Math.cos(rad1);
float x2=40*(float)Math.cos(rad2);
float x3=40*(float)Math.cos(rad3);
float y1=40*(float)Math.sin(rad1);
float y2=40*(float)Math.sin(rad2);
float y3=40*(float)Math.sin(rad3);
System.out.println("Three points are :");
System.out.printf("A(%.2f,%.2f) B(%.2f,%.2f) C(%.2f,%.2f)",x1,y1,x2,y2,x3,y3);//精度2
//边长
float s1=(float)Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2, 2));
float s2=(float)Math.sqrt(Math.pow(x2-x3,2)+Math.pow(y2-y3, 2));
float s3=(float)Math.sqrt(Math.pow(x1-x3,2)+Math.pow(y1-y3, 2));
//角度
float A=(float)Math.toDegrees(Math.acos((s2*s2+s3*s3-s1*s1)/(2*s2*s3)));
float B=(float)Math.toDegrees(Math.acos((s1*s1+s3*s3-s2*s2)/(2*s1*s3)));
float C=(float)Math.toDegrees(Math.acos((s2*s2+s1*s1-s3*s3)/(2*s2*s1)));
System.out.println("Three angles are: ");
System.out.printf("A:%.2f B:%.2f C:%.2f",A,B,C);
}
}
4.7 정점 좌표
정오각형의 외접원인 중심(0, 0)의 반지름을 입력하고 다섯 꼭짓점의 좌표를 표시합니다.
암호:
import java.util.Scanner;
public class Exercise04_07 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter the radius of the bounding circle: ");
double r=in.nextDouble();
System.out.println("The coordinates of five points on the pentagon are");
double angle=Math.PI/2-2*Math.PI/5;
double x=0;
double y=0;
for(int i=0;i<5;i++) {
x=r*Math.cos(angle);
y=r*Math.sin(angle);
System.out.printf("(%.4f,%.4f)\n",x,y);
angle+=2*Math.PI/5;
}
in.close();
}
}
4.8 ASCII 코드에 해당하는 문자 출력
암호:
public class Exercise04_08 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter an ASCII code: ");
int c=in.nextInt();
System.out.println("The character for ASCII code "+c+" is "+(char)c);
}
}
4.9 출력 문자의 유니코드 코드
암호:
import java.util.Scanner;
public class Exercise04_09 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a character: ");
char c=in.next().charAt(0);
System.out.println("The Unicode for the character "+c+" is "+(int)c);
}
}
4.11 10진수에서 16진수(0-15 사이의 정수)
(참고: 10 이상의 숫자 변환)
코드:
import java.util.Scanner;
public class Exercise04_11 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a decimal value (0 to 15): ");
int num=in.nextInt();
if(num>15||num<0) {
System.out.println(num+" is an invalid input");
}
else if(num<10){
System.out.println("The hex value is "+num);
}
else {
System.out.println("The hex value is "+(char)('A'+num-10));
}
}
}
4.13 모음 또는 자음 결정
모음과 자음을 판단하는 문자를 입력하십시오
. 코드:
import java.util.Scanner;
public class Exercise04_08 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a letter: ");
char l=in.next().charAt(0);
if(Character.toUpperCase(l)=='A'||Character.toUpperCase(l)=='O'||Character.toUpperCase(l)=='E'||Character.toUpperCase(l)=='I'||Character.toUpperCase(l)=='U')
{
System.out.println(l+" is a vowel");
}
else if(Character.isLetter(l))
{
System.out.println(l+" is a consonant");}
else
System.out.println(l+" is an invalid input");
}
}
4.17 일
월의 일수를 표시하려면 연도 이름의 처음 세 글자를 입력합니다.
public class Exercise04_17 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a year: ");
int year=in.nextInt();
System.out.print("Enter a month: ");
String month=in.next();
if(month.equals("Jan")||month.equals("Mar")||month.equals("May")||month.equals("Jul")||
month.equals("Agu")||month.equals("Oct")||month.equals("Dec"))
{
System.out.println(month+" "+year+" has 31 days");
}
else if(month.equals("Nov")||month.equals("Apr")||month.equals("Jun")||month.equals("Sep"))
{
System.out.println(month+" "+year+" has 30 days");
}
else if(month.equals("Feb")) {
if((year%400==0)||(year%4==0&&year%100!=0)) {
System.out.println(month+" "+year+" has 29 days");}
else {
System.out.println(month+" "+year+" has 28 days");}
}
else {
System.out.println(month+" is not a correct month name");}
}}
4.18 전공 및 재학생 현황
public class Exercise04_18 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter two characters: ");
String s=in.nextLine();
if(s.charAt(0)=='M')
System.out.print("Mathematics ");
else if(s.charAt(0)=='C') {
System.out.print("Computer Science ");
}
else if(s.charAt(0)=='I') {
System.out.print("Information technology ");
}
else {
System.out.print("Invalid input ");
System.exit(1);
}
if(s.charAt(1)=='1') {
System.out.print("Freshman");
}
else if(s.charAt(1)=='2') {
System.out.print("Sophomore ");
}
else if(s.charAt(1)=='3') {
System.out.print("Junior");
}
else if(s.charAt(1)=='4') {
System.out.print("Senior");
}
else {
System.out.print("Invalid status code ");
System.exit(2);
}
}}
4.21 SSN 감지
주민등록번호, 형식은 DDD-DD-DDDD, D는 숫자로 입력이 적법한지 판단합니다.
public class Exercise04_18 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a SSN: ");
String s=in.nextLine();
if((s.charAt(3)=='-')&&(s.charAt(6)=='-')&&(Character.isDigit(s.charAt(0)))
&&(Character.isDigit(s.charAt(1)))&&(Character.isDigit(s.charAt(2)))
&&(Character.isDigit(s.charAt(4)))&&(Character.isDigit(s.charAt(5)))
&&(Character.isDigit(s.charAt(7)))&&(Character.isDigit(s.charAt(8)))
&&(Character.isDigit(s.charAt(9))))
{
System.out.println(s+" is a valid social security number");
}
else {
System.out.println(s+" is an invalid social security number");
}
}}
4.23 재정 신청: 사례비
보수 명세서를 출력합니다.
import java.util.Scanner;
public class Exercise04_23 {
public static void main(String[] args) {
String name;
double hours;
double hpay;
double ftaxr;//联邦税率
double staxr;//州税率
System.out.print("Enter employee's name: ");
Scanner in=new Scanner(System.in);
name=in.nextLine();
System.out.print("Enter number of hours worked in a week: ");
hours=in.nextDouble();
System.out.print("Enter hourly pay rate: ");
hpay=in.nextDouble();
System.out.print("Enter federal tax withholding rate: ");
ftaxr=in.nextDouble();
System.out.print("Enter state tax withholding rate: ");
staxr=in.nextDouble();
double total=hours*hpay;
double ftax=ftaxr*total;
double stax=staxr*total;
double alltax=ftax+stax;
double net=total-alltax;
System.out.println("Employee Name: "+name);
System.out.println("Hours Worked: "+hours);
System.out.println("Pay Rate: $"+hpay);
System.out.println("Gross Pay: $"+total);
System.out.println("Deductions:\n"
+ " Federal Withholding ("+(int)(ftaxr*100)/100.0+"%): $"+ftax);
System.out.println(" State Withholding ("+(int)(staxr*100)/100.0+"%): $"+(int)(stax*100)/100.0);
System.out.println(" STotal Deduction: $"+(int)(alltax*100)/100.0);
System.out.print("Net Pay: $"+(int)(net*100)/100.0);
}
}
보충 지식 포인트:
1. 삼각함수
연습문제 4.2는 Math.toRadians() 메서드를 사용하여 각도를 라디안으로 변환
하고 acos() 메서드를 사용하여 arcos 역삼각 함수를 계산합니다.
연습 4.6은 Math.toDegrees() 메서드를 사용하여 라디안을 각도로 변환합니다.
2. 문자열 읽기
-
문자열에서 한 문자만 읽어야 하는 경우 charAt() 메서드를 사용할 수 있습니다.
예:
문자열 str = "abc";
문자열에서 문자 가져오기
char ch = str.charAt(0); 첫 번째 문자
char ch2 = str.charAt(1); 두 번째 문자
ch는 a, ch2는 b ; -
next() 메서드를 사용할 때 입력 문자열은 공백을 포함할 수 없습니다.
-
nextLine() 메서드는 공백의 영향을 받지 않고 한 번에 한 줄의 데이터를 읽을 수 있습니다.
-
Java는 또한 BufferedReader 클래스를 사용하여 문자열을 수신하고 readLine() 메서드를 호출하여 문자열을 얻을 수 있습니다.
3. 문자열 변환 케이스의 방법
Exercise 4.11은 Character.toUpperCase() 메서드를 사용하여 판단하기 쉽도록 모든 문자를 대문자로 한 새로운 문자열을 반환합니다.
Character.isLetter(ch)는 지정된 문자가 문자이면 true를 반환합니다.
4. 출구 출구
system.exit(int 상태) 。
정상 종료:
상태가 0이면 프로그램이 정상적으로 종료됩니다. 즉, 현재 실행 중인 Java 가상 머신이 종료됩니다.
비정상 종료:
상태가 0이 아닌 다른 정수(음수 포함, 일반적으로 1 또는 -1)이면 현재 프로그램이 비정상적으로 종료되었음을 의미합니다.
5. 소수점 이하 자릿수 유지
예 4.23 참조
(int)(net*100)/100.0) 소수점 2자리 유지