java - Read a specific line from file and separate the data from one line -
i'm new java appreciated.
i'm trying write program asks user file read from, asks id, searches inside file id , outputs information line. text file read formatted this:
apple^201^3
banana^202^4
orange^205^5
the 2nd
column id.
also need separate information how can output this:
item: apple
id: 201:
price: $3
import java.util.*; import java.io.*; public class fruit { public static void main(string[] args) throws ioexception { scanner keyboard = new scanner(system.in); system.out.println("enter filename >> "); string filename = keyboard.nextline(); file f = new file(filename); scanner fin = new scanner(f); system.out.println("enter item id: "); int fruitid = keyboard.nextint(); while(fin.hasnextline()) { string line = fin.nextline(); if(fin.hasnextint(fruitid)) { system.out.println(line); } else { system.out.println("error"); } } fin.close(); } }
hope import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class findgivenstringfromfile { public static void main(string args[]) throws filenotfoundexception { scanner keyboard = new scanner(system.in); system.out.println("enter filename >> "); string filename = keyboard.nextline(); file f = new file(filename); scanner fin = new scanner(f); system.out.println("enter item id: "); int fruitid = keyboard.nextint(); //reading each line of file using scanner class int linenumber = 1; while (fin.hasnextline()) { string line = fin.nextline(); string[] linedataarray = line.split("\\^"); if(linedataarray != null && linedataarray.length >2){ if(integer.parseint(linedataarray[1]) == fruitid){ system.out.println("item: " + linedataarray[0]); system.out.println("id: " + linedataarray[1]); system.out.println("price: $" + linedataarray[2]); } linenumber++; } } } }
Comments
Post a Comment