Using loops and if statements with the Scanner class - java

I'm trying to write a program that scans through a text file line by line and adds certain integers together on each line. The text file in question has the following format:
01-Jan-2012 ED521D 4 100 30 1499 M N Brewer
02-Jan-2012 ED925H 5 488 30 1499 A B Saini
02-Jan-2012 JF560D 3 275 40 949 M S Cooper
02-Jan-2012 ZK201U 1 359 40 474 R S Chadwick
My aim is to add up the numbers in the third column (4,5,3) if the character in the penultimate column is either an "M" or "A". So the program should output 12 using the text file above. Here's what i've got so far.
public static void main(String[] args) throws IOException {
String filename = "policy.txt";
Scanner input = null;
double itemAmount = 0;
String text = "";
int policyCount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String read = input.nextLine();
String clean = read.replaceAll("\\P{Print}", "");
char policyType = clean.charAt(59);
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
if (policyType == 'A' || policyType == 'M' ){
policyCount++;
}
}
else if(input.hasNext()){
text = input.next();
}
}
System.out.println(policyCount);
System.out.println(itemAmount);
}

This seems to work:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException
{
String filename = "policy.txt";
Scanner input = null;
double itemAmount = 0;
int policyCount = 0;
input = new Scanner(new File(filename));
while (input.hasNext())
{
String read = input.nextLine();
String clean = read.replaceAll("\\P{Print}", "");
char policyType = clean.charAt(59);
if (policyType == 'A' || policyType == 'M')
{
policyCount++;
itemAmount += Character.getNumericValue((clean.charAt(24)));
}
}
input.close();
System.out.println(policyCount);
System.out.println(itemAmount);
}
}
Note that this will only work for single digit numbers in the 24th column. If it might contain more digits you'll have to do a substring on clean and then use Double.valueOf().

I guess would want to put
itemAmount = itemAmount + input.nextInt();
Inside
if (policyType == 'A' || policyType == 'M' ){
}
Hope this helps.
Also, you have not used 'read' String. You are seemingly skipping lines.
Use read.split(" ") to get array of tokens.
Then use 3rd token to parse as Integer.
Add it if the condition is true.

Related

If condition is met -> scan input into one variable. If not -> scan input into another variable

Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}

Sentence Capitalizer with specific requirement

It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}
Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}

How to Extract Multiple words from a string using IndexOf and substring Java?

I have a file i imported through system, Now i am stuck. Using while loops and if statements, and WITHOUT the help of the Split() method, How could i first, Read the file, line by line with the scanner? Then second how could i pull the words out one by one, As i pull out one word, A variable, countWords has to increase by one, say there is 5 words in a string, I would need to run through the loop 5 times and countWords would become 5.
This is the code i have so far, Kind of crappy.
import java.util.Scanner;
import java.io.*;
class Assignmentfive
{
private static final String String = null;
public static void main(String[] args) throws FileNotFoundException
{
Scanner scan = new Scanner(new File("asgn5data.txt"));
int educationLevel = 0;
String fileRead = "";
int wordCount = 0;
while (scan.hasNext() && !fileRead.contains("."))
{
fileRead = scan.nextLine();
int index = fileRead.indexOf(" ");
String strA = fileRead.substring(index);
System.out.print(strA);
wordCount++;
}
There is more to my code, however it is just a few calculations commented out.
Thanks!
Here is how I would refactor your while loop to correctly extract, print, and count all words in a sentence:
while (scan.hasNext()) {
int wordCount = 0;
int numChars = 0;
fileRead = scan.nextLine();
// Note: I add an extra space at the end of the input sentence
// so that the while loop will pick up on the last word.
if (fileRead.charAt(fileRead.length() - 1) == '.') {
fileRead = fileRead.substring(0, fileRead.length() - 1) + " ";
}
else {
fileRead = fileRead + " ";
}
int index = fileRead.indexOf(" ");
do {
String strA = fileRead.substring(0, index);
System.out.print(strA + " ");
fileRead = fileRead.substring(index+1, fileRead.length());
index = fileRead.indexOf(" ");
wordCount++;
numChars += strA.length();
} while (index != -1);
// here is your computation.
if (wordCount > 0) {
double result = (double)numChars / wordCount; // average length of words
result = Math.pow(result, 2.0); // square the average
result = wordCount * result; // multiply by number of words
System.out.println(result); // output this number
}
}
I tested this code by hard-coding the string fileRead to be your first sentence The cat is black.. I got the following output.
Output:
The
cat
is
black

count characters, words and lines in file

This should count number of lines, words and characters into file.
But it doesn't work. From output it shows only 0.
Code:
public static void main(String[] args) throws IOException {
int ch;
boolean prev = true;
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
// count the characters of the file till the end
while(in.hasNext()) {
ch = in.next().charAt(0);
if (ch != ' ') ++charsCount;
if (!prev && ch == ' ') ++wordsCount;
// don't count if previous char is space
if (ch == ' ')
prev = true;
else
prev = false;
if (ch == '\n') ++linesCount;
}
//display the count of characters, words, and lines
charsCount -= linesCount * 2;
wordsCount += linesCount;
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
in.close();
}
I can't understand what's going on.
Any suggestions?
Different approach. Using strings to find line,word and character counts:
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
while (in.hasNext()) {
String tmpStr = in.nextLine();
if (!tmpStr.equalsIgnoreCase("")) {
String replaceAll = tmpStr.replaceAll("\\s+", "");
charsCount += replaceAll.length();
wordsCount += tmpStr.split(" ").length;
}
++linesCount;
}
//display the count of characters, words, and lines
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
in.close();
}
Note:
For other encoding styles use new Scanner(new File(selectedFile), "###"); in place of new Scanner(selectedFile);.
### is the Character set to needed. Refer this and wiki
Your code is looking at only the first characters of default tokens (words) in the file.
When you do this ch = in.next().charAt(0), it gets you the first character of a token (word), and the scanner moves forward to the next token (skipping rest of that token).
You have a couple of issues in here.
First is the test for the end of line is going to cause problems since it usually isn't a single character denoting end of line. Read http://en.wikipedia.org/wiki/End-of-line for more detail on this issue.
The whitespace character between words can be more than just the ASCII 32 (space) value. Consider tabs as one case. You want to check for Character.isWhitespace() more than likely.
You could also solve the end of line issues with two scanners found in How to check the end of line using Scanner?
Here is a quick hack on the code you provided along with input and output.
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
public final class TextApp {
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner fileScanner = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
fileScanner = new Scanner(selectedFile);
}
while (fileScanner.hasNextLine()) {
linesCount++;
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
// count the characters of the file till the end
while(lineScanner.hasNext()) {
wordsCount++;
String word = lineScanner.next();
charsCount += word.length();
}
lineScanner.close();
}
//display the count of characters, words, and lines
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
fileScanner.close();
}
}
Here is the test file input:
$ cat ../test.txt
test text goes here
and here
Here is the output:
$ javac TextApp.java
$ java TextApp
# of chars: 23
# of words: 6
# of lines: 2
$ wc test.txt
2 6 29 test.txt
The difference between character count is due to not counting whitespace characters which appears to be what you were trying to do in the original code.
I hope that helps out.
You could store every line in a List<String> and then linesCount = list.size().
Calculating charsCount:
for(final String line : lines)
charsCount += line.length();
Calculating wordsCount:
for(final String line : lines)
wordsCount += line.split(" +").length;
It would probably be a wise idea to combine these calculations together as opposed to doing them seperately.
Use Scanner methods:
int lines = 0;
int words = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
Scanner lineScanner = new Scanner(in.nextLine());
lineScanner.useDelimiter(" ");
while(lineScanner.hasNext()) {
words++;
chars += lineScanner.next().length();
}
}
Looks like everyone is suggesting you an alternative,
The flaw with your logic is, you are not looping through the all the characters for the entire line. You are just looping through the first character of every line.
ch = in.next().charAt(0);
Also, what does 2 in charsCount -= linesCount * 2; represent?
You might also want to include a try-catch block, while accessing a file.
try {
in = new Scanner(selectedFile);
} catch (FileNotFoundException e) {}
Maybe my code will help you...everything work correct
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class LineWordChar {
public static void main(String[] args) throws IOException {
// Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";
// while next lines are present in file int linesi will add 1
while ((lines=bf.readLine())!=null){
linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
while (st.hasMoreTokens()){
`enter code here` s = st.nextToken();
words++;
// We take every word during separation and count number of char in this words
for (int i = 0; i < s.length(); i++) {
chars++;}
}
System.out.println("Number of lines: "+linesi);
System.out.println("Number of words: "+words);
System.out.print("Number of chars: "+chars);
}
}
public class WordCount {
/**
* #return HashMap a map containing the Character count, Word count and
* Sentence count
* #throws FileNotFoundException
*
*/
public static void main() throws FileNotFoundException {
lineNumber=2; // as u want
File f = null;
ArrayList<Integer> list=new ArrayList<Integer>();
f = new File("file.txt");
Scanner sc = new Scanner(f);
int totalLines=0;
int totalWords=0;
int totalChars=0;
int totalSentences=0;
while(sc.hasNextLine())
{
totalLines++;
if(totalLines==lineNumber){
String line = sc.nextLine();
totalChars += line.length();
totalWords += new StringTokenizer(line, " ,").countTokens(); //line.split("\\s").length;
totalSentences += line.split("\\.").length;
break;
}
sc.nextLine();
}
list.add(totalChars);
list.add(totalWords);
list.add(totalSentences);
System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);
}
}

How to count the key characters?

I have the following code:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("now input a letter to be replaced");
String letter = input.next();
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
}
}
the code needs to do three things take a string and a letter and :
replace the key letter in the string with "-"
remove the key letter of the string
count the amount of times the key letter appears.
At present I have two problems. I don't know how to count the amount of times the letter
appears because technically it is a string and not a char and i do not know how to count
strings. Second, I need to make it so that if the strings are not of the desired length it
simply asks again instead of exiting the program. I have tried to use the getString() method but for some reason it always says that the method is undefined.
For issue #1:
Near the top of the main method:
int count = 0;
After user3 is assigned:
count += (user3.length() - user.length());
With full credit to user1324109 for their solution to issue #1, here is how you can solve your issue #2:
import java.util.Scanner;
public class StringReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user1 = "", user2 = "", user3 = "";
int count = 0;
while(user1.equals("") || user1.length() < 7) {
System.out.println("Input a string");
user1 = input.nextLine();
}
if(!user1.equals("")) {
System.out.println("now input a letter to be replaced");
String letter = input.next();
user2 = user1.replace(letter, "-");
user3 = user1.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
count += (user1.length() - user3.length());
System.out.println("letter was found to be present "+count+" times");
}
}
}
To help with issue #3:
int count = 0;
for(char c : user.toCharArray() ){
if ( c == letter.charAt(0)) count++;
}
System.out.println("Number of occurences: "+count);

Categories