[英]Trying to print a subclass method in a main class in java
I have three classes.我有三个班。 An abstract class, a derived class and a main class.一个抽象的 class,一个派生的 class 和一个主要的 class。 I am trying to print the method in the derived class in the main class.我正在尝试在主 class 中的派生 class 中打印该方法。
public abstract class newsPaperSub {
public String name;
public abstract void address();
public double rate;
}
Derived class:派生 class:
import java.util.Scanner;
public class PhysicalNewspaperSubscription extends newsPaperSub {
@Override
public void address () {
String subAddress = " ";
Scanner input = new Scanner(System.in);
int i;
int digitCount = 0;
for (i = 0; i < subAddress.length(); i++) {
char c = subAddress.charAt(i);
if (Character.isDigit(c)) {
digitCount++;
System.out.println("Pease enter an address: ");
subAddress = input.nextLine();
if (digitCount <= 1) {
rate = 15;
System.out.println("Your subscrption price is: " + rate);
}
}
}
}
}
Main class: I havent been able to figure out what to exactly put in the main class in order to print the function in the derived class.主要 class:我无法弄清楚要在主要 class 中准确放置什么,以便在派生的 function 中打印 function I have tried a couple things with no luck.我尝试了几件事没有运气。 Any help would be greatly appreciated.任何帮助将不胜感激。
public class demo {
public static void main (String [] args) {
}
}
Just put inside of the main method放在main方法里面
PhysicalNewspaperSubscription subscription= new PhysicalNewspaperSubscription()
and then call your method然后调用你的方法
subscription.address()
in the main method as well.在主要方法中也是如此。
Simply put:简单的说:
public class demo {
public static void main (String [] args) {
PhysicalNewspaperSubscription pns = new PhysicalNewspaperSubscription();
pns.address();
}
}
... but your code will not do anything. ...但你的代码不会做任何事情。
The reason being because though you have a Scanner
to read in something from the console, it'll never run that piece of code because the following loop structure never runs:原因是虽然你有一个Scanner
可以从控制台读取某些内容,但它永远不会运行那段代码,因为以下循环结构永远不会运行:
for (i = 0; i < subAddress.length(); i++) {
...
}
The reason it does not run is because when you declare subAddress
you set it to an empty String
( String subAddress = " ";
), so when the loop checks the condition ( i < subAddress.length()
) it'll evaluate FALSE
, because 0 < 0 is FALSE
and hence not run the loop.它不运行的原因是因为当您声明subAddress
时将其设置为空String
( String subAddress = " ";
),因此当循环检查条件( i < subAddress.length()
)时,它将评估FALSE
,因为 0 < 0 是FALSE
,因此不运行循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.