Using Java: The objective of the first part of this assignment is to introduce y
ID: 3871186 • Letter: U
Question
Using Java:
The objective of the first part of this assignment is to introduce you to abstractions that allow your program to communicate with the outside world. The four libraries that implement these abstractions include System.in, System.out, and JavaFX. These I/O libraries are great examples of the power of abstraction because they can be tied to different physical devices at different times without making any changes to the programs.
Write a program that reads in text from standard input (hint: use Scanner) and prints out the number of words in the text. For the purpose of this exercise, a word is a sequence of non-whitespace characters that is surrounded by whitespace. Once complete, add an option to include a file path as an argument. If a file is provided read the file using, for example BufferedReader, otherwise use the standard input as before.
Explanation / Answer
import java.io.File;
import java.util.Scanner;
public class ReadData {
/**
* method to count the words
*
* @param scanner
* @return
*/
public static int countWordsFrom(Scanner scanner) {
int countWords = 0;
while (scanner.hasNext()) {
scanner.next();
countWords++;
}
return countWords;
}
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.println("1. Using Files 2. Using Text");
System.out.print("Enter the choice: ");
int ch = scanner.nextInt();
int countWords = 0;
switch (ch) {
case 1:
System.out.print("Enter the File Name:");
String fileName = scanner.next();
scanner = new Scanner(new File(fileName));
countWords = countWordsFrom(scanner);
System.out.println("Number of words :" + countWords);
break;
case 2:
scanner.nextLine();
System.out.print("Enter the text:");
String text = scanner.nextLine();
scanner = new Scanner(text);
countWords = countWordsFrom(scanner);
System.out.println("Number of words :" + countWords);
break;
default:
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
OUTPUT 1:
1. Using Files
2. Using Text
Enter the choice: 2
Enter the text:This is a Text
Number of words :4
OUTPUT 2:
1. Using Files
2. Using Text
Enter the choice: 1
Enter the File Name:inputtext.txt
Number of words :20
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.