手把手带你刷好题(牛客刷题③)

ced485cbb11e458d81a746890b32cf3f.gif

作者:月亮嚼成星~

博客主页:月亮嚼成星~的博客主页

专栏:手把手带你刷牛客

工欲善其事必先利其器,给大家介绍一款超牛的斩获大厂offer利器——牛客网

点击免费注册和我一起刷题吧

 

文章目录

重写父类方法 

创建单例对象

动态字符串


重写父类方法 

描述

父类Base中定义了若干get方法,以及一个sum方法,sum方法是对一组数字的求和。请在子类 Sub 中重写 getX() 方法,使得 sum 方法返回结果为 x*10+y

输入描述:

整数

输出描述:

整数的和

手把手带你刷好题(牛客刷题③)_第1张图片

题解:

Sub是Base的子类,因此继承了父类的成员变量和成员方法,成员方法中,getY()和sum()因为加了final关键字,无法被修改,子类中是直接使用,而getX()函数可以在子类中重写,我们重写为获取x的值扩大10倍。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            Sub sub = new Sub(x, y);
            System.out.println(sub.sum());
        }
    }

}

class Base {

    private int x;
    private int y;

    public Base(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public final int getY() {
        return y;
    }

    public final int sum() {
        return getX() + getY();
    }

}

class Sub extends Base {

    public Sub(int x, int y) {
        super(x, y);
    }

    //write your code here......
    public int getX(){
        return super.getX()*10;
    }


}

 创建单例对象

描述

Singleton类是单例的,每次调用该类的getInstance()方法都将得到相同的实例,目前该类中这个方法尚未完成,请将其补充完整,使得main()函数中的判断返回真(不考虑线程安全)。

输入描述:

输出描述:

true

 题解:

由于Singleton类是单例的,每次调用该类的getInstance()方法都将得到相同的Singleton类型实例,所以getInstance()方法的返回类型应为Singleton。预设代码中,getInstance()方法为类直接调用,所以该方法应为静态方法。在该方法中进行判断,若instance == null即不存在实例时则新建Singleton,否则直接返回已有的instance。将此处判断逻辑写入getInstance()方法中,补全getInstance()方法。

public class Main {

    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }

}

class Singleton {

    private static Singleton instance;

    private Singleton() {

    }
      //write your code here......
public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}
  


}

动态字符串

描述

将一个由英文字母组成的字符串转换成从末尾开始每三个字母用逗号分隔的形式。

输入描述:

一个字符串

输出描述:

修改后的字符串

手把手带你刷好题(牛客刷题③)_第2张图片

题解:

在原有的字符串的基础上创建一个可以修改的新的字符串,然后利用insert方法从后三位开始插入逗号,最后将修改后的StringBuilder转变为String类进行输出。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        //write your code here......
        StringBuilder newstr=new StringBuilder(str);
        for(int i=str.length()-3;i>=0;i-=3){
            newstr.insert(i,',');
        }
        System.out.println(newstr.toString());

    }
}

 

 “ 本期的分享就到这里了, 记得给博主一个三连哈,你的支持是我创作的最大动力! 

你可能感兴趣的:(手把手带你刷牛客,java,jvm,开发语言)