java中的计数器,如何在Java程序中创建一个计数器

/*This is a quiz program that will ask the user 10 questions. the user will answer

* these questions and will be scored out of 10.*/

class Quiz {

public static void main(String args[]) {

// Instructions

System.out.println("instructions");

System.out.println(" ");

System.out

.println("1. You wll be asked ten questions through out the quiz.");

System.out

.println("2. The first question will appear, you will have to answer that question for the next question to appear.");

System.out

.println("3. When you answer the last question you will be told your score.");

System.out.println(" ");

System.out.println("welcome to the basketball quiz.");

// question 1

System.out.println(" ");

System.out.println("Question 1. ");

System.out.println("How tall is a basketball hoop? ");

System.out.println("Type in Answer here:");

String Question1 = In.getString();

if (Question1.equalsIgnoreCase("10 Feet")) {

System.out.println("Correct!");

} else {

System.out.println("you got this questions wrong");

}

// question 2

System.out.println(" ");

System.out.println("Question 2. ");

System.out.println("Who invented basketball? ");

System.out.println("Type in Answer here:");

String Question2 = In.getString();

if (Question2.equalsIgnoreCase("James Naismith ")) {

System.out.println("Correct!");

} else {

System.out.println("you got this questions wrong");

}

}

}

This is my program that I am writing. I want to make a counter that will keep score of every question that is answered right and then display it to the user after the questions are finished. I tried using this:

int score=0;

score=score+1;

It doesn't not work for the 2nd question, but works for the 3rd... it gives me an error.

Is there another way I can do this or am I doing something wrong?

解决方案

It looks like you are on the right track. You need to declare a socre variable at the begiunning of the program.

int score = 0;

Then in each question where you print out "correct" you can increment the score like this:

score++;

At the end of the program after the last question you can print the score.

Maybe you should post the error you got when you tried it.

UPDATE:

The syntax is score++ NOT score=++. That is, take out the = sign.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值