exercise 1-6

【买菜】

package Practice06;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

import lab2.Anagrammar;

public class Grocer {
 String itemName;
 int qty;
 float unitPrice;
 String unit;
 String[] textArray;
 String[] items;
 
 public static void main(String[] args) {
  Grocer grocer = new Grocer();
  grocer.readFile();
  //方法和变量之前都要加对象名
  grocer.generateBills(grocer.items);
 }
 
 public String[] readFile() {
  Scanner fileInput = null;
  StringBuilder fileContent = new StringBuilder();
  try {
   fileInput = new Scanner(new File("Groceries.txt"));
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  while (fileInput.hasNextLine())
   fileContent.append(fileInput.nextLine() + "\n");
  textArray = fileContent.toString().split("\n");
  System.out.println(fileContent);
  System.out.println(Arrays.toString(textArray));
  //assign the textarray to items using this
  this.items = textArray;
  return textArray;
 }
 
 public void generateBills(String[] items) {
  int count = 0;
  //how to assign the variables
  //Item item = new Item();
  System.out.println("#\tItem\t\tQty\tUnit\t\tUnit price\tTotal price"); //for the table-header labels
  for (int i = 0; i < items.length; i++) {
   String temp = items[i];
   String[] info = temp.split(",");
   //remember to trim
   Item item = new Item(info[0], Integer.valueOf(info[1].trim()), Float.valueOf(info[3].trim()),info[2]);
   System.out.printf("%-8d%-16s%-8d%-16s$%-16.2f$%-16.2f%n", ++count, item.itemName, item.qty, item.unit,
   item.price, item.qty*item.price ); //for the table rows
  }
 }
}
View Code

//方法和变量之前都要加对象名

grocer.generateBills(grocer.items);

 

//assign the textarray to items using this

this.items = textArray;

//remember to trim

 

【彩虹】

rainbow.readFile();

//生成了rainbow以后可以直接用

rainbow.calculateVoteCounts();

 

【nextLine()有空格】

即nextLine()方法返回的是Enter键之前的所有字符,长,它是可以得到带空格的字符串的。

posted @ 2018-09-27 09:42  苗妙苗  阅读(121)  评论(0编辑  收藏  举报