PTA JAVA编程题汇总(一)

日期加减


import java.text.SimpleDateFormat;
import java.util.*;
public class Main  {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
         Calendar date = Calendar.getInstance();
          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
          long l = in.nextLong();
         Long i = in.nextLong();
         date.setTimeInMillis(l);
        long n=i*24*60*60*1000+l;
        Date date2 = new Date(n); 
        System.out.println(format.format(date.getTime()));
          System.out.println(format.format(date2));
	}
}


声明图书类

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct NodeType
{
int id;
int password;
struct NodeType *next;
} NodeType;
int m = 0 ;
void CreaList(NodeType **, int);
NodeType *GetNode(int,int);
void PrntList(NodeType *);
int IsEmptyList(NodeType *);
void JosephusOperate(NodeType **,int);
int main(void){
int n = 0 ;

NodeType *pHead = NULL;
scanf("%d",&n);
scanf("%d",&m);
CreaList(&pHead,n);
JosephusOperate(&pHead,m);
return 1;
}
void CreaList(NodeType **ppHead,int n)
{
int i = 0;
int iPassword = 0;
NodeType *pNew = NULL;
NodeType *pCur = NULL;
for(i =1;i<= n;i++){
iPassword = m;
pNew = GetNode(i,iPassword);
if(*ppHead == NULL)
{
*ppHead = pCur = pNew;
pCur->next = *ppHead;
}
else
{
pNew->next = pCur->next;
pCur->next = pNew;
pCur = pNew;
}
}
}
NodeType *GetNode(int iId, int iPassword)
{
NodeType *pNew = NULL;
pNew = (NodeType *)malloc(sizeof(NodeType));
pNew->id = iId;
pNew->password = iPassword;
pNew->next = NULL;
return pNew;
}
void JosephusOperate(NodeType **ppHead,int iPassword)
{
int iCounter = 0;
int iFlag = 1;
NodeType *pPrv = NULL;
NodeType *pCur = NULL;
NodeType *pDel = NULL;
pPrv = pCur = *ppHead;
while(pPrv->next != *ppHead)
pPrv = pPrv->next;
while(iFlag){
for(iCounter =1 ;iCounter <iPassword;iCounter++)
{
pPrv=pCur;
pCur=pCur->next;
}
if(pPrv ==pCur) iFlag = 0;
pDel = pCur;
pPrv->next = pCur->next;
pCur = pCur->next;
iPassword = pDel->password;
printf("%d ",pDel->id);
free(pDel);
}
*ppHead = NULL;
}


三边,求解三角形的面积


import java.util.Scanner;
public Main 三角形面积 {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.print("Enter three bians: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
if(a + b > c && a + c > b && b + c > a && a > 0 && b > 0 && c > 0){
double S = (a+b+c)/2.0;
double P = Math.sqrt(S*(S-a)*(S-b)*(S-c));
System.out.printf("The area is:%.3f\n",P);

    }
else
      System.out.println("It can not be created a triangle");
   }
}

学生类-构造函数


import java.util.Scanner;


public class Main{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in 


);
        Student student = new Student(scanner.next(), scanner.nextInt(), scanner.next());
        System.out.println(student);
    }
}
class Student {
    private String name;
    private String sex;
    private int age;
    public Student(String name, int age, String sex) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }


    @Override
    public String toString() {
        return "Student [name='"+ this.name  + "', sex='" + this.sex + "', age=" + this.age + "]";
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name  = name;
    }


    public String getSex() {
        return sex;
    }


    public void setSex(String sex) {
        this.sex = sex;
    }


    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        this.age = age;
    }
}


使用公历类GregorianCalendar


import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;


public class Main {
    public static void main(String[] args){
        GregorianCalendar gcl= new GregorianCalendar();
        Scanner in = new Scanner(System.in);
        long time = in.nextLong();
        gcl.setTimeInMillis(time);
        System.out.println(gcl.get(Calendar.YEAR)+"-"+gcl.get(Calendar.MONTH)+"-"+gcl.get(Calendar.DAY_OF_MONTH));
    }
}


给定两个点的坐标,求解两个点的距离



import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        DecimalFormat mFormat = new DecimalFormat("#.##");
        Scanner in = new Scanner(System.in);
        double a = in.nextDouble();
        double b = in.nextDouble();
        System.out.printf("The distance is %.2f",Math.hypot((in.nextDouble()-a), (in.nextDouble()-b)));
        in.close();
    }
}


给定一个字符串,判定是否是数字


import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in 


);
String s = input.nextLine();
try{
float f = Float.parseFloat(s);
System.out.println("true");
}catch(Exception e){
System.out.println("false");
}
}
}


伪随机数



import java.util.Random;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in 


);
int n = input.nextInt();
int m = input.nextInt();
int k = input.nextInt();
int x = 0;
Random r = new Random(k);
for(int i = 1; i <= n; i++) {
x = r.nextInt(m);
}
System.out.println(x);
}
}


手机号

方法1

import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		String s = input.nextLine();
		int len = s.length();
		if(len != 11) {
			System.out.println("No");
		}
		else {
			char o = s.charAt(0);
			if(o != '1') {
				System.out.println("No");
			}
			else {
				boolean flag = true;
				for(int i = 1; i < len; i++){
					char n = s.charAt(i);
					if(n > '9' || n < '0') {
						System.out.println("No");
						flag = false;
						break;
					}
				}
				if(flag) {
					System.out.println("Yes");
				}	
			}
		}
	}
}
方法2

import java.util.Scanner;
import java.util.Arrays;
public class Main {
	public static void main(String[] args) 
	{
		int i = 0;
		Scanner in = new Scanner (System.in);
		String num1 = in.nextLine();
		for ( i = 0; i < num1.length(); i++)
		{
			if (!Character.isDigit(num1.charAt(i))){
				System.out.println("No");
				break;
         		   }
		}
		if(i==num1.length())
		{
			long num = Long.parseLong(num1); 
			long a = num;
			long b = 0;
			long []list = {0,1,2,3,4,5,6,7,8,9};
			int temp = 0;
			for (temp=0;a>=1;temp++)
			{ 
				a = a / 10; 
			}
			for (;num>1;)
			{
				num = num /10;
			}
			if(temp == 11 && num ==1)
			{
				System.out.println("Yes");
			}
			else{
				System.out.println("No");
			}
		}
	}
} 


字符串替换


import java.util.ArrayList;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> ls = new ArrayList<String>();
        Scanner in = new Scanner(System.in);
        int len = 0;
        ls.add(in.nextLine());
        while (ls.get(len).compareTo("end") != 0) {
            len++;
            ls.add(in.nextLine());
        }
        String a = in.nextLine();
        String b = in.nextLine();
        String[] ss = new String[len];
        for (int i = 0; i < len; i++)
            ss[i] = ls.get(i).replace(a, b);
        for (int i = 0; i < len; i++)
            System.out.println(ss[i]);
        in.close();
    }
}

 找素数


import java.math.BigInteger;
import java.util.Scanner;
public class Main{
     public static void main(String[] args){
         Scanner in=new Scanner(System.in);
        String sc = in.next();
        BigInteger m = new BigInteger(sc);
        int  n = in.nextInt();              
         int i=0;
         while(i<n){
             if(isPrime(m)){
                 System.out.println(m);
                 i++;
             }
             m=m.add(BigInteger.ONE);
         }
     }
     public static boolean isPrime(BigInteger num) {              
         return num.isProbablePrime(50);
     }
}


大数整除

import java.math.BigInteger;
import java.util.Scanner;


public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        BigInteger m = new BigInteger(Long.MAX_VALUE + "");
        String s = in.next();
        BigInteger n = new BigInteger(s);
        BigInteger zero = new BigInteger("0");
        m = m.add(BigInteger.ONE);
        int count = 0;
        
        while(count<3) {
            if(division(m,n).compareTo(zero)==0) {
                System.out.println(m);
                count++;
            }
            m = m.add(BigInteger.ONE);
        }
        in.close();
    }
    public static BigInteger division(BigInteger m,BigInteger n) {
        return m.divideAndRemainder(n)[1];
    }
}


求解给定字符串的前缀

import java.util.ArrayList;
import java.util.Scanner;
public class Main{


    public static void main(String[] args){
    Scanner in=new Scanner(System.in);  
    String s1="";
    String s2="";
    while(in.hasNext()){
            s1=in.nextLine();
            System.out.println(isPre(s1));
    }
    in.close();
    }
    public static String isPre(String s1){
        String result="";
        String[] stringArr=s1.split(" ");
        String s11=stringArr[0];
        String s12=stringArr[1];
        char[] ch1=s11.toCharArray();
        char[] ch2=s12.toCharArray();
        String list="";
        int sl1=s11.length()<s12.length()?s11.length():s12.length();
        for(int i=0;i<sl1;i++){
            if(ch1[i]!=ch2[i]) break;
            list+=ch1[i];
        }
        if(list=="") result+="No common prefix";
        else result="The common prefix is "+list;
        return result;
    }
}


两个巨大素数(质数)的乘积


import java.math.BigInteger;
import java.util.Scanner;


public class Main{
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        BigInteger Big1,Big2;
        Big1 = new BigInteger(cin.next());
        Big2 = new BigInteger(cin.next());
        System.out.println(Big1.divide(Big2));
    }
}


创建一个直角三角形类实现IShape接口

class RTriangle implements IShape
{
 private double a,b;
 public RTriangle(double a1,double b1)
 {
     a=a1;b=b1;
 } 
 public double getArea() {
     return a*b*0.5;
 }
 public double getPerimeter() {
     return a+b+Math.sqrt(a*a+b*b);
 }
}


从抽象类shape类扩展出一个正n边形

class RegularPolygon extends shape {
    private int n;
    private double side;
    public RegularPolygon(int n, double side) {
        this.n = n;
        this.side = side;
    }
    public double getArea() {
        return n*side*side/(Math.tan(Math.toRadians(180/n))*4);
    }
    public double getPerimeter() {
        return n*side;
    }
}


找出最大的对象

import java.util.Scanner;
public class Main {
	public static void main(String[] args)  {
        Scanner scanner = new Scanner(System.in);
        String[] t;
        int[] intArray = new int[5];
        String[] stringArray = new String[5];

        for (int i = 0; i < 5; i++) {
            String string = scanner.nextLine();
            stringArray[i] = string;
        }
        String maxs = "";
        for (String s : stringArray) {
            if (s!=null && s.compareTo(maxs) > 0) {
                maxs = s;
            }
        }
        t = scanner.nextLine().split(" ");
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < 5; i++) {
            int num = Integer.parseInt(t[i]);
            if (num > max) {
                max = num;
            }
        }
        System.out.println("Max string is " + maxs);
        System.out.println("Max integer is " + max);
   }
}


求几何形状的面积之和

import java.text.DecimalFormat;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) 
{
Scanner in = new Scanner(System.in);
double r1 = in.nextDouble();
double r2 = in.nextDouble();
double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();
double d = in.nextDouble();
double tot = Math.PI*(Math.pow(r1, 2)+Math.pow(r2, 2))+a*b+c*d;

DecimalFormat df = new DecimalFormat("#.0000");
System.out.println("The total area is "+df.format(tot));
}
}


简单的计算器

import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String string = in.next();
        String[] ob = string.split("\\D");
        BigInteger a = new BigInteger(ob[0]);
        BigInteger b = new BigInteger(ob[1]);
       int op = 0;
        if (string.indexOf("+")!=-1)        op=1;
        else if (string.indexOf("-")!=-1)   op=2;
        else if (string.indexOf("*")!=-1)   op=3;
        else                                op=4;

        switch (op){
            case 1:
                System.out.println(a.add(b));
                break;
            case 2:
                System.out.println(a.subtract(b));
                break;
            case 3:
                System.out.println(a.multiply(b));
                break;
            case 4:
                System.out.println(a.divide(b));
                break;
            default:
                System.out.println("op error.");
                break;
        }
    }
}


使用公历类GregorianCalendar

import java.util.*;
public class Main
{
    public static void main(String[]args)
    {
        Scanner in=new Scanner(System.in);
        GregorianCalendar g=new GregorianCalendar();
        g.setTimeInMillis(in.nextLong());
        System.out.println(g.get(Calendar.YEAR)+"-"+g.get(Calendar.MONTH)+"-"+g.get(Calendar.DAY_OF_MONTH));
         in.close();
    }
}
查找电话号码

import java.util.HashMap;
  import java.util.Map;
  import java.util.Scanner;
  
  public class Main {
      public static void main(String[] args) {
          Map<String, String> list = new HashMap<String, String>();
          String s;
         Scanner scanner = new Scanner(System.in);
         String a= scanner.next();
 
         while (!a.equals("noname")) {
             s = scanner.next();
 
             list.put(a, s);
             a = scanner.next();
 
         }
         String string = scanner.next();
         if (list.get(string) != null) {
             System.out.println(list.get(string));
         }
       else {
             System.out.println("Not found.");
         }
 
     }
}






      

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页