I have this code where I have an list of each sentence from the scanned text file, and it prints the sentences that end with ; and , And I'm wondering if I could make another array of each word in each sentence, so that I can scan the words instead of the sentences?
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[]) throws IOException {
Scanner sf = new Scanner(new File("amazing.txt"));
List<String> text = new ArrayList<>();
while (sf.hasNextLine())
{
String current = sf.nextLine();
if (current.endsWith(",") || current.endsWith(";") || current.endsWith("!"))
System.out.println(current);
}
sf.close();
}
}
Usually we don't use Scanner Object to read a file as it's not a Best Practice check out this example as #Zabuzard pointed out .
Solution:
Scanner sf = new Scanner(new File("amazing.txt"));
List < String > text = new ArrayList < > ();
while (sf.hasNextLine()) {
String current = sf.nextLine();
// if (current.endsWith(",") || current.endsWith(";") || current.endsWith("!"))
// System.out.println(current);
String all_words[];
all_words = current.split(" "); //create an array with all strings seperated with space for each line
System.out.print("All words of the line:");
for (int i = 0; i < all_words.length; i++) {
System.out.print(all_words[i] + " ");
//after you do in this section your checks, add it to the List
}
System.out.println();
}
sf.close();
This will print all the words of each line. You can continue on with implementing your login in your case scenario and trim the strings to remove the special characters as well.
Then you can proceed by adding it to your List<String>.
Related
import java.util.Scanner;
import java.util.ArrayList;
public class kek2 {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
ArrayList<String> wordlist = new ArrayList <String>();
while(true) {
System.out.println("Type a word: ");
String word = imeskanera.nextLine();
int lenght =wordlist.size();
if(word.equals("")) {
for(int i = 0;i<lenght; i++) {
System.out.println(wordlist.get(lenght-i));}
break;
}
wordlist.add(word);
}
}
}
Im trying to print out the array in reversed order but i get error in (lenght-i) part, everything looks fine to me, am'I doing something wrong that Java doesnt allow?
It may be better to limit while loop to reading the inputs and when user is done, print the list contents in any desired order.
Scanner imeskanera = new Scanner(System.in);
List<String> wordlist = new ArrayList<>();
String word;
System.out.println("Type a word: ");
while(!(word = imeskanera.nextLine()).isEmpty()) {
wordlist.add(word);
System.out.println("Type a word: ");
}
for (int i = wordlist.size(); i-- > 0;) { // index decremented in condition
System.out.println(wordlist.get(i));
}
Or ListIterator may be retrieved using List::listIterator and its methods hasPrevious() / previous() can be used to iterate in reverse direction -- however, the size of list is needed anyway:
for (ListIterator i = wordlist.listIterator(wordlist.size()); i.hasPrevious();) {
System.out.println(i.previous());
}
I need to take a file that a user chooses and scan that file for a letter that a user chooses, and then output how many times the user's letter appeared in the file.
I know how to get the user input and get the user to select a file, as well as scanning the file, but I cannot figure out a way to check each character within a file for a specific letter. The closest I have been able to come is this:
public class FileLetterCounter
{
public static void main(String[] args) throws IOException
{
int count = 0, stringLength;
String file, a = "a";
Scanner fileScanner, letterScan;
ArrayList<String> line = new ArrayList<String>();
fileScanner = new Scanner(new File("lab6.txt"));
while (fileScanner.hasNext())
{
line.add(fileScanner.next());
for (int index = 0; index < line.length(); index ++)
{
if (line.get(index).contains(a));
{
count++;
}
}
}
}
}
This doesn't work because the length() method does not work on an ArrayList, and I am unsure of how to approach the problem. I am asking this question because I found a similar one, but the recommended solution was to use what I have right now in my for loop (line.length()), but this won't work.
Instead of adding it to the list, just scan the text into a string, iterate each character of the string to check if the character matches with the search character, and increase the value of count for each match.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the char to search: ");
char searchChar = keyboard.next().charAt(0);
Scanner fileScanner = new Scanner(new File("lab6.txt"));
while (fileScanner.hasNext()) {
String text = fileScanner.next();
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) == searchChar) {
count++;
}
}
}
System.out.println("The character " + searchChar + " appears " + count + " times in the file.");
fileScanner.close();
}
}
Look at this implementation with Streams. Looks pretty nice to me. Additionally do not forget to provide Charset, otherwise you could get unexpected results.
public static long countCharacterInFile(Path file, char ch, Charset charset) throws IOException {
try (Stream<String> stream = Files.lines(file, charset)) {
return stream.map(String::codePoints)
.flatMap(IntStream::boxed)
.filter(c -> c == ch)
.count();
}
}
Output:
Path file = Paths.get("lab6.txt");
System.out.println(countCharacterInFile(file, 'e', StandardCharsets.UTF_8)); // 666
Assuming you are trying to search a character in the whole file. Modified the code by removing all those unnecessary variables. Also I don't see any use of adding each line to a list of strings.
Idea is to scan through each line and increment count if the current character character matches your character
public class FileLetterCounter
{
public static void main(String[] args) throws IOException
{
int count = 0;
char targetLetter = 'a'; //define whatever you want or take it from user input
Scanner fileScanner = new Scanner(new File("lab6.txt"));
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
for(int i=0; i<line.length(); i++) {
if(line.charAt(i) == targetLetter) {
count++;
}
}
}
System.out.println(count);
}
}
We have file with a few words, try safe word with word have 2,4,6 or 8 letters in array but then save in screen write null and null+good word.
What did I write wrong, and why does it show null?
public static void lyginis () throws IOException {
Path path = Paths.get("words.txt");
Scanner scanner = new Scanner(path);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner1 = new Scanner(path);
String[] atrinkti = new String[kiek];
String scan = "";
for (int i = 0; i < kiek; i++) {
scan = scanner1.next();
if (scan.length() % 2 == 0) {
atrinkti[i] += scan ;
}
System.out.println(atrinkti[i]);
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner2 = new Scanner(file);
String[] atrinkti = new String[kiek];
String word = "";
for (int i = 0; i < kiek; i++) {
word = scanner2.next();
if (word.length() % 2 == 0) {
atrinkti[i] = word;
System.out.println(atrinkti[i]);
}
}
}
}
Output
$ cat words.txt
hi
hello
whats up
chicken
duck
goose
$ javac Hello.java; java Hello
hi
up
duck
The issues were:
Path was used instead of File
The += was used within the if statement instead of just =
The System.out.println() function was called outside of the if statement so when the word's length was not divisible by 2, the current array element would print the default initialized value of the array of null
User will input a sequence of numbers, integers separated with commas, like this 2,3,1,245,2,75. How can I find if there is a number that is not duplicated and print it back ? I got so far this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String line;
String[] line2;
line = reader.nextLine();
line2= line.split(",");
int n=0;
for(int i=0; i<line2.length; i++){
System.out.println(line2[n]);
n++;
}
}
What this does is: stores the input in string "line" and then removes the commas and stores only the numbers in "line2". And then prints the content of line2 but thats not necessary I did it just to see if it works, what i need to print is just the unique number.
You could stream the array you get from splitting the strings, create a frequency map of it, and keep just the numbers that appear once:
List<String> unique =
Arrays.stream(input.split(","))
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Iterate over the array and check whether there are copies for each element.
for(String x:line2){
if(unique(x, line2))
System.out.println(x+" is a unique number");
}
Here's the unique() function that checks for copies.
private static boolean unique(String x, String[] line2){
for(String i:line2){
if(i.equals(x))
return false;
}
return true;
}
You can put the numbers in a List<> and then use Collections.frequency(), which is more efficient than iterating over the collection yourself:
Scanner reader = new Scanner(System.in);
String line;
String[] line2;
line = reader.nextLine();
line2= line.split(",");
List<Integer> list = new ArrayList<>();
for(int i=0; i<line2.length; i++){
list.add(Integer.parseInt(line2[i]));
}
boolean flag = true;
for(int a : list){
if(Collections.frequency(list, a)!=1){
flag = false;
}
}
NOTE: this might throw NumberFormatException if the user put something which isn't a number
With Java 8's Streams: I first filter the Array of Strings to remove all duplicates, than check if the string is unique and finally print all unique Strings out.
import java.util.Scanner;
import java.util.stream.Stream;
public class UniqueNumberScanner {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String line;
String[] line2;
line = reader.nextLine();
line2 = line.split(",");
Stream.of(line2).distinct().filter(item -> Stream.of(line2).filter(item::equals).count() == 1).forEach(System.out::println);
}
}
I am working on an assignment that wants me to create a program that accepts a text file with words in it, goes through every word, and then outputs the word with the most amount of double letters. So if a text file had 2 words, (past and progressive for example), it would output progressive. My problem is getting the program to compare each letter in a word. Specifically I cant seem to figure out how to split each word into its letters. Here is what I have so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Doubles {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
///Prompts the user to give a file.
System.out.println("Enter the location of your file...");
String location = keyboard.next();
Scanner file = null;
List<String> list = new ArrayList<String>();
///If the the file location is wrong, give an error.
try {
file = new Scanner(new File(location));
} catch (FileNotFoundException e) {
System.out.println("Error: File not found");
System.exit(1);
}
while(file.hasNext()){
String word = file.nextLine();
list.add(word);
}
///System.out.println(list);
keyboard.close();
doublefinder(list);
}
private static void doublefinder(List<String> list) {
///Code to separate and compare letters.
}
}
I have tried many different approaches but I can't seem to find a solution. Any help would be much appreciated.
You can use the .toCharArray method to create a char array where each element is a letter of the word.
http://crunchify.com/java-simple-way-to-convert-string-to-char-array/
An example implementation is as follows:
public static boolean isDoubleword(String str){
char[] letters = str.toCharArray();
for(int i = 0; i< letters.length-1; i++){
if(letters[i] == letters[i+1])return true;
}
return false;
}
The above function takes a string and returns if the string is a double word.
The method could look like that
private String doubleFinder(List<String> list){
int maxDoubleLetters = 0;
int maxDoubleLettersID = 0; // the position of the word in your list
for(int n = 0; n < list.size(); n++){ // cycle throught each word
String word = list.get(n); // get a word from the list
char[] letters = word.toCharArray(); // split the word into letters
int doubleLetters = 0;
for(int i = 1; i < letters.length; i++){ // search for all double letters
if(letters[i] == letters[i-1]) doubleLetters++;
}
if(doubleLetters > maxDoubleLetters){
maxDoubleLetters = doubleLetters;
maxDoubleLettersID = n;
}
}
if(maxDoubleLetters > 0)
return list.get(maxDoubleLetters);
else
return null;
}
The method shown above will return the word with the highest number of double letters. If the file does not contain any words with double letters the method will return null.
Note: This will not work for words containing triple letters.
If you have any more questions fell free to ask in the comment section.
Arem,
The approach that I would use is to make a method that takes in a string and returns the number of double letters. This can be accomplished using the String.toCharArray(); function. You can then iterate through that array to compare the letters to see how many double letters there are in a string.
e.g.
public static int numDoubles(String str) {
int numDoubles = 0;
char[] blah = str.toCharArray()
for(int i = 0; i < str.length(); i++ {
//if the character == nextChar
numDoubles++;
}
return numDoubles;
}
Use that return value to compare your strings.