I'm writing a program that reads in a list of numbers. Such as:
45
63
74g
34.7
75
I simply want my program to skip lines that contain any letters in them. Any help would be greatly appreciated. Thanks!
If it makes a difference, here is my code:
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
catch (NumberFormatException err) {
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
When an exception is thrown, execution jumps to the catch block. In what you have, this is after the loop, so the loop doesn't continue, just add a try around parseInt.
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
try{
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
} catch( NumberFormatException nfe )
{
// maybe log it?
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
// catch (NumberFormatException err) {}
finally {
try {
if (reader != null){
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
Also note, you are using Integer.parseInt which will throw an exception with the input "34.7", so maybe you wish to use Double.parseDouble
How about using a regex? Like for example:
if (currentLine.matches(".*[a-zA-Z].*")) {
//letters contained.
} else {
//no letters contained.
}
see regex demo: http://regex101.com/r/rQ6oR1
you can try this :
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
if (isInt(num)) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
public boolean isInt(String num)
{
boolean flag=false;
try
{
int i=Integer.parseInt(num);
flag=true;
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
return flag;
}
}
Based on your comment. if your file contain one number per line . then this would be easiest way.
Scanner sc = new Scanner(new File("QuizScores.txt"));
int sum = 0;
int count =0;
while( sc.hasNext()){
String tmpNum = sc.next();
if (isNumeric(tmpNum)){
sum = sum + (int) Double.parseDouble(tmpNum); // if you want t capture in double use Double instead.
count++;
}
}
System.out.println(sum/count);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
Related
I did not want to repeat the other question, I solved a problem in which I post the most common word in the text, but I have a problem, it does not work if I have more blank lines, how can I solve it?
I tried other ways of stackoverflow, but failed.
This is my code.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] input = currentLine.replaceAll("[^a-zA-Z-\"\\n\\n\", \"\\n\"]", " ").toLowerCase().split(" ");
for (int i = 0; i < input.length; i++) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
currentLine = reader.readLine();
}
String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
if (m.getValue() > count) {
mostRepeatedWord = m.getKey();
count = m.getValue();
} else if (m.getValue() == count) {
String key = m.getKey();
if (key.compareTo(mostRepeatedWord) < 0) {
mostRepeatedWord = key;
}
}
}
System.out.println(mostRepeatedWord);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Modify your for loop so that you're not adding to your map on a blank line.
for (int i = 0; i < input.length; i++) {
// Skip the blank lines
if (!input[i].trim().equals("")) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
}
I have a simple java class that uses System.err.println to debug the code as it executes. the purpuse of the class is to find the maximum pairwise product of a given numbers.
following is the code and output.
public class MaxPairwiseProduct {
private static boolean enableLog = true;
static long getMaxPairwiseProductFast(int[] numbers) {
long max_product = 0;
int n = numbers.length;
int firstMaxInt = -1;
int secondMaxInt = -1;
int firstMaxIndex = 0;
int secondMaxIndex = 0;
loge("firstMax initialized :" + firstMaxInt);
loge("secondMax initialized :"+ secondMaxInt);
loge("***********************************************");
for (int firstPassIndex = 1; firstPassIndex < n; firstPassIndex++) {
loge("firstpass : Number " +firstPassIndex);
if (numbers[firstPassIndex] > firstMaxInt )
{
loge("\t firstpass : Found max " +numbers[firstPassIndex]);
firstMaxInt = numbers[firstPassIndex] ;
firstMaxIndex = firstPassIndex ;
}
}
for (int secondPassIndex = 1; secondPassIndex < n; secondPassIndex++) {
loge("secondPassIndex : Number " +numbers[secondPassIndex]);
if (numbers[secondPassIndex] > secondMaxInt && secondPassIndex != firstMaxIndex )
{
loge("\t firstpass : Found max " +secondPassIndex);
secondMaxInt = numbers[secondPassIndex] ;
secondMaxIndex = secondPassIndex;
}
}
max_product = firstMaxInt * secondMaxInt ;
return max_product;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println(getMaxPairwiseProductFast(numbers));
}
private static void loge(String s)
{
if (enableLog == true)
{
System.err.println(s);
}
}
private static void log(String s)
{
if (enableLog == true)
{
System.out.println(s);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new
InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
the output is (from the output window in Netbeans):
It is clear that the output messages is not in the intended order.
It appears to me as if the program execute in multi-thread.
what is the error in my code and why it output like this ?
I found the answer here
Delay in running thread due to system.out.println statement
a stackOverflow member guided me to this.
basically , changing the loge method to the following fixed the issue.
private static void loge(String s)
{
if (enableLog == true)
{
System.err.println(s);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MaxPairwiseProduct.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I have written this code but I have to change this from saving in list to saving in array. So that every animal in my txt file should have its position in the array. There is 10 animals. Anyone can help?
public class Main {
public static void main(String[] args) {
String line = "";
int count = 0;
List<String> arrayList = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
while (line != null) {
count++;
line = br.readLine();
if (line == null)
break;
if (count == 3 || count % 3 == 1 && !line.equals("1") &&
!line.equals("5") && !line.equals("10"));
arrayList.add(line);
}
System.out.println(Arrays.toString(arrayList.toArray()));
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}catch (IOException e) {
System.err.println("Cannot read this file.");
}
}
}
With Java8+, you could do :
Path path = Paths.get("Zoo.txt");
String[] animals = Files.lines(path, Charset.defaultCharset()).toArray(String[]::new);
Based on #Ryan suggestion :
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "";
int count = 0;
int countLineNumber=0; //to count line numbers
List<String> arrayList = new ArrayList();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
while (line != null) {
count++;
line = br.readLine();
if (line == null)
break;
if (count == 3 || count % 3 == 1 && !line.equals("1") &&
!line.equals("5") && !line.equals("10"));
arrayList.add(line);
countLineNumber++;
}
//System.out.println(countLineNumber);
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}catch (IOException e) {
System.err.println("Cannot read this file.");
}
//getting elements from arayList saving them into a array
String[] array=new String[countLineNumber];
for(int i=0;i<countLineNumber;i++){
array[i]=arrayList.get(i);
}
//display element in array
for(int k=0;k<array.length;k++){
System.out.println(array[k]);
}
}
I'm developing a tool to analyse and give some statistics about other people's source code, the tool will be able to recognize many things in the code! Right now am stuck at counting the number of comments on the code, my current code is:
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
To check the code, I am using a test file. But the code is giving me the wrong result in both files, for example; I am getting three in the following file
Yes
//comment
yes
yes
/*
if
random
test
test
*/
While the answer should be two comments!
In the following file, it's showing me that I have five comments while I still actually have two
Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/
The whole approach is flawed. You need to parse the source file properly, at least you need to keep track properly of quotes and nesting of "/*". Note that any comment character combination can appear inside statements like:
System.out.println("// this is *not* a line comment");
String s = "*/ this is not the end of a block comment";
and so on. Then there is the weird behavior with character escape sequences being processed before the file is interpreted:
\u002F* this is a valid comment */
Its not that easy to determine what is a comment and whats not :) I strongly suggest you look for an open source parser solution for java sources.
I think you have a problem in that comments can occur inside or at the end of a line as well...
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.contains("//")) {
count++;
} else if (line.contains("/*")) {
count++;
while (!line.contains("*/") && !(line = br.readLine()).contains("*/"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
Of course the problem here is what if the "//", "/* " or "*/" sequences occur within quoted text....?
I haven't tested your code however, I believe this should work :
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while ((line = br.readLine())!=null && !line.endsWith("'*\'"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
When you meet the /* you should increment the counter and skip the comment section.
Guys here is a easy solution. Just download the cloc software from this link for windows.
This software support every language & can accept folder of files also. Put your folder and cloc in same place and open cmd type this command
cloc-(version no).exe (folder name)
cloc-1.64.exe main
and have the no of lines, blank line and total no of lines in the code.
For more detail see this: http://cloc.sourceforge.net/
enter code here
public class FilterInputStreamDemo {
public static void main(String[] args) {
String line = "";
int comment_count = 0;
int line_count = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
line_count++;
if (line.startsWith("//")) {
comment_count++;
single_comment_count++;
} else if (line.startsWith("/*")) {
comment_count++;
multiple_comment_count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
comment_count++;
multiple_comment_count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("comment_count=" + comment_count);
}
}
package com.usaa.training;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CommentsReading {
public static void main(String[] args) {
String line = "";
int number_of_blocks = 0;
int comment_count = 0;
int line_count = 0;
int TODO = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
File file = new File("C:\\code\\InvolvedPartyBasicInfoMapper.java");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line_count++;
;
if (line.contains("//")) {
if (line.contains("TODO")){
TODO++;
}
comment_count++;
single_comment_count++;
} else if (line.contains("/*") )
{
if (line.contains("TODO")){
TODO++;
}
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
break;
}
while (!(line = br.readLine()).endsWith("'*/'") )
{
line_count++;
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
number_of_blocks++;
break;
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total # of Lines = " + line_count);
System.out.println("Total # of Comment Lines= " +comment_count);
System.out.println("Total # of Single line Comments= " +single_comment_count );
System.out.println("Total # of Comment lines with Block Comments = " +multiple_comment_count );
System.out.println("Total # of Block line Comments = " +number_of_blocks);
System.out.println("No of TODO's = " +TODO);
}
}
I used reverse a string, but now need the final document is the principle, and vice versa:
Hello
Bye
to
Bye
hello
and not:
olleH
eyB
As I do this?
This is my source:
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
String s;
try {
while ((s = br.readLine()) != null) {
StringBuilder reverse = new StringBuilder(s);
String sCadenaInvertida = reverse.reverse().toString();
System.out.println(sCadenaInvertida);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks!!
Just put everything in an ArrayList and use Collections.reverse
http://www.java2s.com/Code/Java/Collections-Data-Structure/ReverseorderofallelementsofJavaArrayList.htm
pseudo code:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("Bye");
Collections.reverse(arrayList);
System.out.println(arrayList);
Add the items to an array (first come first serve) then traverse the array in reverse
for (into I = array.length; i >= 0; i--) {
//print array[i]
}
Alternatively you can use an ArrayList if you don't know the number of lines in the document
ArrayList<String> theWords= new ArrayList<String>();
while ((s = br.readLine()) != null) {
//split line into words
String[] parts = s.split("\\s+"):
//for each word append to arraylist
for(String s : parts)
{
theWords.append(s);
} //end for loop
} //end while loop
// iterate array, from size-1 to 0
int theWordsSize = theWords.size()--;
for(int i= theWordsSize; i >= 0; i--)
{
System.out.println(theWords.get(i));
} //end for loop
here the answer, It was easy:
public class Reverse2 {
public static void main(String[] args) {
if(args.length != 1){
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
ArrayList<String> lista = new ArrayList<String>();
String s;
try {
while((s=br.readLine()) != null){
lista.add(s);
}
for(int i= lista.size()-1;i>=0;i--){
System.out.println(lista.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
thanks for all the possible solutions