java learning experience (a)

By learning this week, mastered the basic grammatical rules of java, which makes me the most profound two things: First, call the console package; the second is process control continue.

  1. Enter the console
    commands dos program reads window data, to some extent, to achieve a "interactive", able to design many convenient procedure, such as the following to calculate the average class student achievement program:
import java.util.Scanner;
public class TestFor1{
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		int i,a , sum = 0;
		System.out.println("请输入班级学生人数:");
		int b = input.nextInt();
		for ( i = 1;i <= b; i++){
			System.out.println("请输入第"+i+"个同学的分数");
			a = input.nextInt();
			if(a < 0 || a > 100){
			System.out.println("请输入0~100内的数值");
			break;
			}
			sum = sum + a;
			}
			if(i == b+1)
		  System.out.println("平均分为:"+sum/b);
		}
	}

First, the program can by calling Scanner.class, reading class size, by determining how many times the number of grades input, the final number is divided by the average value of the class. If you do not call the package, when changes in the number, also need to modify the program.
2. continue statement
execution to continue in the program, it will jump out of this cycle, once, this statement will be of great use to enter next. For example, in the following calculation 1 + 3 + 5 + ...... + 99 in the calculation method.

Conventional thinking is:

public class Work2For{
	public static void main(String[] args){
		int sum = 0;
		for (int i = 1; i <= 99; i += 2){
			sum = sum + i ;
			}
		System.out.println(sum);
		}
	}

However, this method is not flexible enough, here is the program continue to improve the use

public class Work2For{
	public static void main(String[] args){
		int sum = 0;
		for (int i = 1; i <= 99; i ++){
			if( i%2 == 0)
			continue;
			sum = sum + i ;
			}
		System.out.println(sum);
		}
	}

When using an even number continue, skip this for the next cycle, so that a program designed to facilitate subsequent improvements according to different needs.
There are the following piece of code is also very good to show the advantages continue.

String str = input.next();
			switch (str){
			case "剪子": player = 0; break;
			case "石头": player = 1; break;
			case "布": player = 2; break;
			default:System.out.println("请出: “剪子”、 “石头”或“布”");	continue;
			}
			

Program reads characters from dos command window, when dissatisfied input, will pass continue, the end of this cycle, the next cycle be that prompts until you enter the correct date.
By use of continue statement can produce a lot of good results.
In addition to the above two points, for nested statements, the content is more important, the follow-up study of this part of the exercise should also be strengthened

Released two original articles · won praise 1 · views 29

Guess you like

Origin blog.csdn.net/qq_44952731/article/details/104226388