Home > Java > Java Tutorial > body text

How to input a number in a loop in java?

little bottle
Release: 2019-05-25 12:00:13
Original
7794 people have browsed it

Java is an object-oriented programming language. It contains many class libraries. When we are coding, we can achieve the desired functions by calling methods in the class libraries. In this article, I will tell you how to implement loop input in Java.

How to input a number in a loop in java?

To implement loop input, we need to call the Scanner class.

Let’s introduce the Scanner class!

Scanner is a text scanner based on regular expressions. We can obtain user input through the Scanner class.

The Scanner class provides multiple constructors. Different constructors can accept files, input streams, and strings as data sources and are used to parse data from files and input stream strings.

If you want to implement loop input, you must use the for function.

The following code is to loop to input the students’ five scores and find the average score:

import java.util.Scanner;

public class test4 {
public static void main(String[] args){

Scanner in=new Scanner(System.in);    //定义输入
double sum=0;
for(int i=1;i<=5;i++){        //循环输入成绩
System.out.print("请输入小明第"+(i)+"门成绩:");
int  score=in.nextInt();        //进行输入成绩
sum=sum+score;
}

System.out.println("平均成绩为:"+sum/5);    //输出平均成绩

}
}
Copy after login

The above is the detailed content of How to input a number in a loop in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!