我的這段時間有沒有問題,或偶爾發生循環,或者我錯過了什麼?經過精細的作品,但在第二首先來看,我得到這樣的:爲什麼我在使用(scanner).nextLine()時一次循環打印2個提示?
Enter course NAME: class name
Enter course HOURS: 4
Enter course GRADE: 4.0
You have entered class: jeff graves, class hours: 4 and, class grade 4.0
Do you want to continue:
y
Enter course NAME: Enter course HOURS:
只是正常使用(scanner).next();
但當時我只能採取從用戶的一個詞,當它滑過它將從nextInt拋出一個錯誤。
public class GetGrades { //open class GetGrades
public static void main(String[] args) {
/**creating new instance of scanner named input to read user input*/
Scanner input = new Scanner(System.in); // create new instance of scanner object
boolean repeat = true; //boolean value for while loop holding array input
String s; // create string to store user input value for exiting loops
/** create 3 arrays to store course name, hours, and grades*/
String[] name = new String[20]; //type string array for class name
int[] hours = new int[20]; // type int array for class hours
float[] grade = new float[20]; //type float array for class grade
outerloop: // set break point for nested for loops exit on user input
while(repeat != false) {// while loop with boolean value to let user exit array input
for (int i=0; i<name.length; i++) { //for loop for name array
System.out.print("Enter course NAME: "); //prompt user for input
name[i] = input.nextLine(); //read next line value and store in array name
System.out.print("Enter course HOURS: "); //prompt user for input
hours[i] = input.nextInt(); //read the next int and store in array hours
System.out.print("Enter course GRADE: "); //prompt user for input
grade[i] = input.nextFloat(); //read the next float value and store in array grade
/**Print line to console summing um what the user has entered*/
System.out.println("You have entered class: " + name[i] + ", class hours: " + hours[i] +
" and, class grade " + grade[i]);
/**prompt user if wanted to enter more grades, break loop on n or N*/
System.out.println("Do you want to continue:");
s = input.next();
if (s.equals("y") || s.equals("Y")) { //open if statement
repeat = true;
} else { //close if and open else
break outerloop;
} //close else statement
}//close for loop with i as count
}//close while
**改爲input.nextLine()現在它只是吹過一切,而不需要一個「你要繼續提示」 ......跳過一路走到最後 – 2015-04-03 04:18:20
在'grade [i] = input.nextFloat();之後添加'input.nextLine()'; '出於同樣的原因 – 2015-04-03 04:21:47
omg我嚇壞了愛你! 4天的折磨現在結束了! – 2015-04-03 08:14:18