我正在制作一個程式,它會重復一個單詞的長度,例如,如果我要寫“Hello”,它會重復 5 次。但是,當我寫它時,我不斷收到一個錯誤訊息
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method nextLine() is undefined for the type WordLoop
inputString cannot be resolved
at WordLoop.main(WordLoop.java:11)
而且由于我對 Java 的了解不夠深入,我的臉面目全非。因此,任何幫助將不勝感激。
代碼:
import java.util.*;
class WordLoop
{
public static void main (String[] args )
{
int times;
//String string = new String();
Scanner scan = new Scanner(System.in);
System.out.println("Enter word: "); // Asks for the word
String string = nextLine();
while (string = inputString.length()) // loop until the end
{
System.out.println(string);
}
System.out.println("Done with the loop");
}
}
uj5u.com熱心網友回復:
這可能是您正在尋找的:
import java.util.*;
class WordLoop
{
public static void main (String[] args )
{
//String string = new String();
Scanner scan = new Scanner(System.in);
System.out.print("Enter word: "); // Asks for the word
String string = scan.nextLine();
int count = 1;
while (count <= string.length()) // loop until the end
{
System.out.println(count ": " string);
count ;
}
System.out.println("Done with the loop");
}
}
uj5u.com熱心網友回復:
這里有幾件事。
呼叫 nextLine 方法導致的編譯錯誤,但忘記告訴要在哪個物件上執行此操作。這應該是scan.nextLine()
劇透警報 - 如果您想先自己解決剩下的問題,請停在這里
為了使您的回圈正常作業,您還需要將string變數的長度與某些內容進行比較。如果你times用零初始化你的變數,那么你可以使用它。請記住,每次通過回圈時也要增加它 - 為此您可以使用times .
我的完整建議是這樣的
import java.util.*;
class WordLoop
{
public static void main (String[] args )
{
int times = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter word: "); // Asks for the word
String string = scan.nextLine();
while (times < string.length()) // loop until the end
{
System.out.println(string);
times ;
}
System.out.println("Done with the loop");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/441009.html
標籤:爪哇 细绳 while循环 java.util.scanner
