Why isn't my file being opened? - java

The file is in the root directory of where my source code is. Also is having a number appened to the end of the path variable going to mess things up or how would you do that?
There are 10 files to choose from and they all have similar names but end with a different number. So I was thinking of having the default path variable and then append the number to it and then doing File nameFile = new File(path + year + ".txt")
Any idea why it's not picking it up?
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class nameRanker {
public static void main(String[] args) throws Exception {
int skip = 0;
int rank = 0;
int year = 0;
char gender = '0';
String name = "";
String compareName = "";
Boolean found = false;
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: "); //try to catch mismatched input here (0-10)
try { year = input.nextInt();
System.out.print("\nEnter the gender: "); //try to catch mismatched input here (M or F)
gender = input.next().charAt(0);
System.out.print("\nEnter the name: "); //try to catch mismatched input here (no #)
name = input.next();
}
catch (InputMismatchException e) {
e.printStackTrace();
System.err.println("Entered value does not match expected value. \n(Year must be integer, gender M or F, and name must be a string.)");
}
String path = "\\BabynamesrankingFiles\\Babynamesranking";
File nameFile = new File(path + year + ".txt"); //throws IOexception if not found
//Scanner readFile = null;
try (Scanner readFile = new Scanner(nameFile)){
//readFile = new Scanner(nameFile);
if(nameFile.canRead()){ //if the file is readable
while(readFile.hasNext() && !found){ //while data in file
if(gender == 'M'){ //if male only parse first two values
rank = readFile.nextInt(); //store rank
compareName = readFile.next(); //grab name to compare
found = (compareName == name) ? true : false; //if name found break while loop
}
if(gender == 'F'){
rank = readFile.nextInt(); //store the rank
compareName = readFile.next(); //store the boy name
skip = readFile.nextInt(); //store the total names value even though unused
compareName = readFile.next(); //store the girl name to compare
found = (compareName == name) ? true : false; //if name found break while loop
}
} //end while loop
if(!found){ //if name not found
System.out.println("The name " + name + "is not ranked in year " + year);
}
else{
System.out.println("The name " + name + " is ranked " + rank + " in the year " + year);
}
}
}
catch(IOException ex){
System.out.println("Error could not open file, check file path.");
}
finally {
input.close(); //close scanner
}
}
}

Related

comparing user inputs in array to make sure they dont have the same name in java

What am I missing it keeps, coming back false on the first try. What do I need to change to make sure it scans to get rid of duplicates.
final int numPassengers = 4;
final int numShips = 2;
boolean input = false;
String[] travelerNames = new String[4];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < numPassengers; ++i) {
System.out.println("Enter traveler name ");
do {
travelerNames[i] = scanner.nextLine();
if(travelerNames[i].equals(travelerNames[i])) {
System.out.println("Names cannot match enter new name!");
input = false;
scanner.next();
}
else {
input = true;
}
} while(!input);
System.out.println(travelerNames[i]);
A simple solution would be to use an arraylist.
Arraylist has a method called contains.
List<String> names = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if(names.contains(input)){
System.out.println("Name is duplicated");
}
else {
names.add(input);
}
I hope i could help you with your Problem
travelerNames[i] = scanner.nextLine(); Whoops... too late, it's already within the Array and it's in there before you get to check and see if it has been previously entered. Don't save a step here by popping the name into the Array right away, put the name into a String variable first then traverse the Array to see if that name already exists, for example:
for (int i = 0; i < numPassengers; ++i) {
String name = "";
while(name.isEmpty()) {
System.out.print("Enter traveler name #" + (i + 1) + ": -> ");
name = scanner.nextLine().trim();
if (name.isEmpty() || name.matches("\\d+")) {
System.out.println("Invalid Name Supplied! ("
+ name + ") Try again...\n");
name = "";
continue;
}
// Is the name already within the travelerNames[] Array?
for (String nme : travelerNames) {
if (nme != null && nme.equalsIgnoreCase(name)) {
System.out.println("Invalid Entry! The name '" + name
+ "' already exists! Try again...\n");
name = "";
break;
}
}
}
// Everything seems OK so add the name to the Array.
travelerNames[i] = name;
}
System.out.println();
System.out.println("The names contained within the Array:");
System.out.println(Arrays.toString(travelerNames));

Output prints first and part of second string. String sizes not set correctly

I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help

An array of string causing my program not to continue to run after an if-else statement - java

I am creating a simple program that gets an input from a user and outputs to .txt file. I have made some changes to my code so that whenever a user enters a variation of 'quit', 'Quit', or 'QUIT' it will break, else it will continue as normal. However when I run and enter data as normal it is not continuing as normal and stopping. Also, how would I display a printline so that when a user does type 'Quit' it would say for example
System.out.println("You have quit!");
My Code
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.nio.file.*;
public class JavaProject {
private static char[] input;
public static void main(String[] args) {
//variables
int hrs, mins;
String gamerName, gamerReport;
int gameCount;
int errorCount;
//Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
int[] minutesPlayed = new int [100];
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
//formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
//User enters either their name or quit. Entering a name will move on to next part
for ( ; ; )
{
System.out.print("Enter your Name. If you do not wish to proceed, enter 'Quit' to quit.");
System.out.println(" ");
gamerName = Scan.nextLine();
if ("Quit".equals(gamerName))
{
break;
}
for(int b = 1; b < 100; b++ ) { //this is making the code loop 100 times
//user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println("FALSE DATA FORMAT WILL CAUSE ERROR");
System.out.println(" ");
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport = null; // an array of string
//splitUpReport = gamerReport.split(":"); // split the text up on the colon
//gets input, if "quit" then break
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equals("quit"))
{
break;
}
if (gamerReport.equals("Quit"))
{
break;
}
if (gamerReport.equals("QUIT"))
{
break;
}
else
{
splitUpReport = gamerReport.split(":");
}
System.out.println("You have quit!");
}
int i = 0;
//copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
//output to file using a PrintWriter using a FileOutPutStream with append set to true within the printwriter constructor
//
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
//writer.println("Games Played: " + splitUpReport);
//writer.println("Total Achievement: " + highScores);
//writer.println("Total Time: " + minutesPlayedS%60);
writer.println();
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
System.out.println("Goodbye!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
my code issue
//gets input, if "quit" then break
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equals("quit"))
{
break;
}
if (gamerReport.equals("Quit"))
{
break;
}
if (gamerReport.equals("QUIT"))
{
break;
}
else
{
splitUpReport = gamerReport.split(":");
}
System.out.println("You have quit!");
}
You should change your if to else if. Otherwise your else is only regarding the third if. You can also use a single if with equalsIgnoreCase. This matches quit, Quit or QUIT.
To print a message, before each break, insert your System.out.println("You have quit!");
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
break;
}
splitUpReport = gamerReport.split(":");
gameNames[count] = splitUpReport[0];
highScores[count] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[count] = Integer.parseInt(splitUpReport[2].trim());
}
You also have another option, maybe more in-line with what you were trying to do.
// ignore the for loop
gamerReport = Scan.nextLine();
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
return;
}
splitUpReport = gamerReport.split(":");
You should also not comment one of your scans:
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
//gamerReport = Scan.nextLine();
And your writer should use splitReport:
writer.println("Game: " + splitUpReport[0] + ", score= " + splitUpReport[1] + ", minutes played= " + splitUpReport[2]);

How would I modify this so that rather than have it break it will just request the user to enter the file name again?

The problem
When the user enters the filename into the program, it will create an exception stating that there is no file named like that in the directory.
What I want is that - instead of showing an exception - the program will repeat the message that asks the user to enter the filename.
My code:
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName);
}else{
}
}
}
private static void processFile(String fileName) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
You can try determine if the file exists first by doing something like the following:
File file = new File(fileName);
if(file.exists()) {
processFile(fileName)
}
Here is the solution
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
File file = new File(fileName);
if(!file.exists()) {
continue;
}
processFile(fileName);
}
}
Use this code:
String fileName;
File file;
for(;;) {
/* read file name */
System.out.print("enter file name: ");
fileName = bufferedReader.readLine();
file = new File(fileName);
/* check path */
if (!file.exists())
System.out.println("file doesn't exist");
else if(!file.isFile())
System.out.println("file isn't a regular file");
else if (...)
...
else
break;
}
where bufferedReader is BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); if you want to read file name from keyboard.
You can check if file exists exists(), is a regular file isFile(), is a directory isDirectory(), can be read carRead(), wrote canWrite(), executed canExecute(), an so on..

Java Scanner class reading strings

I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains.
List of people: length 3
1 : Fnjiei : ID 7868860 : Age 18
2 : Oipuiieerb : ID 334134 : Age 39
3 : Enekaree : ID 6106274 : Age 31
I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) It was able to read one single line....... but no more than a single line of text.
public void readFile(String fileName)throws IOException{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
try {
while (input.hasNextLine()){
int howMany = 3;
System.out.println(howMany);
String userInput = input.nextLine();
String name = "";
String idS = "";
String ageS = "";
int id;
int age;
int count=0;
for (int j = 0; j <= howMany; j++){
for (int i=0; i < userInput.length(); i++){
if(count < 2){ // for name
if(Character.isLetter(userInput.charAt(i))){
name+=userInput.charAt(i); // store the name
}else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 2){ // for id
if(Character.isDigit(userInput.charAt(i))){
idS+=userInput.charAt(i); // store the id
}
else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 3){ // for age
if(Character.isDigit(userInput.charAt(i))){
ageS+=userInput.charAt(i); // store the age
}
}
id = Integer.parseInt(idS); // convert id to integer
age = Integer.parseInt(ageS); // convert age to integer
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
userInput = input.nextLine();
}
}
}finally{
if (input != null){
input.close();
}
}
}
My appology if my mere code begs to be changed.
Edited It gives me a number format exception!!!
I dont know how many empty space would be there between these values.
Here's a solution that uses only Scanner API, the important one being findInLine. It can handle minor syntactic variations in the input format, and yet it's very readable, requiring no need for fancy regex or magic array indices.
String text =
"List of ##%^$ people : length 3 !#%# \n" +
"1 : Fnjiei : ID 7868860 ::: Age 18\n" +
" 2: Oipuiieerb : ID 334134 : Age 39 (old, lol!) \r\n" +
" 3 : Enekaree : ID 6106274 => Age 31\n";
Scanner sc = new Scanner(text);
sc.findInLine("length");
final int N = sc.nextInt();
for (int i = 0; i < N; i++) {
sc.nextLine();
sc.findInLine(":");
String name = sc.next();
sc.findInLine("ID");
long id = sc.nextLong();
sc.findInLine("Age");
int age = sc.nextInt();
System.out.printf("[%s] %s (%s)%n", id, name, age);
}
This prints:
[7868860] Fnjiei (18)
[334134] Oipuiieerb (39)
[6106274] Enekaree (31)
API links
Scanner.findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
Use this Pattern.compile overload if performance is an issue
This seems to be shorter:
public void readFile(String fileName)throws IOException
{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
String userInput;
try
{
while (input.hasNextLine())
{
userInput = input.nextLine().trim();
if (userInput.length() > 0)
{
String[] userInfo = userInput.split(":");
int count = Integer.parseInt(userInfo[0].trim());
String name = userInfo[1].trim();
int id = Integer.parseInt(userInfo[2].trim().split("\\s+")[1].trim());
int age = Integer.parseInt(userInfo[3].trim().split("\\s+")[1].trim());
System.out.println("Count: " + count + " Name: " + name + " ID:" + id + " Age:" + age);
}
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
}
finally
{
if (input != null)
{
input.close();
}
}
}
For the input you have us, it prints this:
Count: 1 Name: Fnjiei ID:7868860 Age:18
Count: 2 Name: Oipuiieerb ID:334134 Age:39
Count: 3 Name: Enekaree ID:6106274 Age:31
More information about the split method can be found here. I basically first split the line by using the : as delimiter, then, I split again using the \\s+, which basically splits a string and return an array containing the words that were separated by white spaces.
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader("filename")));
try{
while(input.hasNextLine()){
String userInput = input.nextLine();
String[] data = userInput.split(":");
System.out.println("Name: "+data[1]+" ID:"+data[2].split("\\s+")[2]+
" Age:"+data[3].split("\\s+")[2]);
}
}finally{
if(input != null)
input.close();
}
Above snippet shows the basic idea.Also please keep in mind that this might not be the optimal solution.

Categories

Resources