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.
Related
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));
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}
You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!
You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;
Using Java, im reading in an input file using scanner and i am able to read and print out the input file. But i am having difficulty parsing it now.
The example input file is as follows :
height 6
weight 120
name john
team played for team1 start 2010 end 2012
team played for team1 start 2010 end 2012
team played for team2 start 2013 end 2015
how do i go about parsing this information. currently im scanning the input by line like:
while (scanner.hasNext()) {
String line = scanner.nextLine();
System.out.println(line);
}
would i do something like
int height = height.nextInt();
int weight = weight.nextInt();
String name = name.nextLine();
and now im stuck with the last 3 lines, assuming the first 3 lines were parsed correctly
As Stated by #pshemo i missed out to add line = line.replace(..)
int height = 0;
int weight = 0;
String name = "";
while (scanner.hasNextLine()) // use hasNextLine()
{
String line = scanner.nextLine();
if(line.startWith("height ")) // do the same for weight
{
line = line.replace("height ", "");
try
{
height = Integer.parseInt(line);
}
catch(NumberFormatException e1)
{
}
}
else if(line.startWith("weight ")) // do the same for weight
{
line = line.replace("weight ", "");
try
{
weight = Integer.parseInt(line);
}
catch(NumberFormatException e1)
{
}
}
else if(line.startsWith("name "))
{
line = line.replace("name ", "");
name = line;
}
else if(line.startsWith("team played for "))
{
line = line.replace("team played for ", "");
String teamName = "";
int i = 0;
while(line.charAt(i) != ' ')
{
teamName = teamName + line.charAt(i); // copying the team name till space
i++;
}
line = line.replace(teamName+" ","");
// now we will be left with a string that contains start year 1 end year 2
line = line.replace("start ", "");
i = 0; // using the same i variable
String startYear = "";
while(line.charAt(i) != ' ')
{
startYear = startYear+ line.charAt(i);
i++
}
line = line.replace(startYear+" end ", "");
String endYear = line;
// just make this as global variables if u need to use them in a different method also if you need to parse string to integer use Interger.parseInt(String)
}
System.out.println("Name :-" + name);
System.out.println("Weight :-" + weight);
System.out.println("Height :-" + height);
}
// by now all the data has been stored to their respective variables
I think that this solution is a bit more elegant.
BTW, I don't really know what do you want to do with the information so I've just left It as is. You can create an object or just print it to console:
while (scanner.hasNext()) {
scanner.next(); // skip "height"
int height = scanner.nextInt(); // get height
scanner.next(); // skip "weight"
int weight = scanner.nextInt(); // get weight
scanner.next(); // skip "name"
String name = scanner.next(); // get name
while (scanner.hasNext("team")) {
// parse the "team info" similarly, as shown above.
// make sure that you parse it correctly, so that
// in the next inner while loop, the scanner.hasNext("team")
// will be positioned just before the next line of "team"
// or a next line that containes a new record.
}
}
As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}
Currently I have text file that stores student names and their test scores. The format of the file is last name, first name, and test score. Each value in the text file is separated but a space. So the file looks similar to this:
Smith John 85
Swan Emma 75
I've got the code running so that it prints all the data to the console, but what I can't get it to do is take all the test scores, add them up, and find the average and print the average to the console. As well as print any students' whose score is 10 less then the average.
Right now this is the code I'm using to read and print the information to the console.
public class ReadTXT
{
public static void main(String[] args)
{
{
String txtFile = "/Users/Amanda/Desktop/Studentdata.txt";
BufferedReader br = null;
String line = "";
String txtSplitBy = " ";
try {
br = new BufferedReader(new FileReader(txtFile));
while ((line = br.readLine()) != null) {
String[] LastName= line.split(txtSplitBy);
String[] FirstName = line.split(txtSplitBy);
String[] TS = line.split(txtSplitBy);
System.out.println("Last Name: " + LastName[0]
+ "\n" +"First Name: " + FirstName[1] + "\n" +
"Test Score: " + TS [2] + "\n") ;
{
double average = sum / i;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
}
And this is the code I was trying to use to find the average.
int i =Integer.parseInt ("TS");
double sum = 0.0;
for (int x = 0; x < i; sum += i++);
{
double average = sum / i;
}
I keep getting this exception, though:
Exception in thread "main" java.lang.NumberFormatException: For input string: "TS"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at ReadTXT.main(ReadTXT.java:35)
I am new to learning java but I am trying.
This code here:
String[] LastName= line.split(txtSplitBy);
String[] FirstName = line.split(txtSplitBy);
String[] TS = line.split(txtSplitBy);
is not really needed, as you are splitting the line several times to create 3 different String arrays, what you want to do is split the line once and then assign variables from the array indexs like this:
String[] splitLine = line.split(txtSplitBy);
String lastName = splitLine[0]; //first element of array
String firstName = splitLine[1]; //second element of array
String score = splitLine[2]; //third element of array
Then you can parse the score as a string, which will be a number not the literal String you are trying "TS" you want the variable name, so leave out the "
int i = Integer.parseInt (score);
Then for each iteration in your while loop add to a total and have a count then calculate your average that way. (or create a List of scores )Like:
int total = 0;
int count = 0;
List<Integer> allScores = new ArrayList<Integer>();
while ((line = br.readLine()) != null)
{
String[] splitLine = line.split(txtSplitBy);
String lastName = splitLine[0]; //first element of array
String firstName = splitLine[1]; //second element of array
String score = splitLine[2]; //third element of array
System.out.println("Last Name: " + lastName
+ "\n" +"First Name: " + firstname + "\n" +
"Test Score: " + score + "\n") ;
int i = Integer.parseInt (score);
total += i;
count++;
// Add to List
allScores.add(i);
}
double average = total/count;
To loop a List
for( Integer i: allscores)
{
// Do the appropriate code here
}
If you need the names also you should create a Class to hold firstName, lastName and score then add these to your list.
See This Tutorial on Classes
Oops:
int i =Integer.parseInt ("TS");
This doesn't make sense. What number is "TS" supposed to represent?
Edit: you state:
I know that TS is not a valid number that's why I was trying to cast it to a number
You can't "cast" letters to a number, again it makes no sense.
You need to read in the Strings in the file and then parse those Strings, not some letters you make up.
What your code should do is:
read in each line in the file in a for loop
inside this loop, split the String using String's split(" ") method.
Use Integer.parse(...) to parse the 3rd item in the array returned.
So would I use Integer.parse(String [] TS)?
No, this won't even compile since you're trying to pass a String array into a method that takes a String parameter.