1.请按照以下要求设计一个Test类。
要求如下: 定义一个PrintArray()和BubbleSort()方法,方法参数都为数组类型。2)在PrintArray()方法中通过for循环对数组进行遍历输出,BubbleSort()中使用双层for循环实现对数组元素的排序。3)最后在Main()方法中定义一个数组arr,对数组arr进行排序操作,并输出排序前和排序后的数组结果,进行比较。
这个Test类包含了PrintArray()方法用于输出数组元素和BubbleSort()方法用于对数组进行冒泡排序。在Main()方法中,首先创建一个Test类的实例,然后定义一个数组并调用PrintArray()方法输出排序前的数组。接着调用BubbleSort()方法对数组进行排序,最后再次调用PrintArray()方法输出排序后的数组。
以下是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
public static void PrintArray(int[] arr)
{
for(int i = 0;i< arr.Length; i++)
{
Console.WriteLine(arr[i] + "");
}
Console.WriteLine();
}
public static void Bubblesort(int[] arr)
{
int n = arr.Length;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
static void Main(string[] args)
{
int[] arr = { 5, 2, 8, 12, 9, 10, 23, 1, 4 };
Console.WriteLine("排序前的数组:");
PrintArray(arr);
Bubblesort(arr);
Console.WriteLine("排序后的数组:");
PrintArray(arr);
}
}
}
运行结果:
2.请按照以下要求设计一个Student类。(考察知识点为构造方法重载)
要求如下: 在Student类中定义三个重载的构造方法,一是无参的构造方法,二是接收一个string类型参数的构造方法,该方法用于为Name属性赋值,三是接收两个参数的构造方法,该方法用于为Name、Age字段赋值。 定义一个测试类,在Main()方法中创建三个Student对象,并在创建对象时为name、age字段赋值。
这段代码创建了一个Student类,并在其中定义了三个不同的构造方法,用于满足无参、接收一个字符串参数和接收一个字符串参数和一个整数参数的情况。然后在Test类的Main()方法中创建了三个Student对象,并为它们的Name和Age字段赋值,并输出了测试结果。
以下是运行代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
internal class Program
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
//无参构造方法
public Student()
{
}
//接收一个string类型参数的构造方法
public Student(string name)
{
Name = name;
}
//接收两个参数的构造方法
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
public class Test
{
static void Main(string[] args)
{
//创建三个Student对象,并为name、age字段赋值
Student student1 = new Student();
student1.Name = "wangshuo";
student1.Age = 21;
Student student2 = new Student();
student2.Name = "lixuelei";
student2.Age = 21;
Student student3 = new Student();
student3.Name = "shidonghua";
student3.Age = 22;
//测试输出
Console.WriteLine($"Student 1:Name-{student1.Name},Age-{student1.Age}");
Console.WriteLine($"Student 2:Name-{student2.Name},Age-{student2.Age}");
Console.WriteLine($"Student 3:Name-{student3.Name},Age-{student3.Age}");
}
}
}
}
运行结果