Reading only the integers from a txt file and adding the value up for each found
Edit:
You'll have to excuse me, that method will not work. What you need to do is read one line at a time, then split the line by each space, to get an array of words. From there you can identify integers and store the value.
final static String filename = "FILENAME.txt";
public static void main(String[] args) {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(" ");
//For each word in the line
for(String str : words) {
try {
int num = Integer.parseInt(str);
total += num;
foundInts = true;
System.out.println("Found: " + num);
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total);
// close the scanner
scan.close();
}
Reading only integers from text file and adding them
You are almost there. Make a sum
to add up the numbers, and add continue
to skip to the next line on error:
int sum = 0;
boolean isGood = true;
for(String str : words) {
try {
sum += Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// If any of the items fails to parse, skip the entire line
isGood = false;
continue;
};
}
if (isGood) {
// If everything parsed, print the sum
System.out.println(sum);
}
I need to read only Integers from a random scanner text file in Java. I can't get it to skip non integers and the whole code breaks
There is no need to use skip()
for this task.
You can check if next token is integer or not and skip all not integers.
For example:
while(scanFile.hasNext()) {
if (!scanFile.hasNextInt()) {
scanFile.next();
continue;
}
System.out.println(scanFile.nextInt());
}
Output:
23 23 44 55 100 0 39 58
JAVA- Read integers from txt file and compute integers
Here's the fixed code. Instead of splitting the input using
" "
you should have split it using
","
That way when you parse the split strings you can use the substring method and parse the number portion of the input.
For example, given the string
Arthur Albert,74%
my code will split it into Arthur ALbert
and 74%
.
Then I can use the substring method and parse the first two characters of 74%, which will give me 74.
I wrote the code in a way so that it can handle any number between 0 and 999, and added comments when I made additions that you didn't already have. If you still have any questions however, don't be afraid to ask.
final static String filename = "filesrc.txt";
public static void main(String[] args) throws IOException {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
int successful = 0; // I did this to keep track of the number of times
//a grade is found so I can divide the sum by the number to get the average
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(",");
//For each word in the line
for(String str : words) {
System.out.println(str);
try {
int num = 0;
//Checks if a grade is between 0 and 9, inclusive
if(str.charAt(1) == '%') {
num = Integer.parseInt(str.substring(0,1));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is between 10 and 99, inclusive
else if(str.charAt(2) == '%') {
num = Integer.parseInt(str.substring(0,2));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
//Checks if a grade is 100 or above, inclusive(obviously not above 999)
else if(str.charAt(3) == '%') {
num = Integer.parseInt(str.substring(0,3));
successful++;
total += num;
foundInts = true;
System.out.println("Found: " + num);
}
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total/successful);
// close the scanner
scan.close();
}
How to read all numbers from a file then add them together?
You are almost there. Try your same code with minor modification. I have added inline comments.
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
//lstRandomNumbers.Items.Clear(); //don't need this
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
//lstRandomNumbers.Items.Clear();//don't need this
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
//lstRandomNumbers.Items.Add(number);//don't need this
sum+=number; // add this
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = sum.ToString(); //change `number' to `sum`
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
@Issa, Please let me know if this helps.
Reading integers from text file
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
where isNumeric can be defined as follows:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Reading integers from a text file only and separating
Try this:
Private Sub test()
Dim sr As New System.IO.StreamReader("file.txt")
Dim LofInt As New List(Of String)
While sr.Peek <> -1
Dim line As String = sr.ReadLine
Dim intValue As String = String.Empty
For Each c As Char In line
If IsNumeric(c) Then
intValue += c
End If
Next
LofInt.Add(intValue)
End While
sr.Close()
LofInt.Sort()
For Each i In LofInt
ListBox1.Items.Add(i)
Next
End Sub
So basicly what we do:
We read you file line by line and store the numeric values. after each line we add what we've got to a list.
After that we use a function of that list to sort the "numers" (still a string, so we should say text) and add them to your listbox
Related Topics
How to Stop the Items Duplication in Recyclerview Android
Reading Data from Nested Json Object Using Java
Intellij Idea - Gradle: Execution Failed for Task ':Compilejava'
Java Spring @Scheduled Tasks Executing Twice
How to Encrypt a String/Stream With Bouncycastle Pgp Without Starting With a File
Deserialization With @Jsonsubtypes for No Value - Missing Property Error
How to Do Name Validation Allowing Alphabet, Spaces and Dot in Android
Cannot Find Element Using Selenium Webdriver
Handling the Null Value from a Resultset
Ora-00942 Sqlexception With Hibernate (Unable to Find a Table)
Subscript and Superscript a String in Android
How to Count Method Calls by Instance
How to Junit Test That Two List<E> Contain the Same Elements in the Same Order
Passing Empty List as Parameter to JPA Query Throws Error
Http Post Request With Content Type Application/X-Www-Form-Urlencoded Not Working in Spring