Reading file and store in vector - java

I'm reading from the file:
name1 wordx wordy passw1
name2 wordx wordy passw2
name3 wordx wordy passw3
name (i) wordx wordy PASSW (i)
x
x word
x words
words
x
words
At the moment I can print line by line:
Line 1: name1 wordx wordy passw1
Line 2: name2 wordx wordy passw2
I plan to have access to:
users [0] = name1
users [1] = name2
users [2] = name3
..
passws [0] = passw1
passws [1] = passw2
passws [2] = passw3
..
My code is:
public static void main(String args[]) throws FileNotFoundException, IOException {
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = null;
try {
inFile = new Scanner(new File("C:\\file.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (inFile.hasNextLine()) {
list.add(inFile.nextLine()+",");
}
String listString = "";
for (String s : list) {
listString += s + "\t";
}
String[] parts = listString.split(",");
System.out.println("Line1: "+ parts[0]);
}
How do I get the following output:
User is name1 and password is passw1
User is name32 and password is passw32
Thanks in advance.

Something like this will do:
public static void main(String args[]) throws FileNotFoundException, IOException {
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = null;
try {
inFile = new Scanner(new File("C:\\file.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (inFile.hasNextLine()) {
list.add(inFile.nextLine());
}
int line = 0;
String[] parts = list.get(line).split(" ");
String username = parts[0];
String pass = parts[3];
System.out.println("Line" + (line + 1) + ": " + "User is " + username +" and password is " + pass);
}
EDIT: if you want to iterate through all lines just put last lines in a loop:
for (int line = 0; line < list.size(); line++) {
String[] parts = list.get(line).split(" ");
String username = parts[0];
String pass = parts[3];
System.out.println("Line" + (line + 1) + ": " + "User is " + username +" and password is " + pass);
}

First thing to do is, to add this loop to the end of your code :
for(int i = 0; i <= parts.length(); i++){
System.out.println("parts["+i+"] :" + parts[i] );
}
that will simply show the result of the split using ,.
Then adapt your code, you may want to use another regex to split() your lines, for instance a space.
String[] parts = listString.split(" ");
for documentation about split() method check this.

If you want to get that output then this should do the trick:
public static void main(String args[]) throws FileNotFoundException, IOException {
Scanner inFile = null;
try {
inFile = new Scanner(new File("F:\\file.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Map<String, String> userAndPassMap = new LinkedHashMap<>();
while (inFile.hasNextLine()) {
String nextLine = inFile.nextLine();
String[] userAndPass = nextLine.split(" ");
userAndPassMap.put(userAndPass[0], userAndPass[1]);
}
for (Map.Entry<String, String> entry : userAndPassMap.entrySet()) {
System.out.println("User is:" + entry.getKey() + " and password is:" + entry.getValue());
}
}
By storing in a map you are linking directly each username with its password. If you need to save them into separate arrays then you can do this in the while loop instead:
List<String> users = new LinkedList<>(),passwords = new LinkedList<>();
while (inFile.hasNextLine()) {
String nextLine = inFile.nextLine();
String[] userAndPass = nextLine.split(" ");
users.add(userAndPass[0]);
passwords.add(userAndPass[1]);
}
and later transform them to arrays
users.toArray()

I recommend you use a java.util.Map, a standard API which allows you to store objects and read each one of them by a key. (In your case, string objects indexed by string keys). Example:
Let's assume this empty map:
Map<String, String> map=new HashMap<String,String>();
If you store this:
map.put("month", "january");
map.put("day", "sunday");
You can expect that map.get("month") will return "january", map.get("day") will return "sunday", and map.get(any-other-string) will return null.
Back to your case: First, you must create and populate the map:
private Map<String, String> toMap(Scanner scanner)
{
Map<String, String> map=new HashMap<String, String>();
while (scanner.hasNextLine())
{
String line=scanner.nextLine();
String[] parts=line.split(" ");
// Validation: Process only lines with 4 tokens or more:
if (parts.length>=4)
{
map.put(parts[0], parts[parts.length-1]);
}
}
return map;
}
And then, to read the map:
private void listMap(Map<String,String> map)
{
for (String name : map.keySet())
{
String pass=map.get(name);
System.out.println(...);
}
}
You must include both in your class and call them from the main method.

If you need arbitraray indexing of the read lines, use ArrayList:
First, define a javabean User:
public class User
{
private String name;
private String password;
// ... add full constructor, getters and setters.
}
And then, you must create and populate the list:
private ArrayList<User> toList(Scanner scanner)
{
List<User> list=new ArrayList<User>();
while (scanner.hasNextLine())
{
String line=scanner.nextLine();
String[] parts=line.split(" ");
// Validation: Process only lines with 4 tokens or more:
if (parts.length>=4)
{
list.add(new User(parts[0], parts[parts.length-1]));
}
}
return list;
}

Related

Take user input and search through 2D array and printout the result

I am trying to make a program that takes input from the user, searches through 2D array and prints out if the input matches data from the arrays. So, basically if the user types in VA, it should output Virginia. I am reading data from a Binary file that has 2 rows of data. The 1st row contains 2 letter abbreviations for all the states and the 2nd row contains the state names. For example: VA Virginia and in new line FL Florida and so on. Below is what I have so far. readStateFile() method works fine. I just need some help with getState method.
public static void main(String[] args) throws IOException {
try {
int age = getAge();
String[][] states = readStateFile();
String state = getState(states);
int ZIPCode = getZIPcode();
System.out.printf("\nAge:\t\t%d\n", age);
System.out.printf("Address:\t%s %s\n\n", ZIPCode, state);
System.out.println("Your survey is complete. " + "Your participation has been valuable.");
} catch (CancelledSurveyException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Thank you for your time.");
}
}
private static String getState(String[][] states) throws IOException {
states = readStateFile();
String in = "";
String[][] abb;
abb = states;
System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
Scanner st = new Scanner(System.in);
in = st.next();
if (in.equals("q")) {
System.out.println("Your survey was cancelled.\n" + "Thank you for your time.");
System.exit(0);
}
if (abb.equals(states)) {
for (int i = 0; states[0][i] != null; i++) {
if (abb.equals(states[0][i])) {
for (int state = 1; state <= 100; state++) {
System.out.println(states[0][i]);
}
}
}
} else {
System.out.println("You've entered invalid state abbrevation.");
}
return in;
}
private static String[][] readStateFile() throws IOException {
String states[][] = new String[50][50];
try {
FileInputStream fstream = new FileInputStream("states copy.bin");
DataInputStream inputFile = new DataInputStream(fstream);
for (int i = 0, j = i + 1; i < 50; i++) {
states[i][0] = inputFile.readUTF();
states[i][j] = inputFile.readUTF();
// System.out.println(states);
}
inputFile.close();
return states;
} catch (EOFException e) {
System.out.println("Survey Cancelled");
}
return states;
} ```
Instead of using a multidimensional array, it might be more helpful to use a HashMap.
Each abbreviation is used as a key, and the name of the state can be found using that key as a lookup. Illustrated below:
public static void main(final String[] args)
{
try
{
final Map<String, String> states = readStateFile();
// Display the contents of the file
// for (final Map.Entry<String, String> s : states.entrySet())
// {
// System.out.println(s.getKey() + " = " + s.getValue());
// }
final String state = getState(states);
final int age = getAge();
final int postalCode = getZIPcode();
System.out.println();
System.out.printf("Age:\t\t%d\n", Integer.valueOf(age));
System.out.printf("Address:\t%s %s\n\n", Integer.valueOf(postalCode), state);
System.out.println("Your survey is complete. Your participation has been valuable.");
}
catch (final IOException ex)
{
System.out.println(ex.getMessage());
}
System.out.println("Thank you for your time.");
}
private static String getState(final Map<String, String> states)
{
System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
final StringBuilder sb = new StringBuilder();
try (final Scanner st = new Scanner(System.in))
{
final String stateAbbrev = st.next().toUpperCase(Locale.getDefault());
if ("Q".equals(stateAbbrev))
{
System.out.println("Your survey was cancelled." + System.lineSeparator() + "Thank you for your time.");
System.exit(0);
}
if (states.containsKey(stateAbbrev))
{
final String stateName = states.get(stateAbbrev);
sb.append(stateName);
}
else
{
System.out.println("You've entered an invalid state abbrevation: " + stateAbbrev);
}
}
return sb.toString();
}
private static Map<String, String> readStateFile() throws IOException
{
final List<String> lines = Files.readAllLines(Paths.get("C:/states copy.bin"));
// Get a list of items, with each item separated by any whitespace character
final String[] stateAbbrev = lines.get(0).split("\\s");
final String[] stateNames = lines.get(1).split("\\s");
final Map<String, String> states = new HashMap<>();
for (int i = 0; i < stateAbbrev.length; i++)
{
states.put(stateAbbrev[i], stateNames[i]);
}
return states;
}

display array issues possibly due to whitespace characters

I'm trying to import a txt file with car info and separate the strings into arrays and then display them. The number of doors is combined with the next number plate. Have tried a few ways to get rid of the whitespace characters which I think is causing the issue but have had no luck.
whitespace chars
My code displays this result:
Number Plate : AG53DBO
Car Type : Mercedes
Engine Size : 1000
Colour : (255:0:0)
No. of Doors : 4
MD17WBW
Number Plate : 4
MD17WBW
Car Type : Volkswagen
Engine Size : 2300
Colour : (0:0:255)
No. of Doors : 5
ED03HSH
Code:
public class Application {
public static void main(String[] args) throws IOException {
///// ---- Import File ---- /////
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
String content = stringBuilder.toString();
///// ---- Split file into array ---- /////
String[] dataList = content.split(",");
// Display array
for (String temp : dataList) {
// System.out.println(temp);
}
ArrayList<Car> carArray = new ArrayList();
// Loop variables
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 5) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
}
}
And
public class Car {
String[] data;
private String modelUnpro;
private String engineSizeUnpro;
private String registrationUnpro;
private String colourUnpro;
private String doorNoUnpro;
// Constructor
public Car(String[] data, int arrayPosition) {
registrationUnpro = data[arrayPosition];
modelUnpro = data[arrayPosition + 1];
engineSizeUnpro = data[arrayPosition + 2];
colourUnpro = data[arrayPosition + 3];
doorNoUnpro = data[arrayPosition + 4];
}
// Getters
private String getModelUnpro() {
return modelUnpro;
}
private String getEngineSizeUnpro() {
return engineSizeUnpro;
}
private String getRegistrationUnpro() {
return registrationUnpro;
}
private String getColourUnpro() {
return colourUnpro;
}
private String getDoorNoUnpro() {
return doorNoUnpro;
}
public String displayCar() {
return "Number Plate : " + getRegistrationUnpro() + "\n Car Type : " + getModelUnpro() + "\n Engine Size : "
+ getEngineSizeUnpro() + "\n Colour : " + getColourUnpro() + "\n No. of Doors : " + getDoorNoUnpro() + "\n";
}
}
Text file:
AG53DBO,Mercedes,1000,(255:0:0),4
MD17WBW,Volkswagen,2300,(0:0:255),5
ED03HSH,Toyota,2000,(0:0:255),4
OH01AYO,Honda,1300,(0:255:0),3
WE07CND,Nissan,2000,(0:255:0),3
NF02FMC,Mercedes,1200,(0:0:255),5
PM16DNO,Volkswagen,1300,(255:0:0),5
MA53OKB,Honda,1400,(0:0:0),4
VV64BHH,Honda,1600,(0:0:255),5
ER53EVW,Ford,2000,(0:0:255),3
Remove Line separator from while loop.
String fileName = "D:\\Files\\a.txt";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line.trim());
}
reader.close();
String content = stringBuilder.toString();
String[] dataList = content.split(",");
ArrayList<Car> carArray = new ArrayList();
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 3) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
In StringBuilder you collect all lines:
AG53DBO,Mercedes,1000,(255:0:0),4\r\nMD17WBW,Volkswagen,2300,(0:0:255),5\r\n...
This string should first be spit on ls - and then you have lines with fields separated by comma.
Now just splitting by comma will cause a doubled array element 4\r\nMD17WBW.
Something like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path); // Without line ending.
List<Car> cars = new ArrayList<>();
for (String line : lines) {
String[] data = line.split(",");
Car car = new Car(data);
cars.add(car);
}
Path, Paths and especially Files are very handy classes. With java Streams one also can abbreviate things like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<Car> cars = Files.lines(path) // Stream<String>
.map(line -> line.split(",")) // Stream<String[]>
.map(Car::new) // Stream<Car>
.collect(Collectors.toList()); // List<Car>
Here .lines returns a Stream<String> (walking cursor) of lines in the file, without line separator.
Then .map(l -> l.split(",")) splits every line.
Then the Car(String[]) constructor is called on the string array.
Then the result is collected in a List.

How to count unique words in a text file?

I have implemented code to count number of:
- chars
- words
- lines
- bytes
in text file.
But how to count dictionary size: number of different words used in this file?
Also, how to implement iterator which can iterate over only letters? (Ignore whitespaces)
public class wc {
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File file = new File("Sample.txt");
try(Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)))){
while (scanner.hasNextLine()) {
String tmpStr = scanner.nextLine();
if (!tmpStr.equalsIgnoreCase("")) {
String replaceAll = tmpStr.replaceAll("\\s+", "");
charsCount += replaceAll.length();
wordsCount += tmpStr.split("\\s+").length;
}
++linesCount;
}
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
System.out.println("# of bytes: " + file.length());
}
}
}
To get unique words and their counts:
1. Split your obtained line from file into a string array
2. Store the contents of this string array in a Hashset
3. Repeat steps 1 and 2 till end of file
4. Get unique words and their count from the Hashset
I prefer posting logic and pseudo code as it will help OP to learn something by solving posted problem.
Example of how my code works:
File with words "aa bb cc cc aa aa" has 3 unique words.
First, turn words into a string with each word separated by "-".
String: "aa-bb-cc-cc-aa-aa-"
Get the first word: "aa", set the UniqueWordCount = 1, and then replace "aa-" with "".
New String: "bb-cc-cc-"
Get the first word: "bb", set the UniqueWordCount = 2, and then replace "bb-" with "".
New String: "cc-cc-"
Get the first word: "cc", set the UniqueWordCount = 3, and then replace "cc-" with "".
New String: "", you stop when the string is empty.
private static int getUniqueWordCountInFile(File file) throws FileNotFoundException {
String fileWordsAsString = getFileWords(file);
int uniqueWordCount = 0;
int i = 0;
while (!(fileWordsAsString.isEmpty()) && !(fileWordsAsString.isBlank())) {
if (Character.toString(fileWordsAsString.charAt(i)).equals(" ")) {
fileWordsAsString = fileWordsAsString.replaceAll(fileWordsAsString.substring(0, i+1),"");
i = 0;
uniqueWordCount++;
} else {
i++;
}
}
return uniqueWordCount;
}
private static String getFileWords(File file) throws FileNotFoundException {
String toReturn = "";
try (Scanner fileReader = new Scanner(file)) {
while (fileReader.hasNext()) {
if (fileReader.hasNextInt()) {
fileReader.nextInt();
} else {
toReturn += fileReader.next() + " ";
}
}
}
return toReturn;
}
If you want to use my code just pass getUniqueWordCountInFile() the file that has the words for which you want to count the unique words.
hey #JeyKey you can use HashMap. Here I using Iterator too. You can check out this code.
public class CountUniqueWords {
public static void main(String args[]) throws FileNotFoundException {
File f = new File("File Name");
ArrayList arr=new ArrayList();
HashMap<String, Integer> listOfWords = new HashMap<String, Integer>();
Scanner in = new Scanner(f);
int i=0;
while(in.hasNext())
{
String s=in.next();
//System.out.println(s);
arr.add(s);
}
Iterator itr=arr.iterator();
while(itr.hasNext())
{i++;
listOfWords.put((String) itr.next(), i);
//System.out.println(listOfWords); //for Printing the words
}
Set<Object> uniqueValues = new HashSet<Object>(listOfWords.values());
System.out.println("The number of unique words: "+uniqueValues.size());
}
}

Java reading from text file and remove dash in string

I have a text file:
John Smith 2009-11-04
Jenny Doe 2009-12-29
Alice Jones 2009-01-03
Bob Candice 2009-01-04
Carol Heart 2009-01-07
Carlos Diaz 2009-01-10
Charlie Brown 2009-01-14
I'm trying to remove the dashes and store them as separate types: first, last, year,month,day and then add it to a sortedset/hashmap. But for some reason. It's not working right.
Here is my code:
public class Test {
File file;
private Scanner sc;
//HashMap<Name, Date> hashmap = new HashMap<>();
/**
* #param filename
*/
public Test(String filename) {
file = new File(filename);
}
public void openFile(String filename) {
// open the file for scanning
System.out.println("Test file " + filename + "\n");
try {
sc = new Scanner(new File("birthdays.dat"));
}
catch(Exception e) {
System.out.println("Birthdays: Unable to open data file");
}
}
public void readFile() {
System.out.println("Name Birthday");
System.out.println("---- --------");
System.out.println("---- --------");
while (sc.hasNext()) {
String line = sc.nextLine();
String[] split = line.split("[ ]?-[ ]?");
String first = split[0];
String last = split[1];
//int year = Integer.parseInt(split[2]);
//int month = Integer.parseInt(split[3]);
//int day = Integer.parseInt(split[4]);
Resource name = new Name(first, last);
System.out.println(first + " " + last + " " + split[2] );
//hashmap.add(name);
}
}
public void closeFile() {
sc.close();
}
public static void main(String[] args) throws FileNotFoundException,
ArrayIndexOutOfBoundsException {
try {
Scanner sc = new Scanner( new File(args[0]) );
for( int i = 0; i < args.length; i++ ) {
//System.out.println( args[i] );
if( args.length == 0 ) {
}
else if( args.length >= 1 ) {
}
// System.out.printf( "Name %-20s Birthday", name.toString(), date.toString() );
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: Birthdays dataFile");
// Terminate the program here somehow, or see below.
System.exit(-1);
} catch (FileNotFoundException e) {
System.err.println("Birthdays: Unable to open data file");
// Terminate the program here somehow, or see below.
System.exit(-1);
}
Test r = new Test(args[0]);
r.openFile(args[0]);
r.readFile();
r.closeFile();
}
}
Your splitting on dashes but your is program is build around a split using spaces.
Try just splitting on spaces
String[] split = line.split("\\s");
So "John Smith 2009-11-04".split("[ ]?-[ ]?"); results in ["John Smith 2009", "11", "04"] When what you want is for it to split on spaces ["John", "Smith", "2009-11-04"]
I would do this differently, first create a domain object:
public class Person {
private String firstName;
private String lastName;
private LocalDate date;
//getters & setters
//equals & hashCode
//toString
}
Now create a method that parses a single String of the format you have to a Person:
//instance variable
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public Person parsePerson(final String input) {
final String[] data = input.split("\\s+");
final Person person = new Person();
person.setFirstName(data[0]);
person.setLastName(data[1]);
person.setDate(LocalDate.parse(data[2], dateTimeFormatter));
return person;
}
Note that the DateTimeFormatter is an instance variable, this is for speed. You should also set the ZoneInfo on the formatter if you need to parse dates not in your current locale.
Now, you can read your file into a List<Person> very easily:
public List<Person> readFromFile(final Path path) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines
.map(this::parsePerson)
.collect(toList());
}
}
And now that you have a List<Person>, you can sort or process them however you want.
You can even do this while creating the List:
public List<Person> readFromFile(final Path path) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines
.map(this::parsePerson)
.sorted(comparing(Person::getLastName).thenComparing(Person::getFirstName))
.collect(toList());
}
}
Or have your Person implements Comparable<Person> and simply use natural order.
TL;DR: Use Objects for your objects and life becomes much simpler.
I would use a regex:
private static Pattern LINE_PATTERN
= Pattern.compile("(.+) (.+) ([0-9]{4})-([0-9]{2})-([0-9]{2})");
...
while (sc.hasNext()) {
String line = sc.nextLine();
Matcher matcher = LINE_PATTERN.matcher(line);
if (!matcher.matches()) {
// malformed line
} else {
String first = matcher.group(1);
String last = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
int month = Integer.parseInt(matcher.group(4));
int day = Integer.parseInt(matcher.group(5));
// do something with it
}
}
You are splitting on spaces and a hyphen. This pattern does not exist.
String[] split = line.split("[ ]?");
String first = split[0];
String last = split[1];
line = split[2];
//now split the date
String[] splitz = line.split("-");
or something like this might work:
String delims = "[ -]+";
String[] tokens = line.split(delims);
If i understood your question right then Here is answer. Check it out.
List<String> listGet = new ArrayList<String>();
String getVal = "John Smith 2009-11-04";
String[] splited = getVal.split("[\\-:\\s]");
for(int j=0;j<splited.length;j++)
{
listGet.add(splited[j]);
}
System.out.println("first name :"+listGet.get(0));
System.out.println("Last name :"+listGet.get(1));
System.out.println("year is :"+listGet.get(2));
System.out.println("month is :"+listGet.get(3));
System.out.println("day is :"+listGet.get(4));
OP :
first name :John
Last name :Smith
year is :2009
month is :11
day is :04

method to read array list to find certain string and value

public class array {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));
System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line;
List<String> list = new ArrayList<String>();
while((line=reader.readLine()) !=null)
{
list.add(line);
}
reader.close();
for (String s : list) {
System.out.println(s);
}
}
}
I have fruit.txt
apple 20 good
orange 30 good
banana 40 needmore
how do I retrieve how many oranges I have from the array list.
I want the program to read the user input in this case "orange" and display out 30 and the status is not good.
ideal output is
You have orange 30 of them and status is good
Try the following updated class.
public class array
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));
System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line;
boolean found = false;
int count = 0;
List<String> list = new ArrayList<String>();
while ((line = reader.readLine()) != null)
{
String[] items = line.split(" ");
if (fruit.equals(items[0]))
{
found = true;
count = Integer.parseInt(items[1]);
break;
}
list.add(line);
}
reader.close();
if (found)
{
System.out.println("You have " + fruit + " " + count + " of them and status is good");
}
}
}
You need to split your Strings in your List, and then print each elements of your array obtained within your specified string format: -
for (String s : list) {
String[] tokens = s.split(" ");
if (tokens[0].equals(fruit)) {
System.out.println("You have " + tokens[0] + " " + tokens[1] +
" of them and status is " + tokens[2]);
break;
}
}
Or, you can use: -
System.out.format("You have %s %s of them and status is %s",
tokens[0], tokens[1], tokens[2]);
You will need to split up the lines into the three fields using a StringTokenizer. Then I would create a new class to hold that information.
When you read a line, split the values into String array like this:
while((line=reader.readLine()) !=null)
{
String [] values = line.split(" ");
list.add("You have "+values[0] + " " + values[1] " of them and status is "+values[2] );
}
Not tested but should work, try:
public class array {
public static class Fruit {
private String name;
private String count;
private String status;
public Fruit(String name, String count, String status) {
this.name = name;
this.count = count;
this.status = status;
}
public String getName() {
return name;
}
public String getCount() {
return count;
}
public String getStatus() {
return status;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));
System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line= "";
HashMap<String, Fruit> map = new HashMap<String, Fruit>();
while ((line = reader.readLine()) != null) {
String[] strings = line.split(" ");
map.put(strings[0], new Fruit(strings[0], strings[1], strings[2]));
}
reader.close();
System.out.print("You have " + fruit + " " + map.get(fruit).getCount() + " of them and status is: " + map.get(fruit).getStatus());
}
}

Categories