Home >Java >javaTutorial >How to input a number in a loop in java?
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.
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); //输出平均成绩 } }
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!