面向对象程序设计JAVA学习记录(3)

1.Point position

Given a directed line from point p0(x0, y0) to p1(x1, y1), you can use the following condition to decide whether a point p2(x2, y2) is on the left of the line, on the right, or on the same line

(a) p2 is on the left of the line. (b) p2 is on the right of the line. (c) p2 is on the same line.

Write a program to get the three points for p0, p1, and p2 and displays whether p2 is on the left of the line from p0 to p1, on the right, or on the same line.

Input:
x, y coordinates of three points p0, p1 and p2.

Output:
point position information. if p2 is on the left/right side of the line, output "(x2, y2) is on the left/right side of the line from (x0, y0) to (x1, y1)". Otherwise, output "(x2, y2) is on the line from (x0, y0) to (x1, y1)". (x0, y0), (x1, y1) and (x2, y2) are the coordinates of the points respectively.

Example Input:
4.4 2 6.5 9.5 -5 4

Example Output:
(-5.0, 4.0) is on the left side of the line from (4.4, 2.0) to (6.5, 9.5)

该题就是计算相对位置,注意输出格式

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        double x0 = s.nextDouble();
        double y0 = s.nextDouble();
        double x1 = s.nextDouble();
        double y1 = s.nextDouble();
        double x2 = s.nextDouble();
        double y2 = s.nextDouble();
        double r = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0);
        if(r>0) System.out.printf("(%.1f, %.1f) is on the left side of the line from (%.1f, %.1f) to (%.1f, %.1f)\n",x2,y2,x0,y0,x1,y1);
        if(r<0) System.out.printf("(%.1f, %.1f) is on the right side of the line from (%.1f, %.1f) to (%.1f, %.1f)\n",x2,y2,x0,y0,x1,y1);
        if(r==0) System.out.printf("(%.1f, %.1f) is on the line from (%.1f, %.1f) to (%.1f, %.1f)\n",x2,y2,x0,y0,x1,y1);
        s.close();
    }
}

 2.Reverse it

Given a number n, you are required to output its reverse counterpart. that is, the most significant digit become the list significant digit and so on. There are several test cases for each test group.

Input: Test case count T following by each test case. Example:
5
12000
11111
012
5
-23

Output:
21
11111
21
5
-32

倒序输出,这里用字符串去解决,添加判断条件识别复数以及排去头部和末尾的0

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            String str = s.next();
            int a = str.length();
            char arr[] = str.toCharArray();
            if(arr[0] == '-'){
                int j, t;
                for(j = 1; j < a; j++){
                    if(arr[j] != '0') break;
                }
                for(t = a-1; t > j; t--){
                    if(arr[t] != '0') break;                    
                }
                if(j == a){
                    System.out.print("0");
                    continue;
                }
                System.out.print("-");
                for(int k = t; k > j-1; k--){
                    System.out.print(arr[k]);
                }
            }
            else{
                int j, t;
                for(j = 0; j < a; j++){
                    if(arr[j] != '0') break;
                }
                for(t = a-1; t > j; t--){
                    if(arr[t] != '0') break;                    
                }
                if(j == a) System.out.print("0");
                for(int k = t; k > j-1; k--){
                    System.out.print(arr[k]);
                }
            }
            System.out.print("\n");
        }
        s.close();
    }
}

3.Distance between points

Geometry is a great math aspect. You are interested in how long are two points. Each point is presented by its coordinates in format x1 y1 x2 y2. Your output for each pair of points should reserve 4 decimals. There are several test cases for each test group.

Input: Test case count T following by T group of coordinats. Example:
3
0.0 0.0 0.0 0.0
0.0 1.0 0.0 -1.0
0.0 0.0 1.0 1.0

Output:
0.0000
2.0000
1.4142

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            double x1 = s.nextDouble();
            double y1 = s.nextDouble();
            double x2 = s.nextDouble();
            double y2 = s.nextDouble();
            double r = (y2 - y1)*(y2 -y1) + (x2 - x1)*(x2 - x1);
            System.out.printf("%.4f\n",Math.sqrt(r));
        }
        s.close();
    }
}

4.Binary form

You are required to present a given integer its binary form. There may be several test cases for each test group.

Input: Test case count T following by each test case. Example:
4
12
-1
0
2147483647

Output:
1100
11111111111111111111111111111111
0
1111111111111111111111111111111

利用Integer.toBinaryString方法,可以轻松完成二进制输出

import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner a = new Scanner(System.in);
    int b = a.nextInt();
    for(int i=0;i\u003Cb;i++){
      int c = a.nextInt();
      System.out.println(Integer.toBinaryString(c));
    }
    a.close();
  }
}

5.Fahrenheit

Celsius and Fahrenheit designed two systems to measure the temperature. So they can be translated into each other. The formula for the translation is: C=5*(F-32)/9, where C is Celsius and F is Fahrenheit. Now you are given several cases of temperature in Fahrenheit. And they are expected to be translated into Celsius for the travelers. Reserve 2 decimals for each output. There are several test cases for each test group.

Input: Test case count T following by each test case. Example:
3
54.5
83
100

Output:
12.50
28.33
37.78

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            double f = s.nextDouble();
            double c = 5*(f - 32)/9;
            System.out.printf("%.2f\n",c);
        }
        s.close();
    }
}

6.The sum

You are given two numbers "from"(inclusive) and "to"(inclusive). And you are expected to create an application to sum up the numbers from "from" to "to" and prints out sum of these numbers.

If "From" is greater than "to", then output the testing case number.

Input: Total test case count T following by T cases of test instances. Example: 
4
4 5
6 10
20 19
3 3

output: For each test case, you should firstly output the test case number, then give the output. Example
Case 1: 9
Case 2: 40
Case 3:
Case 4: 3

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            int a = s.nextInt();
            int b = s.nextInt();
            if(a>b){
                System.out.printf("Case %d:\n",i+1);
                continue;
            }
            long sum = 0;
            for(int j = a; j <= b; j++){
                sum += j;
            }
            System.out.printf("Case %d: ",i+1);
            System.out.println(sum);
        }
        s.close();
    }
}

7.The UFOs

Problem Description

It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.

Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be 21 * 19 * 1 * 3 * 15 = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)

Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.

Examples:

Input Output
COMETQ
HVNGAT 
GO
ABSTAR
USACO 
STAY

INPUT

There may be multiple test cases. Each test case consists two lines as follows:

Line 1: An upper case character string of max length 6 that is the name of the comet.
Line 2: An upper case character string of max length 6 that is the name of the group.

OUTPUT

For each test case, output a single line containing either the word "GO" or the word "STAY".

SAMPLE INPUT

COMETQ
HVNGAT

SAMPLE OUTPUT

GO

题目比较难读懂,就是将每个字母按照字母表序号数字化,求乘积再取模,对比两行的结果,这里利用ASCII码,Integer.valueOf方法可以获取

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        while(s.hasNext()){
            String s1 = s.next();
            String s2 = s.next();
            int n1 =s1.length();
            int n2 =s2.length();
            char a1[] = s1.toCharArray();
            char a2[] = s2.toCharArray();
            long g1 = 1;
            long g2 = 1;
            for(int i = 0 ;i < n1 ;i++){
                int v1 = Integer.valueOf(a1[i]) - 64;
                g1 *= v1;
            }
            for(int j = 0 ;j < n2 ;j++){
                int v2 = Integer.valueOf(a2[j]) - 64;
                g2 *= v2;
            }
            g1 = g1%47;
            g2 = g2%47;
            if(g1 ==g2) System.out.println("GO");
            else System.out.println("STAY");
        }
        s.close();
    }
}

8.Name of the month

You are interested in the month presentation in different cultures. And now your boss assigned you a task: to transform the arabic presentation of months into its western counterpart. If it's a invalid month, then output "Invalid". There are several test cases for each test group.

Input: Test case count T following by each test case. Example:
3
1
6
0

Output:
Jan
Jun
Invalid

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++) {
            int a = s.nextInt();
            if(a == 1) System.out.println("Jan");
            else if(a == 2) System.out.println("Feb");
            else if(a == 2) System.out.println("Feb");
            else if(a == 3) System.out.println("Mar");
            else if(a == 4) System.out.println("Apr");
            else if(a == 5) System.out.println("May");
            else if(a == 6) System.out.println("Jun");
            else if(a == 7) System.out.println("Jul");
            else if(a == 8) System.out.println("Aug");
            else if(a == 9) System.out.println("Sep");
            else if(a == 10) System.out.println("Oct");
            else if(a == 11) System.out.println("Nov");
            else if(a == 12) System.out.println("Dec");
            else System.out.println("Invalid");
        }
        s.close();
    }
}

9.Substring

You are expected to get the substring of a given string.

For each test case, you are given a input line with a format of "startPos endPos MotherString". If the endPos is smaller than the startPos or the startPos exceed the length of the MotherString, output -1. If the startPos is ok and the endPos exceeds the length of MotherStirng, get the substring remaining and output it.

There are several test cases for each test group.

Input: Test case count T following by each test case. Example:
3
4 8 The quick brown fox jumps over the lazy dog
5 2 Invalid case
4 4 Single char

Output:
quick
-1
l

截取输入字符串中的一段,可以直接使用substring方法,注意到可能会先识别到一个空格,需+1

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++) {
            int a = s.nextInt();
            int b = s.nextInt();
            String str = s.nextLine();
            if(a > b) System.out.println("-1");
            else System.out.println(str.substring(a+1,b+2));
        }
        s.close();
    }

10.Is it a substring

Try to design a class named IsSubString(NOT public class), which has only one public method:
public boolean isSubString(String sub, String Mother){...}
The method searchs for a specific string within another string; the method must return true if the former exists in the latter string.

You don't need to worry about the input and the output. Just submit your class as specified. The preset codes will deal with all input and output issues and output True or False according to your logic.

Example:
isSubString("The", "The cat in the hat.") is true
isSubString("hat.", "The cat in the hat.") is true
isSubString("hat..", "The cat in the hat.") is false

So, pay attention and make sure that you test your program thoroughly.

Hint - Use the charAt(int index) method in the String class to retrieve a specific character from a string; the index starts with zero. For example.
"cat".charAt(0) is `c',
"cat".charAt(1) is `a',
and "cat".charAt(2) is `t'.
The length() method returns the number of characters in the string; e.g. "cat".length() is 3.
Use indexOf or similar methods is prohibited.

前置代码

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
import java.util.*;
class Main 
{
	public static void main(String[] args) 
	{
		IsSubString iss = new IsSubString();
		Scanner scanner = new Scanner(System.in);
		// Get test cases.
		String str = scanner.nextLine();
		int t = Integer.parseInt(str);
		while(t-->0){
			String sub = scanner.nextLine();
			String mother = scanner.nextLine();
			System.out.println(iss.isSubString(sub,mother));
		}
	}
}
/* PRESET CODE END - NEVER TOUCH CODE ABOVE */

建议直接使用contains方法,直接判断是否包含其中

class IsSubString{
    public boolean isSubString(String sub, String Mother){
        if(Mother.contains(sub)) return true;   
        else return false; 
    }
}

11.The Salary Calculator

At a certain company, a wor ker is paid an hourly rate of P1 dollars for the first 200 hours he works each month. He is paid an hourly rate of P2 dollars for the remaining hours. Return the minimum number of hours he must work this month to earn salary dollars.

Input

The first line contains a single integer T tells that there are T case in the problem. Then for each case, there are three integers, P1, P2, salary in order. 1<=P1, P2<=100; 1<=salary<=1000000.

Output

For each case return an double type value hour, up to 4 decimals.

Sample Input

2
10 15 1000
10 15 3000

Sample Output

100.0000
266.6667

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++) {
            double a = s.nextDouble();
            double b = s.nextDouble();
            double c = s.nextDouble();
            if(a*200 > c) System.out.printf("%.4f\n",c/a);
            else System.out.printf("%.4f\n",200+(c-200*a)/b);
        }
        s.close();
    }
}

12.Calculator?

You are to design a simple calculator for the childrens. Currently, you plan to provide addition, substract, multiplication, division, power, reminder(+-*/^%) operations. All other operations are invalid.

Input

Each line contains a arithmatic operation, the first char is the operator, following by two operands. Your calculator should perform the operations and output the answers.

Output

The output will consist of one line for each line of calculation. Leading zeros should be suppressed in the output. Insignificant trailing zeros must not be printed. Don't print the decimal point if the result is an integer. For invalid operations, output "Invalid".

Sample Input

+ 4 4
- -3 2
* 3 -4
/ 12 6
^ 2 3
% 6 5
+ 4.3 5

Sample Output

8
-5
-12
2
8
1
9.3

要做一个计算器,注意取模和除时候的非法输入0,增加一个输出规则,整数不输出小数点后,发现制作的规则在0.0000000不适用,故增加一个输出判断,程序应该还有优化空间

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        while(s.hasNext()){
            char m = s.next().charAt(0);
            double a = s.nextDouble();
            double b = s.nextDouble();
            if(m == '+'){
                if((a+b) == 0) System.out.println("0");
                else System.out.println(a+b);
            }
            else if(m == '-'){
                if((a-b) == 0) System.out.println("0");
                else System.out.println(doubleTrans(a-b));
            }
            else if(m == '*'){
                if((a*b) == 0) System.out.println("0");
                else System.out.println(doubleTrans(a*b));
            }
            else if(m == '/'){
                if(b != 0)System.out.println(doubleTrans(a/b));
                else System.out.println("Invalid");
            }
            else if(m == '^'){
                if(Math.pow(a,b) == 0) System.out.println("0");
                else System.out.println(doubleTrans(Math.pow(a,b)));
            }
            else if(m == '%'){
                if(b != 0)System.out.println(doubleTrans(a%b));
                else System.out.println("Invalid");
            }
            else System.out.println("Invalid");
        }
        s.close();
    }
    public static String doubleTrans(double num){
        String number1 = String.format("%.6f", num);
        double number2 = Double.parseDouble(number1);
        if(Math.round(number2)-number2 == 0){
            return String.valueOf((long)number2);
        }
        return String.valueOf(number2);
    }
}

13.Narcissistic numbers

An n-digit number that is the sum of the n-th powers of its digits is called an n-narcissistic number. It is also sometimes known as an Armstrong number, perfect digital invariant (Madachy 1979), or plus perfect number. Hardy (1993) wrote, "There are just four numbers, after unity, which are the sums of the cubes of their digits: 153=1^3+5^3+3^3, 370=3^3+7^3+0^3, 371=3^3+7^3+1^3, and 407=4^3+0^3+7^3. These are odd facts, very suitable for puzzle columns and likely to amuse amateurs, but there is nothing in them which appeals to the mathematician." Narcissistic numbers therefore generalize these "unappealing" numbers to other powers (Madachy 1979, p. 164).

The smallest example of a narcissistic number other than the trivial 1-digit numbers is:
153=1^3+5^3+3^3

For a given positive number "n", which indicates that there are n-digits. You are requested to find and output all these Narcissistic Numbers in order. If no such number exists, output "No".

Input

An Integer n

Output

All the Narcissistic Numbers of n-digit in natural order.

Sample Input

1

Sample Output

1 2 3 4 5 6 7 8 9

输出符合规律n1n2n3...nn=n1^n+n2^n+n3^n+...nn^n的数,我的思路是直接在所有n位数内逐个判断,运算比较复杂

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        while(s.hasNextInt()){
            int n = s.nextInt();
            int a = (int)Math.pow(10,n-1);
            int all = 0;
            int[] arr1 = new int[100];
            for(int i = a; i < 10*a; i++){
                int m = i;
                int[] arr = new int[n];
                for(int j = 0; j < n; j++){
                    arr[j] = m%10;
                    m = m/10;   
                }
                int bi = 0;
                for(int k = 0; k < n; k++){
                    bi += (int)Math.pow(arr[k],n);
                }
                if(bi == i){
                    arr1[all] = i;
                    all++;
                }
            }
            if(all > 0){
                for(int i = 0; i < all-1; i++){
                    System.out.printf("%d ", arr1[i]);
                }
                System.out.println(arr1[all-1]);
            }
            else System.out.println("No");
        }
        s.close();
    }
}

14.Value Added Tax

In Russia, the Value Added Tax is 18% for almost all goods, with the exception of certain food items, which have a Value Added Tax of only 10%.

You are given a String of product , the name of a product, and an int price , the price of the product before tax. You are also given a list of food , each element of which is the name of a food product. If the given product is an element in food, it is a food item (and thus subject to 10% tax), and otherwise, it is a non-food item (and thus subject to 18% tax). Calculate the price of the product after tax has been added.

Constraints:
product will contain between 1 and 50 characters, inclusive.
Each character in product will be a lowercase letter ('a'-'z').
price will be between 1 and 1000, inclusive.
food list will contain between 1 and 50 elements, inclusive.
Each element of food will contain between 1 and 50 characters, inclusive.
Each character in each element of food will be a lowercase letter ('a'-'z').
All elements of food will be distinct.

Input

The first line contains a single integer T tells that there are T case in the problem. Then there are 2 lines for each test case. The first line is the product name and its price. And the second line is a food list with the first integer indicating the number of food product in the list, following the food product names.

Output

The price of the product after tax has been added. Reserve 2 digit after the point.

Sample Input

3
milk 1
3 bread butter milk
car 100
3 bread butter milk
abc 57
3 a b c

Sample Output

1.10
118.00
67.26

逐个读入即可,第一个读入产品名,然后读入价格,再读入数量,最后是读入食品清单,可以用indexOf判断是否在食品清单中

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            String p = s.next();
            int v = s.nextInt();
            int num = s.nextInt();
            String f = s.nextLine();
            if(f.indexOf(p) == -1){
                System.out.printf("%.2f\n",v*1.18);
            }
            else System.out.printf("%.2f\n",v*1.1);
        }
        s.close();
    }
}

猜你喜欢

转载自blog.csdn.net/lijj0304/article/details/126965151