I am using bufferedreader to capture the text in a CSV file and a Scanner to assign it to a variable so I can save it to an array later, the file has three values, a number, a name, and a "price" but when I read the "price" it captures the "price" \n number which throws off everything, how do I stop reading \n without using ".nextLine" The code looks like this
try {
File file = new File("...\\file.csv");
FileReader printReader = new FileReader(file);
BufferedReader BuffReader = new BufferedReader(printReader);
Scanner Writer = new Scanner(BuffReader);
//get max number of iteams in the file
Writer.useDelimiter(",");
String num = Writer.next();
int max=Integer.parseInt(num);
System.out.println(num + " Max");
/*start Random
Random rand = new Random();
int min;
min = 1;
int Amount = rand.nextInt((max - min) + 1) + min;
System.out.println(Amount + " Amount");*/
String Item = Writer.next(); //get the name of the iteam
System.out.println(Item + " Item1"); //print item
String Price = Writer.next(); ///get price of the item...this is were the error occurs
System.out.println(Price + " Price1"); //print price
num = Writer.next(); //Suppose to get the number of the item
int Num=Integer.parseInt(num); //conver to an int
System.out.println(Num + " Num");
Item = Writer.next();
System.out.println(Item + " Item2");
Price = Writer.next();
System.out.println(Price + " Price2");
BuffReader.close();
Writer.close();
}
the example for the CSV/txtfile is
116,item,Price
1,item2,price2
2,item3,price
my goal is to choose a random item from this list using a util.Random, and checking what number it is using the first number in the txt file and saving the team and price to an array
You can use \n
as an additional delimiter besides ,
. Simply change this line of code:
Writer.useDelimiter(",");
to this one:
Writer.useDelimiter("(,|\n)");
With this next()
reads three values in each line and does not combine the last and first value of two lines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.