/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.util.Scanner;
/**
*
* @author Donovan
*/
public class Controller {
public Controller() {
sentenceArray();
}
private void sentenceArray() {
int size = 0;
String word = "";
int i = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many words would you like to enter?");
size = input.nextInt();
String [] sentence = new String[size];
System.out.println("please enter a word.");
word = input.next();
while( i < size){
if( i < size){
sentence[i] = word;
i++;
System.out.println("Please enter a word.");
word = input.next();
}//end if
}//end while
displayArray(sentence);
} // end sentence array
public static void displayArray(String []sentence){
System.out.print( "Your sentence is: " );
for (String x : sentence){
System.out.print( x + "\t" );
}
}//end displayResults
}//end controller
答案 0 :(得分:0)
问题是你在i >= size
之后要求输入。
具体来说,这些行
i++;
System.out.println("Please enter a word.");
word = input.next();
这不是C,所以你可以在方法调用中声明变量。
public void sentenceArray() {
Scanner input = new Scanner(System.in);
System.out.println("How many words would you like to enter?");
int size = input.nextInt();
String[] sentence = new String[size];
int i = 0;
while (i < size) {
System.out.println("please enter a word.");
String word = input.next();
sentence[i] = word;
i++;
}
displayArray(sentence);
}
答案 1 :(得分:0)
do while
循环我会使用一个do while
循环来测试循环体之后的条件,你不需要一个与你的循环一致的if
,你也不需要临时的{{ 1}}。像,
String
最后,我想您在private void sentenceArray() {
Scanner input = new Scanner(System.in);
System.out.println("How many words would you like to enter?");
int size = input.nextInt();
String[] sentence = new String[size];
int i = 0;
do {
System.out.println("Please enter a word.");
sentence[i] = input.next();
i++;
} while (i < size);
displayArray(sentence);
}
的循环后想要println()
。像,
displayArray
答案 2 :(得分:0)
我的理解是你要求多余的“请输入一个字”?如果是,请删除上面的这些行:
System.out.println("please enter a word.");
word = input.next();
请在此处查看完整代码:
public class Controller {
public Controller() {
sentenceArray();
}
private void sentenceArray() {
int size = 0;
int i = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many words would you like to enter?");
size = input.nextInt();
String [] sentence = new String[size];
while( i < size){
System.out.println("Please enter a word.");
sentence[i] = input.next();
i++;
//end if
}//end while
displayArray(sentence);
} // end sentence array
public static void displayArray(String []sentence){
if(sentence.length > 0) {
System.out.print( "Your sentence is: " );
for (String x : sentence){
System.out.print( x + "\t" );
}
}
}//end displayResults
public static void main(String[] args) {
Controller controller = new Controller();
}
}//end controller
希望得到这个帮助。