请仔细阅读右侧代码,根据方法内的提示,在Begin - End区域内进行代码补充,具体任务如下: 编写测试类,输入一个标准的网址,输出其域名的主体; 将该主体转换为大写,打印输出; 具体输出要求请看测试说明。
时间: 2024-10-31 22:07:18 浏览: 34
```java
import java.net.URL;
import java.util.Scanner;
public class DomainExtractor {
public static String extractDomain(String urlString) {
try {
URL url = new URL(urlString);
return url.getHost(); // 获取域名
} catch (Exception e) {
System.out.println("Invalid URL format.");
return null;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个标准的网址:");
String inputUrl = scanner.nextLine();
String domain = extractDomain(inputUrl); // 提取域名
if (domain != null) { // 如果提取成功
domain = domain.toUpperCase(); // 转换为大写
System.out.println("提取的域名主体(大写): " + domain);
} else {
System.out.println("无法获取域名,检查输入URL是否有效。");
}
scanner.close();
}
}
// 测试说明:
// 输入例如: https://www.example.com
// 输出应为: EXAMPLE.COM
```
在这个Java代码片段中,我们首先创建了一个`DomainExtractor`类,其中包含一个静态方法`extractDomain`用于从给定的URL字符串中提取域名。然后在`main`方法中,我们通过`Scanner`从用户那里获取输入,并调用`extractDomain`方法处理输入。
如果域名提取成功,我们将它转换为大写并打印出来;如果失败,则显示错误消息。请注意,此代码假设输入URL是有效的,实际应用中需要添加更多的异常处理。
阅读全文
相关推荐



















