段软w 发表于 2021-1-10 17:10:16

求助两道简单的程序设计题!

1. Given class Test as follows. Please complete the program such that it can run correctly and output the result as follws.

        John’s friend is Mary
        Mary’s friend is John
public class Test{
        public static void main(String[ ] args){
        Person john =new Person(“John”);
        Person mary =new Person(“Mary”);
        john.setFriend(mary);
        System.out.println(john.getInfo());
        System.out.println(mary.getInfo());
        }
}
写了部分 后面差的的如何补上呢!
2.Given class Test as follows. Please complete the program such that it can run correctly
and output the result as follows.
       

Import java.util.*;
Public class Test{
        private static Weword addTo(Weword w.ArrayList list){
                for(int i = 0;i < list.size();i++) if(w.equals (list.get(i))) return list.get(i);
                list.add(w);
                return w;
public static void main(String[] args){
        String line = “Trump’s eldest son has tested positive for the coronavirus”;
        String[] words = line.split(“ “);
        ArrayList list = new ArrayList();
        for(int i = 0;i < words.length;i++){
                Weword w = addTo(new Weword(words),list);
                w.num++;
        }
        System.out.println(list);
}

非常非常感谢!

段软w 发表于 2021-1-10 17:15:30

救救孩子 感谢大佬们

89684794@qq.com 发表于 2021-2-5 15:08:53

题目的要求是输出“John’s friend is Mary”    “Mary’s friend is John” 这两句话就可以了吧。
你创建一个Person类,定义一个name和friend变量,创建set和get方法,一个有参的构造方法。在创建一个getInfo()方法,里面就写System.out.println(name+"’s friend is"+friend)。
主函数main题目已经写好了,你运行就可以了 。。
你试试看 ,是不是这样的!!

百里狂生 发表于 2021-2-9 12:23:43

1、
class Person{
        String name;
        String friend;
        public Person(String name) {
                this.name = name;
        }
       
        void setFriend(Person friend) {
                this.friend = friend.name;
                friend.friend = this.name;
        }
       
        String getInfo() {
                return name+"'s friend is "+friend;
        }
}
2、
class Weword{
        int num;
        String word;
        public Weword(String word) {
                this.word = word;
        }
        @Override
        public String toString() {
                return word+":"+num;
        }
}
页: [1]
查看完整版本: 求助两道简单的程序设计题!