使用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(inti = 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());
} }
使用java中,面向對象封裝+繼承的方法算題