Java学习(五)—— 编写程序

本文是Java学习系列的第五篇,主要内容包括编程实践、知识点整理,如for循环、数据类型转换、ArrayList操作和布尔表达式的使用。通过示例介绍了如何使用ArrayList,并对比了ArrayList与数组的区别。同时,强调了Java API的使用,如System.out.println和Math.random()等。
摘要由CSDN通过智能技术生成

系列文章目录

一:上手
二:类和对象
三:primitive主数据类型和引用
四:方法操作实例变量
五:编写程序



前言

行百里者半九十


1、编程实践

从无到有去编写一个Game程序,是一个不小的工程,当然也会学到许多新的方法,比如产生随机数,将String类型转换成Int类型,还有一个重要的对象ArrayList等等

在这里插入图片描述
上面就是游戏的说明,然后让我们一步步开始吧

实现程序如下:

import java.util.*;
import java.io.*;

public class DotComBust  {
	
	//声明并初始化变量
	private GameHelper helper = new GameHelper();
	private ArrayList<DotCom> dotComList = new ArrayList<DotCom>();
	private int numOfGuesses = 0;
	

	private void setUpGame() {
		//创建3个DotCom对象并指派名称、置入ArrayList
		DotCom one = new DotCom();
		one.setName("Pets.com");
		DotCom two = new DotCom();
		two.setName("eToys.com");
		DotCom three = new DotCom();
		three.setName("Go2.com");
		dotComList.add(one);
		dotComList.add(two);
		dotComList.add(three);
		
		//列出简单提示
		System.out.println("Your goal is to sink three dot coms.");
		System.out.println("Pets.com, eToys.com, Go2.com");
		System.out.println("Comn on");
		
		for (DotCom dotComToSet : dotComList) {//对list中的每个DotCom都重复一次
			ArrayList<String> newLocation = helper.placeDotCom(3);//要求DotCom的位置
			dotComToSet.setLocationCells(newLocation);//调用DotCom的setter方法来指派刚取得的位置
		}//close for loop
	}//close setUpGame method
	
	private void startPlaying() {
		while(!dotComList.isEmpty()) {//判断DotCom的list是否为空
			String userGuess = helper.getUserInput("Enter your guess");//取得玩家输入
			checkUserGuess(userGuess);//调用checkUserGuess方法
		}
		finishGame();//调用finishGame方法
	}
	
	private void checkUserGuess(String userGuess) {
		numOfGuesses++;//递增玩家猜测次数的计数
		String result = "miss";//先假设没有命中
		
		for (DotCom dotComToTest : dotComList) {//对list中的每个DotCom都重复一次
			result = dotComToTest.checkUserGuess(userGuess);//要求DotCom检查是否命中或击沉
			if (result.equals("hit")) {
				break;
			}
			if (result.equals("kill")) {
				dotComList.remove(dotComToTest);
				break;
			}
		}
		System.out.println(result);//列出结果
	}
	
	private void finishGame() {
		//列出玩家成绩
		System.out.println("All Dot Coms are dead! Your stock is now worthless.");
		if (numOfGuesses <= 18) {
			System.out.println("It only took you " + numOfGuesses + "guesses.");
		} else {
			System.out.println("Took you loog enough");
		}
	}
	
	public static void main(String[] args) {
		DotComBust game = new DotComBust();//创建游戏对象
		game.setUpGame();//要求游戏对象启动
		game.startPlaying();//要求游戏对象启动游戏的主要循环
	}
}


class GameHelper{
	private static final String alphabet="abcdefg";
	private int gridLength=7;
	private int gridSize=49;
	private int [] grid =new int[gridSize];
	private int comCount=0;
	
	public String getUserInput(String prompt) {
		String inputLine=null;
		System.out.print(prompt+" ");
		try {
			BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
			//java.io里面的类:BufferedReader(readLine是其里面的方法)和InputStreamReader
			inputLine=is.readLine();
			if(inputLine.length()==0)
				return null;
		}catch (IOException e) {
			System.out.println("IOException:"+e);
		}
		return inputLine.toLowerCase();//变成小写字母
	}
	
	public ArrayList<String> placeDotCom(int comSize){
		ArrayList<String> alphaCells=new ArrayList<String>();
		@SuppressWarnings("unused")
		String [] alphacoords=new String[comSize];
		String temp=null;
		int [] coords =new int [comSize];
		int attempts=0;
		boolean success=false;
		int location=0;
		
		comCount++;
		int incr=1;
		if((comCount%2)==1) {
			incr=gridLength;
		}
		
		while(!success&attempts++<200) {
			location =(int)(Math.random()*gridSize);//随机起点
			int x=0;
			success=true;
			while(success&&x<comSize) {
				if(grid[location]==0) {
					coords[x++]=location;
					location+=incr;
					if(location>=gridSize) {
						success=false;
					}
					if(x>0&&(location%gridLength==0)) {//超出右边缘,失败
						success=false;
					}
				}else {//找到已经使用的位置,失败
					success=false;
				}
			}
		}//while结束
		
		int x=0;
		int row=0;
		int column=0;
		
		while (x<comSize) {
			grid[coords[x]]=1;
			row=(int)(coords[x]/gridLength);//得到行的值
			column=coords[x]%gridLength;//得到列的值
			temp=String.valueOf(alphabet.charAt(column));//转换成字符串
			
			alphaCells.add(temp.concat(Integer.toString(row)));
			x++;
		}
		return alphaCells;
	}
}


class DotCom {
	
	private ArrayList<String> locationCells;
	private String name;
	
	public void setLocationCells(ArrayList<String> loc) {
		locationCells = loc;
	}
	
	public void setName(String n) {
		name = n;
	}
	
	public String checkUserGuess(String userInput) {
		String result = "miss";
		int index = locationCells.indexOf(userInput);
		if (index > 0) {
			locationCells.remove(index);
			
			if (locationCells.isEmpty()) {
				result = "kill";
				System.out.println("Ouch! You sunk " + name );
			} else {
				result = "hit";
			}
		}
		
		return result;
	}
}

2、知识点整理

2.1关于for循环

for (int i=0;i<100;i++){}
这是基本的for循环,包括初始化、boolean测试、重复表达式后面的执行体四个部分。

for (String name : nameArray){}
这是加强版的for循环,包括声明了类型的变量、要被逐个运行的集合以及执行体三个部分,它能够很容易的逐个运行数组或其他集合(collection)的元素。

2.2转换primitive主数据类型

比如将String转换成int类型,Java提供了下面这样的方法
Integer.parseInt("3")
也可以通过下面这样的方法将int转换成String
String x = String.valueOf(3);

2.3ArrayList操作

ArrayList和数组list都是一个对象,但ArrayList的方法要多许多,而list只有一个.length方法。

函数操作
add(Object elem)向list中加入对象参数
remove(int index)在索引参数中移除对象
remove(Object elem)移除该对象
contains(Object elem)如果对象和参数匹配,则返回true
isEmpty()如果对象中没有元素则返回true
indexOf(Object elem)返回对象参数的索引或-1
size()返回list中元素的个数
get(int index)返回当前索引参数的对象

一些方法的示例代码如下:

import java.util.ArrayList;

ArrayList<String> mylist = new ArrayList<String>();
String a = new String("aaa");
mylist.add(a);
		
String b = new String("bbb");
mylist.add(b);
		
int theSize = mylist.size();
System.out.println(theSize);

Object o = mylist.get(1);

mylist.remove(1);

boolean res = mylist.contains(b);
System.out.println(res);		

创建ArratList时不需要指定大小,只需要创建出此类型的对象即可,它可以在加入或删除元素时自动调整大小。
使用数组实现上面操作,你会看到哪里有不一样:

String[] mylist = new String(2);

String a = new String("aaa");
mylist[0] = a;

String b = new String("bbb");
mylist[1] = b;

int theSize = mylist.length;

String o = mylist[1];

mylist[1] = null;

boolean isIn = false;
for (String item : mylist) {
	if (b.equals(item)){
		isIn = true;
		break;
	}
}

使用数组时的list.[1]操作称为特殊语法,这样的语法只能用在数组上。虽说数组也是对象,但它有自己的规则,你无法调用它的方法,最多通过length存取它的实例变量。

2.4布尔类型表达式

“与”和“或”的运算符(&&, ||)
不等于(!=)

2.5 Java的API

实际上,我们在编写的程序中,常用的一些语句比如System.out.println和Math.random()等都是来自Java的lang这个包,只不过java.lang是被预先引用的,是一个基础包,因此不需要我们自己引用。
但是像ArrayList这样,我们就必须在类的声明前进行引用:

import java,util.*;
import java.util.ArrayList;

class myClass{
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值