我正在编写这个用户进行数学测试的程序。我现在面临并一直在努力解决的问题是如何在测试结束时显示最终得分。
我有一个计数器,每个正确答案的分数会增加,但我如何(最后)显示最终/总分?任何帮助表示赞赏。
这是btw的三个班级之一。
import java.util.Scanner;
public class Questions {
Scanner scan = new Scanner(System.in);
int answer = 0;
int point = 0;
String correct = "Correct";
public void pointers(){
point++;
System.out.println(point + " point added to total score");
}
public void totalPoints(){
pointers();
}
public void showQuestions(){
System.out.println("\n--------------\nQuestion #1: 1+1 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println(correct);
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #2: 340-23 = ? ");
answer = scan.nextInt();
if(answer == 317){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #3: 900/3 = ? ");
answer = scan.nextInt();
if(answer == 300){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #4: 23*2 = ? ");
answer = scan.nextInt();
if(answer == 46){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #5: -4+6 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
}
}
答案 0 :(得分:1)
问题在于你是先尝试获取输入,然后再询问年龄。键入keyboard.nextInt()时,它会立即输入。问题出在这里:
*int age = keyboard.nextInt();
* System.out.println("Age: " + age);
*age = keyboard.nextInt();
我的建议是删除第一个keyboard.nextInt(): 例: System.out.println(“\ nName:”+ name); name = keyboard.nextLine();
System.out.println("Age: " + age);
final int age = keyboard.nextInt();
就是这样。请小心放置方法调用的位置,例如它们应该在你的println()之后。
答案 1 :(得分:0)
不知道你想要实现什么,但
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
System.out.println("Hello, it is time to take a math test.\nFirst we need you to enter some information about yourself.");
System.out.print("\nEnter name: ");
final String name = keyboard.nextLine();
System.out.print("Enter Age: ");
final int age = keyboard.nextInt();
keyboard.close();
System.out.println("Your personal information: " + name + " of " + age + " years old.");
}
}
输出:
C:\Temp\123431>java -classpath .;Main.class Main
Hello, it is time to take a math test.
First we need you to enter some information about yourself.
Enter name: ttt
Enter Age: 321
Your personal information: ttt of 321 years old.
C:\Temp\123431>java -classpath .;Main.class Main