ログインしてさらにmixiを楽しもう

コメントを投稿して情報交換!
更新通知を受け取って、最新情報をゲット!

Javaの課題丸投げコミュのトークナイザー

  • mixiチェック
  • このエントリーをはてなブックマークに追加
質問です。
トークナイザーを使うときに、white space以外(","で区切ろうとしてます)で
それぞれのトークンに区切るとき、どのようにしたらいいのでしょうか?

コメント(15)

String str = "hoge.jpg";//解析したい文字列
StringTokenizer tokenizer = new StringTokenizer(str,".");

と、コンストラクタの2番目の引数に区切りたい文字でできた文字列をあげれば大丈夫です。そういうことを調べる時には

http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/index.html?overview-summary.html

のページの右上からドキュメントをダウンロードし、

API と 言語仕様に関するドキュメント
Java 2 プラットフォーム API 仕様

のページを開いて

StringTokenizerのクラスについて調べると良いです。
質問の方法がクリアでなかったようです。
一応、教科書のやり方はわかるのですが、

token token2,0.99,123,a
java java2,1.99,234,b
mixi mixi2,2.99,345,c

のように、トークンを","のみで区切れるようにして、
アーレイを使って個別に情報を引き出したいのですが
どうしたらいいですか?
(というように質問を変えさせてください。。)

前に、上記の方法で試したのですが、
Null Pointer Exception
というアウトプットが出てくるのです。
サンプルで書いていただいた例、どのような入力に対してどのような出力を得たいのかわかりません。

区切り文字の変更については1.のコメントの通りです。

配列を用いて・・・以下の下りの意味がわかりません。

NullPointerExceptionについては発生状況が分からないのでアドバイスできません。
1.String#indexOfで空白位置を検出、String#substringで空白以降を切り出し、StringTokenizerに渡す。区切り文字は","

2.String#splitを使う。正規表現で区切り文字を指定する。
みなさん、見てくださっただけでもありがとうございます。

>Ray

token token2,0.99,123,a
java java2,1.99,234,b
mixi mixi2,2.99,345,c

というようなものを
token token2
java java2
mixi mixi2
というような感じのテキストファイルにしたいのです。
NullPointerException
に関しては、説明しきれないので、ファイルを明日辺りに
そのものをのせようと思います。
もしよろしければ、アドバイスお願いします。

>なかのさん
なるほど!試してみます!!

>クニさん
すいません。。プログラミングのクラスをとってまだ3ヶ月
って言うのと、教科書が英語なので、日本語でなんというのか
わからないのです。(個人のHPとかだと併用してたりもするようなので)
読みづらくてすいません。。
APIドキュメントはこれでも読んでいるんです。。。
StringTokenizer使わないとダメなのかな?
書いてあることだったらこれで十分っぽいけど

String str = "token token2,0.99,123,a";// 解析したい文字列
String[] strs = str.split(",");
I tried to use array(or vector) to put each information that I read from certain textfile, in this case the file is named "items_Mon.txt," via BufferedReader. I actually could read the file itself, however, I am unable to put the information into small potion by array. If you have any suggestions, I will be happy.


Assignment Scenario
You work for a small grocer, who knows you have been taking computer programming courses. The owner would like to take more control over the store’s inventory and ordering process and has asked you to write a program to help with some tasks:
1) Current Inventory Report – shows all items, cost, price, and quantity on-hand
2) Customer Price List – shows all items and their retail prices
3) Re-order report – what he needs to place on the next order
The owner goes around the store and makes a hand-written list of currently inventory every day. The file is typed it in to a computer as a text file, and emailed to you for processing. There are sometimes mistakes in the file (duplicate entries and incomplete entries).
Requirements
Your program should read the file, and note any errors. It may stop if there are incomplete entries, but should post an error message for the invalid line. If a duplicate entry is found (matching description and each fields), post an error message, do not add the duplicate entry, and continue to process the file. Generate the three reports to the console, per the examples.
Add the three (incomplete) java source files and copy the three ‘items_Day’ files provided to your project from the csdata/CMPSC22/Fall06/Final folder:
1) GroceryList.java - “Driver” with main method
2) Item.java - Class to represent a single grocery item
3) ItemLinkedList.java - Class to implement a linked list of Items


Example Output for Monday List:

Enter the name of the store:
Don's Mighty Mart
Enter items file name:
items_Mon.txt
Adding new item 1: Green Beans
Adding new item 2: Kernel Corn
Adding new item 3: Farm Fresh Eggs
Adding new item 4: Whole Milk
Adding new item 5: Skim Milk
Adding new item 6: Organic Milk
Adding new item 7: Wheat Bread
Adding new item 8: White Bread
Adding new item 9: Swiss Cheese
Adding new item 10: Sharp Cheddar Cheese
Adding new item 11: Mild Cheddar Cheese
Adding new item 12: Sliced Ham
Adding new item 13: Lean Ground Beef
Adding new item 14: Ground Beef
Adding new item 15: Tortilla Chips
Adding new item 16: Potato Chips
Adding new item 17: Butter
Adding new item 18: Peanut Butter
Adding new item 19: Berry Jelly
Adding new item 20: Grape Jelly
Adding new item 21: Romaine Lettuce
Adding new item 22: Iceberg Lettuce
Adding new item 23: Carrots
Adding new item 24: Onions
Adding new item 25: Potatoes


Don's Mighty Mart Item and inventory report:
Green Beans (can), Price $0.99, Cost $0.55, Quantity: 22
Kernel Corn (can), Price $0.99, Cost $0.53, Quantity: 28
Farm Fresh Eggs (dozen), Price $2.99, Cost $1.55, Quantity: 34
Whole Milk (gallon), Price $3.59, Cost $2.67, Quantity: 12
Skim Milk (gallon), Price $3.49, Cost $2.47, Quantity: 16
Organic Milk (gallon), Price $3.99, Cost $3.17, Quantity: 4
Wheat Bread (loaf), Price $2.99, Cost $1.22, Quantity: 17
White Bread (loaf), Price $2.19, Cost $1.12, Quantity: 27
Swiss Cheese (pound), Price $4.19, Cost $3.22, Quantity: 5
Sharp Cheddar Cheese (pound), Price $4.99, Cost $3.79, Quantity: 18
Mild Cheddar Cheese (pound), Price $4.59, Cost $3.39, Quantity: 8
Sliced Ham (pound), Price $3.29, Cost $2.22, Quantity: 4
Lean Ground Beef (pound), Price $3.29, Cost $2.22, Quantity: 23
Ground Beef (pound), Price $2.99, Cost $2.02, Quantity: 29
Tortilla Chips (bag), Price $3.29, Cost $1.88, Quantity: 87
Potato Chips (bag), Price $3.59, Cost $1.78, Quantity: 32
Butter (pound), Price $4.99, Cost $3.76, Quantity: 18
Peanut Butter (jar), Price $2.99, Cost $1.71, Quantity: 6
Berry Jelly (jar), Price $2.29, Cost $1.44, Quantity: 7
Grape Jelly (jar), Price $2.29, Cost $1.47, Quantity: 11
Romaine Lettuce (head), Price $1.49, Cost $0.78, Quantity: 14
Iceberg Lettuce (head), Price $1.69, Cost $0.98, Quantity: 26
Carrots (bunch), Price $1.59, Cost $0.88, Quantity: 12
Onions (bag), Price $1.99, Cost $1.23, Quantity: 16
Potatoes (bag), Price $2.49, Cost $1.66, Quantity: 22


Don's Mighty Mart Customer Price List:
Green Beans (can) Price: $0.99
Kernel Corn (can) Price: $0.99
Farm Fresh Eggs (dozen) Price: $2.99
Whole Milk (gallon) Price: $3.59
Skim Milk (gallon) Price: $3.49
Organic Milk (gallon) Price: $3.99
Wheat Bread (loaf) Price: $2.99
White Bread (loaf) Price: $2.19
Swiss Cheese (pound) Price: $4.19
Sharp Cheddar Cheese (pound) Price: $4.99
Mild Cheddar Cheese (pound) Price: $4.59
Sliced Ham (pound) Price: $3.29
Lean Ground Beef (pound) Price: $3.29
Ground Beef (pound) Price: $2.99
Tortilla Chips (bag) Price: $3.29
Potato Chips (bag) Price: $3.59
Butter (pound) Price: $4.99
Peanut Butter (jar) Price: $2.99
Berry Jelly (jar) Price: $2.29
Grape Jelly (jar) Price: $2.29
Romaine Lettuce (head) Price: $1.49
Iceberg Lettuce (head) Price: $1.69
Carrots (bunch) Price: $1.59
Onions (bag) Price: $1.99
Potatoes (bag) Price: $2.49


Don's Mighty Mart Re-Order report
Organic Milk - Order Qty: 16) Cost: $50.72
Swiss Cheese - Order Qty: 15) Cost: $48.30
Mild Cheddar Cheese - Order Qty: 12) Cost: $40.68
Sliced Ham - Order Qty: 16) Cost: $35.52
Peanut Butter - Order Qty: 14) Cost: $23.94
Berry Jelly - Order Qty: 13) Cost: $18.72
Total Reorder Cost: $217.88
token token2,0.99,123,a
java java2,1.99,234,b
mixi mixi2,2.99,345,c
というようなものを
token token2
java java2
mixi mixi2
にするだけなら、

import java.util.*;

class Token{
public static void main(String[] args){
String str = "token token2,0.99,123,a";
StringTokenizer tokenizer = new StringTokenizer(str,",");
String token = tokenizer.nextToken();
System.out.println(token);
}
}

のような方法で十分だと思います。

NullPointerExceptionについてはソースファイルを載せて頂いてもおそらく読む気にならないので、NullPointerExceptionと一緒にいろいろ書いてあるエラーメッセージだけ載せてください。
これ以上長いのは失礼だと思いまして。
わざわざ、本当に申し訳ありません。。
親切心、痛み入ります。
ちなみに、トークナイザーの部分をコメントにして
読み込むと、元のテキストファイル自体は正常に
アウトプットできます。

NullPointerException:
at java.util.StringTokenizer.<init>(Unknown Source)
at java.util.StringTokenizer.<init>(Unknown Source)
at GroceryList.main(GroceryList.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
>

重要な部分だけくりぬいて見ました。
元のソースとは若干異なりますが、問題点は同じです。

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

public class GroceryList
{
public static void main(String args[])
{
System.out.println("Enter items file name:");
String fileName;
Scanner keyboard = new Scanner(System.in);
fileName = "items_Mon.txt";//keyboard.nextLine();
String temp = null;
try
{
BufferedReader inputStream =
new BufferedReader(new FileReader(fileName));
StringTokenizer wordFinder = new StringTokenizer(temp,",");
int itemNum = 25;// number of items
int itemDesc = 5;// number of items categories
String[][] item = new String[itemNum][itemDesc];
String token;
for (int i = 0; i < itemNum; i++)// read each item line
{
temp = inputStream.readLine();
System.out.println(temp);
wordFinder = new StringTokenizer(temp);
//for (int j =0; j < 5; j++)
//{
//token = wordFinder.nextToken();




//}
}
inputStream.close( );
}
catch(FileNotFoundException e)
{
System.out.println("File " + fileName + " not found.");
}
catch(IOException e)
{
System.out.println("Error reading from file " + fileName);
}
}
}

items_Mon.txt(これが読み込むファイルです。)

Green Beans,can,0.55,0.99,22
Kernel Corn,can,0.53,0.99,28
Farm Fresh Eggs,dozen,1.55,2.99,34
Whole Milk,gallon,2.67,3.59,12
Skim Milk,gallon,2.47,3.49,16
Organic Milk,gallon,3.17,3.99,4
Wheat Bread,loaf,1.22,2.99,17
White Bread,loaf,1.12,2.19,27
Swiss Cheese,pound,3.22,4.19,5
Sharp Cheddar Cheese,pound,3.79,4.99,18
Mild Cheddar Cheese,pound,3.39,4.59,8
Sliced Ham,pound,2.22,3.29,4
Lean Ground Beef,pound,2.22,3.29,23
Ground Beef,pound,2.02,2.99,29
Tortilla Chips,bag,1.88,3.29,87
Potato Chips,bag,1.78,3.59,32
Butter,pound,3.76,4.99,18
Peanut Butter,jar,1.71,2.99,6
Berry Jelly,jar,1.44,2.29,7
Grape Jelly,jar,1.47,2.29,11
Romaine Lettuce,head,0.78,1.49,14
Iceberg Lettuce,head,0.98,1.69,26
Carrots,bunch,0.88,1.59,12
Onions,bag,1.23,1.99,16
Potatoes,bag,1.66,2.49,22
今携帯からなので不確かですが、wordFinderに代入するStringTokenizerのコンストラクタが区切り文字無しのものになっているからじゃないでしょうか。
今帰宅してチェックしました。12.のコメントで指摘した部分以前にExceptionが出ています。間違っている個所はエラーの通りです。

18行目の
StringTokenizer wordFinder = new StringTokenizer(temp,",");
ですが、temp = null; のあとtempに値が入っていないのでNullPointerExceptionが出ています。18行目でコンストラクタを呼ばず、27行目のコンストラクタを18行目に書いてあるものと同じにすれば期待通りの動きをするのではないかと思います。
できました!!
コンストラクタで二つのクラスに分けてみました。
一応、アウトプットも正しいようです。
本当にご迷惑おかけしました。
ありがとうございます。
原因はご指摘いただいたとおりtempの値の入力が無かった
事かなと思います。
だったのかなぁと思うのですが、弱点・原因の究明は
ほかのクラスが落ち着いてからやってみようかと思います。
以下がうまくいったプログラムです。

import java.util.*;

public class GroceryList
{

public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of your shop");
String shopName = keyboard.nextLine();

Item storeItem = new Item(shopName);

storeItem.showAllAdd();
storeItem.showAllStock();
storeItem.showAllCustomer();
storeItem.showAllReorder();
}
}


//Item class
import java.io.*;
import java.util.*;
import java.text.*;

public class Item
{
private String shopName;
private String fileName;
private int itemNum = 25;
private int itemDesc = 5;
String item[][] = new String[itemNum][itemDesc];
public Item(String newShopName)
{
shopName = newShopName;
System.out.println("Enter items file name:");
Scanner keyboard = new Scanner(System.in);
fileName = keyboard.nextLine();
String temp = null;
try
{
BufferedReader inputStream =
new BufferedReader(new FileReader(fileName));
// number of items categories
String token;

for (int i =0; i < itemNum; i++)
{
temp = inputStream.readLine();
StringTokenizer tokenizer = new StringTokenizer(temp,",");
for (int j = 0; j < 5; j++)
{
token = tokenizer.nextToken();
if (token != null)
item[i][j] = token;
else
item[i][j] = null;
}
}
inputStream.close( );
}
catch(FileNotFoundException e)
{
System.out.println("File " + fileName + " not found.");
}
catch(IOException e)
{
System.out.println("Error reading from file " + fileName);
}
catch(NoSuchElementException e)
{
System.out.println("File: " + fileName + " has critical mistake(s). Please re-enter after correction.");
System.out.println("The part that says null first time must have problem.");
}
}

public void showAllAdd()
{
for (int i = 0; i < itemNum; i++)
System.out.println("Adding new item " + (i + 1) + ": " + item[i][0]);
}

public void showAllStock()
{
System.out.println("\n\n" + shopName + " Item and Inventory report:");
for (int i = 0; i < itemNum; i++)
System.out.println(item[i][0] + " (" + item[i][1] + ") , Price $" + item[i][3] + ", Cost $" + item[i][2] + ", Quantity: " + item[i][4]);
}

public void showAllCustomer()
{
System.out.println("\n\n" + shopName + " Customer price list:");
for (int i = 0; i < itemNum; i++)
System.out.println(item[i][0] + " (" + item[i][1] + ") , Price $" + item[i][3]);
}

public void showAllReorder()
{
DecimalFormat decimal2 = new DecimalFormat("00.00");
double subTotal;
double subTotalDecimal;
double reorderTotal = 0.00;
System.out.println("\n\n" + shopName + " Re-orderList report");
for (int i = 0; i < itemNum; i++)
{
if ((Integer.parseInt(item[i][4])) < 10)
{
subTotal = (20 - (Integer.parseInt(item[i][4])))*(Double.parseDouble(item[i][2]));
System.out.println(item[i][0] + " - Order Qty: " + (20 - (Integer.parseInt(item[i][4]))) + ") Cost: $" + decimal2.format(subTotal));
reorderTotal = reorderTotal + subTotal;
}
}
System.out.println("Total Reorder Cost: $" + decimal2.format(reorderTotal));
}
}

ログインすると、みんなのコメントがもっと見れるよ

mixiユーザー
ログインしてコメントしよう!

Javaの課題丸投げ 更新情報

Javaの課題丸投げのメンバーはこんなコミュニティにも参加しています

星印の数は、共通して参加しているメンバーが多いほど増えます。