class A{ public A(String str){ System.out.println(str); } public static void main(String[] args){ //A a1= new A(); //编译通不过 } } 请问注释的语句为什么编译通不过?
时间: 2024-03-14 10:45:56 浏览: 18
在这个例子中,类A定义了一个带有参数的构造方法,即:
```java
public A(String str) {
System.out.println(str);
}
```
由于类A没有定义无参构造方法,因此在创建类A的实例时,必须使用带有参数的构造方法。如果尝试使用无参构造方法创建类A的实例,编译器会报错,因为找不到符合要求的构造方法。
在类A中,下面这行代码会导致编译错误:
```java
A a1 = new A(); // 编译错误:找不到符合要求的构造方法
```
因为这里使用了无参构造方法创建类A的实例,但是类A中没有定义无参构造方法。如果要解决这个问题,可以修改代码使用带有参数的构造方法来创建类A的实例,例如:
```java
A a1 = new A("Hello, world!");
```
这样就可以正确地创建类A的实例并打印出相应的信息。
相关问题
class A{ public A(String str){ System.out.println(str); } public static void main(String[] args){ //A a1= new A(); //编译通不过 } }
在这个例子中,类A定义了一个带有参数的构造方法,即:
```java
public A(String str) {
System.out.println(str);
}
```
由于类A没有定义无参构造方法,因此在创建类A的实例时,必须使用带有参数的构造方法。如果尝试使用无参构造方法创建类A的实例,编译器会报错,因为找不到符合要求的构造方法。
在类A中,下面这行代码会导致编译错误:
```java
A a1 = new A(); // 编译错误:找不到符合要求的构造方法
```
因为这里使用了无参构造方法创建类A的实例,但是类A中没有定义无参构造方法。如果要解决这个问题,可以修改代码使用带有参数的构造方法来创建类A的实例,例如:
```java
A a1 = new A("Hello, world!");
```
这样就可以正确地创建类A的实例并打印出相应的信息。
public class StrDemo{ public static void main(String[] args){ String str1=”We are Students”; int n1=str1.length; int n2=str1.indexof(“students”) boolean b=str1.contains(“good”) System.out.println(n1); System.out.println(n2); System.out.println(b); }
这段代码有一些语法错误,应该修改为:
```
public class StrDemo {
public static void main(String[] args) {
String str1 = "We are Students";
int n1 = str1.length();
int n2 = str1.indexOf("students");
boolean b = str1.contains("good");
System.out.println(n1);
System.out.println(n2);
System.out.println(b);
}
}
```
这段代码的作用是定义一个 `StrDemo` 类,其中包含一个 `main` 方法。在 `main` 方法中,定义了一个字符串变量 `str1`,并获取了它的长度和包含子串 `"students"` 的位置。同时,使用 `contains` 方法判断字符串中是否包含子串 `"good"`,并将结果输出到控制台。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)