JAVA学习脚印3: java语言控制流程

来源:互联网 发布:怎么编程shell 编辑:程序博客网 时间:2024/06/06 10:01

JAVA学习脚印3: java语言控制流程

本节首先介绍,java语言中的字符串处理以及输入输出控制,最后介绍控制流程。

 

在讲述控制流程之前,先介绍以下java中字符串和输入输出的内容,以便后续练习编写控制流程程序时做准备。


1.字符串处理

 

java中的字符串就是uncoded字符序列。java标准库提供了String类来处理字符串。

1)构建字符串

第一种方式就是使用双引号把字符串括起来,例如"hello"就是一个字符串String类的一个实例:String greeting = "hello";

第二种方式是使用字符串构建器StringBuilder类提供的方法。有些时候需要由较短的字符串构建字符串,这个时候使用字符串连接符号+(见下面字符串拼接部分)的效率比较低,因此可以使用StringBuilder类来避免该问题,例如:

StringBuilder builder = new StringBuilder();

builder.append("hello");

builder.append(",world!");

String hello = builder.toString();

System.out.println(hello);// print hello,world!

2)字符串拼接

java语言使用+来实现字符串的拼接,例如"hello"+",world!",将形成"hello,world!"。

注意,当将一个字符串与一个非字符串的值进行拼接时,后者将自动调用其toString()方法转换为字符串并与前者拼接在一起,例如:

"your age is "+age;//Ok

3)字符串取子串

使用sustring方法,例如 hello=hello.substring(0,3)+'p';// hello = "help"

4)字符串比较

使用equals方法检测两个字符串是否相等,一定不能使用 == 运算符检测两个字符串是否相等,== 运算符只能够确定两个字符串是否放置在同一个位置上。

我们查看String类equals方法源码:

public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String) {            String anotherString = (String) anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                            return false;                    i++;                }                return true;            }        }        return false;    }

就明白了equals方法将首先查看是否引用同一个对象,若是则肯定两个字符串对象相等;否则逐个字符的比较两个对象,直到判断出结果。

String a = "hello";String b = "hello";String c = "help";System.out.println((a == b));// pirnt trueSystem.out.println( ("hel" == c.substring(0,3)) );//print falseSystem.out.println((a.equals(b)));//print trueSystem.out.println((a.equals(c)));//print false

实际上虚拟机中字符串常量是共享的,所以a==b 为true;但是+或者substring等操作产生的结果并不是共享的,因此"hel" == c.substring(0,3)) 为false。

因此不要使用 == 运算符检测字符串是否相等,而要使用使用equals方法。

2.输入输出

 

1)标准输入输出流(控制台窗口)

输入:

首先构造一个Scanner对象来关联System.in,接受输入:

Scanner in = new Scanner(System.in);

String name = in.nextLine();//输入姓名

int age = in.nextInt();// 输入年龄

另外从控制台读取密码时一般会回显出来,因此系统提供了Console类提供密码输入:

Console cons;String username;char[] passwd;if ((cons = System.console()) != null) {username = cons.readLine("User name:");passwd = cons.readPassword("Password:");//do some jobArrays.fill(passwd, ' ');//迅速填充密码域 避免信息泄漏}

输出:

输出基本上时之前经常用过的了,如System.out.print。要想格式化输出,java提供了和C语言一样的System.out.printf函数来控制输出格式。当然也可以使用静态的String.format方法创建一个格式化的字符串用于输出,例如:

System.out.printf("%.8f", Math.PI);// print 3.14159265

 

2)文件的输入输出

输入:

同样可以利用Scanner来读入文件,例如:

Scanner in = new Scanner(new File("1.txt"));

String line = in.nextLine();

输出:

可以利用PrintWriter来写入文件,例如:

PrintWriter out = new PrintWriter(new File("2.txt"));

out.println(line);

注意Scanner和PrintWriter构造函数均需要File对象,File对象表达的是抽象路径名,它根据路径字符串生成。

下面综合标准输入输出流以及文件读写流,编写一个从控制台读入文件名,然后读取文件内容,并将文件行数写入文件及控制台的程序。代码如下例3-1所示:

3-1  InputAndOutput.java

package com.learningjava;import java.io.*;import java.util.Scanner;/** * a program to statistic file line count * @version 1.1 2013-08-06 * @author wangdq */public class InputAndOutput {public static void main(String[] args) { try { //read file name form standard inputScanner in = new Scanner(System.in);//constuct a new scanner to read fileSystem.out.println("input the filename for reading content:");Scanner filein = new Scanner(new File(in.nextLine ()));//construc a new writer to write fileSystem.out.println("input the filename for storing result:");PrintWriter out = new PrintWriter(new File(in.nextLine()));//read lines from fileint lineCnt = 0;while(filein.hasNextLine()) {filein.nextLine();lineCnt++;}//store the lineCnt to the fileout.println("there has :"+lineCnt+" in the file.");//print the lineCnt to the standard outputSystem.out.println(lineCnt);//close the streamin.close();filein.close();out.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

程序运行效果:

wangdq@wangdq:~/workspace/InputAndOutput/bin$ java com.learningjava.InputAndOutput

input the filename for reading content:

../src/com/learningjava/InputAndOutput.java

input the filename for storing result:

../cnt.txt

45

wangdq@wangdq:~/workspace/InputAndOutput/bin$ cat ../cnt.txt

there has :45 in the file.

程序读取InputAndOutput.java文件,计算出公有45行,并将结果写到cnt.txt文件中,显示在控制台上。linux 下可通过 cat filename|wc -l 命令或者利用vim编辑器查看文件行数,以验证程序的正确性。

3.流程控制

 

java中流程控制与c++中基本上相同,但也有区别。java中分支结构可以由if、或者if...else语句控制 ,多重选择由switch语句实现;循环结构一共有三种即while、do...while、for循环;中断流程的语句有break和continue语句。

需要注意的是:

1)在java中不允许在嵌套的块中重定义一个变量。例如:

int n = 0;int m = 5;for(int n = 0 ;n< m;n++) {}

将出现错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

Duplicate local variable n

外围的变量n和for循环块中的n属于重复定义。再看一例,语句序列:

int n = 0;int m = 5;if(m > 0){     int n;}

也会引起同样的问题,注意java与c++的区别。

2)java中还新增了一种更好的循环结构,这种增强的循环结构语句格式如下:

for(variable: collection) statement 

例如输出数组的内容可以如下:

String[] words = {"apple","banana","orange","grape"};for(String item:words) {System.out.println(item);}

可以将这种循环称之为for each循环,它使代码更加简洁。



至此,熟悉了java语言中的字符串,输入输出以及控制流。

0 0
原创粉丝点击