编写一个名为wordCount的方法,该方法接受String作为其参数,并返回String中的单词数.单词是一个或多个非空格字符的序列(除''之外的任何字符).例如,调用wordCount("hello")应返回1,调用wordCount("你好吗?")应返回3,调用wordCount("此字符串有宽空格")应返回5,调用wordCount ("")应该返回0.
我做了一个功能:
public static int wordCount(String s){
int counter = 0;
for(int i=0; i<=s.length()-1; i++) {
if(Character.isLetter(s.charAt(i))){
counter++;
for(i<=s.length()-1; i++){
if(s.charAt(i)==' '){
counter++;
}
}
}
}
return counter;
}
Run Code Online (Sandbox Code Playgroud)
但我知道这有一个限制,它也将计算字符串中的所有单词完成之后的空格数nad它还将计算2个空格,因为可能是2个单词:(是否有预定义的单词计数函数?或者这段代码可以纠正吗?
我制作了一个使用线程的程序---
public class ThreadTest{
public static void main(String[] args){
MyThread newthread=new MyThread();
Thread t=new Thread(newthread);
t.start();
for(int x=0;x<10; x++){
System.out.println("Main"+x)
}
}
}
Run Code Online (Sandbox Code Playgroud)
class MyThread implements Runnable{
public void run(){
for(int x=0; x<10; x++){
System.out.println("Thread"+x);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是......为什么我们使用"Thread"类并创建它的对象并在其构造函数中传递"MyThread"调用?我们不能通过创建它的对象并调用run方法来调用"MyThread"对象的run方法吗?
(即 MyThread newthread=new MyThread(); and then newthread.run(); )
创建胎面对象并在其中传递MyThread类的原因是什么?
我创建了2个源代码文件,Shirt.java和ShirtTestArray.java
我面临的问题是,每当我尝试访问displayShirtInformation()方法时,我都无法做到这一点..并获得错误类,接口或枚举预期
下面给出了两个源文件 -
Shirt.java--
public class Shirt {
public int shirtID = 0; // Default ID for the shirt
public String description = "-description required-"; // default
// The color codes are R=Red, B=Blue, G=Green, U=Unset
public char colorCode = 'U';
public double price = 0.0; // Default price for all shirts
public int quantityInStock = 0; // Default quantity for all shirts
public Shirt() {
}
public Shirt(int ID, String d, char c, double …Run Code Online (Sandbox Code Playgroud) 我写了这个类(打印数组列表),在其中我在main函数中创建了一个方法.
好吧它不起作用:我做了函数static并在main方法中声明了它,但它仍然没有用.在main方法中,我创建了没有访问说明符的函数:它仍然不起作用.
你不能在方法中声明一个main方法吗?
有没有办法在main方法中声明一个方法(除了在main方法之外使它成为公共静态)?
public class TestArrays {
public static void main(String[] args) {
// Step 1 & 2: declare/initialize array variables
int[] array1 = { 2, 3, 5, 7, 11, 13, 17, 19 };
int[] array2;
// Step 3: display array1 with initial values
System.out.print("array1 is ");
printArray(array1);
System.out.println();
// Step 4: make array2 refer to array1
array2 = array1;
// modify array2
array2[0] = 0;
array2[2] = 2;
array2[4] = …Run Code Online (Sandbox Code Playgroud) java ×4