使用java中,面向对象封装+继承的方法算题
1.第一种:给定一行字符,逆序输出此字符串(空格.数字不输出),如“ab 23,(4 cd”输出“dc(,ba”。(要求:使用面向对象封装+继承)
class Bu { private String str; public Bu(){} public Bu(String str){ this.str = str; } public String getStr(){ return str; } public void setStr(String str){ this.str = str; } public String getInfo(){ return str; } } class Rvs extends Bu //负责翻转 { public Rvs(){} public Rvs(String str){ super(str); } public void m(){ //给定字符串,逆序输出字符串
String temp = ""; //定义新的字符串变量负责接收逆序后的字符串 char[] chs = super.getStr().toCharArray(); for(int i = chs.length-1;i >= 0;i--){ temp += chs[i]; } super.setStr(temp); } } class Oth extends Rvs //去掉数字和空格 { public Oth(){} public Oth(String str){ super(str); } public void m2(){ String temp = ""; char[] chs = super.getStr().toCharArray(); //先去掉数字 for(int i = 0;i < chs.length;i++){ if(chs[i] >= '0' && chs[i] <= '9'){ continue; } temp += chs[i]; } temp = temp.replace(" ",""); //再去空格,用replace()方法 super.setStr(temp); } } class Statt { public static void main(String[] args) { //Rvs r = new Rvs("4m 897ou // "); //r.m(); //System.out.println(r.getInfo()); Oth oth = new Oth("4m 897ou // "); oth.m(); //字符串的逆序 oth.m2(); //逆序后字符串去掉空格和数字 System.out.println(oth.getInfo()); //最后输出是getInfo()内容 } }
2.第二种:输入数字n,是奇数n就变为3n+1,是偶数就是n/2,经过若干次这样的变换,一定会使n变为1,求输出变换的次数,并要求次数是
除以3的余数 (要求:使用面向对象封装+继承)
package com.oracle.acm.prac;
class X{
private int n;
private int count; //次数
public X(){
count=0;
}
public X(int n){
count=0;
this.n=n;
}
public void changeNum(){
//若n为奇数,则将n变为3n+1,否则变为n的一半
if(n%2!=0){
n=3*n+1;
}else{
n=n/2;
}
}
public int getChangeCount(){
//经过若干次这样的变换,一定会使n变为1.求输出变换的次数
while(n!=1){
this.changeNum();
count++;
}
return count%3; //要求次数要对3取余
}
}
public class Demo10 {
public static void main(String[] args) {
X x=new X(2);
System.out.println(x.getChangeCount());
}
}
/**给定一行字符,逆序输出此字符串(空格.数字不输出),如“ab 23,(4 cd”输出“dc(,ba”。要求:使用面向对象封装+继承 */
class Bu{private String str;public Bu(){}public Bu(String str){this.str = str;}public String getStr(){return str;}public void setStr(String str){this.str = str;}public String getInfo(){return str;}}class Rvs extends Bu{public Rvs(){}public Rvs(String str){super(str);}public void m(){String temp = "";char[] chs = super.getStr().toCharArray();for(int i = chs.length-1;i >= 0;i--){temp += chs[i];}super.setStr(temp);}}class Oth extends Rvs{public Oth(){}public Oth(String str){super(str);}public void m2(){String temp = "";char[] chs = super.getStr().toCharArray();for(int i = 0;i < chs.length;i++){if(chs[i] >= '0' && chs[i] <= '9'){continue;}temp += chs[i];}temp = temp.replace(" ","");super.setStr(temp);}}class Statt {public static void main(String[] args) {//Rvs r = new Rvs("4m 897ou // ");//r.m();//System.out.println(r.getInfo());Oth oth = new Oth("4m 897ou // ");oth.m();oth.m2();System.out.println(oth.getInfo());
} }