Scan and put it to Array - java

I want scan sentence and count how many word is. And than put the sentence to Array. And print it.
It works until System.out.println("단어개수 : " + count);
but it doesn't work after that.
import java.util.Scanner;
public class Midterm_HW00 {
public static void main(String[] args) {
System.out.println("Insert sentence: ");
Scanner scanner = new Scanner(System.in);
int count =1;
String sentence = scanner.nextLine(); //문자열 읽기
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)==' ') { //단어 개수를 띄어쓰기 개수로 계산
count++;
}
}
System.out.println("단어 개수: " + count);
String[] wordArray = new String[30]; //배열 선언
int word = wordArray.length;
for(int j=0; j<word; j++){
wordArray[j] = scanner.next();
System.out.println("" + wordArray[j]);
scanner.close();
}
}
}

you can get all this by using simple method:
String[] array = yourString.split(" ");
int amountOfWords = array.length;

Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
String[] words = sentence.split("[ ]+");
System.out.println("단어 개수: " + words.length);
for(String word : words){
System.out.println(word);
}

you can use string split by a space to generate an array like this String[] wordArray = sentence.split("\\s+");
code :
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Insert sentence: ");
Scanner scanner = new Scanner(System.in);
int count =1;
String sentence = scanner.nextLine(); //문자열 읽기
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)==' ') { //단어 개수를 띄어쓰기 개수로 계산
count++;
}
}
System.out.println("단어 개수: " + count);
String[] wordArray = sentence.split("\\s+"); //배열 선언
for(int j=0; j<wordArray.length; j++){
System.out.println("" + wordArray[j]);
}
}

import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Insert sentence: ");
Scanner scanner = new Scanner(System.in);
int count =1;
String sentence = scanner.nextLine();
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)==' ') {
count++;
}
}
System.out.println("단어 개수: " + count);
String[] wordArray = new String[] {sentence};
for(int j=0; j<count; j++){
System.out.println("" + wordArray[j]);
scanner.close();
}
}
}

import java.util.*;
public class Solution {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int count = 1;
String sentence = sc.nextLine();
// finding the number of word
for (int i=0; i<sentence.length(); i++) {
if (sentence.charAt(i) == ' ')
count += 1;
}
System.out.println("The count is : " + count);
// store the sentence to a string array using split(split by the space)
String [] sentenceToArray = sentence.split(" ");
// print all elements inside the array
for (int i=0; i<sentenceToArray.length; i++)
System.out.print(sentenceToArray[i]);
}
}

Related

Need to print a string array

My task is to read the strings by input, and then display the strings that have more than 4 vowels in each. I have this code:
import java.util.Scanner;
public class Main {
static boolean vowelChecker(char a) {
a = Character.toLowerCase(a);
return (a=='a' || a=='e' || a=='i' || a=='o' || a=='u' || a=='y');
}
static int counter(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++)
if (vowelChecker(str.charAt(i))) {
++count;
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
String str = scanner.nextLine();
int b = counter(str);
if (b > 4) {
System.out.println("What do I write here?");
}
}
}
And my question is: how to correctly write the code so that the output would be strings from input that have more than 4 vowels?
import java.util.Scanner;
public class Test {
private static final char[] VOWELS = new char[]{'a', 'e', 'i', 'o', 'u', 'y'};
public static void main(String[] args) {
// Initialize and open a new Scanner
final Scanner scanner = new Scanner(System.in);
// Get the number of lines we want to analyze
System.out.print("Enter the number of elements you want to store: ");
final int n = Integer.parseInt(scanner.nextLine());
// Get all the lines from the user
System.out.println("Enter the elements of the array: ");
final String[] lines = new String[n];
for(int i = 0; i < n; i++) {
lines[i]=scanner.nextLine();
}
// Close the Scanner
scanner.close();
// Check each line, count the number of vowels, and print the line if it has more than 4 vowels.
System.out.println("\nInputs that have more than 4 vowels");
for(int i = 0; i < n; i++) {
if (countVowels(lines[i]) > 4) {
System.out.println(lines[i]);
}
}
}
private static boolean isVowel(char a) {
for (int i = 0; i < VOWELS.length; i++) {
if (Character.toLowerCase(a) == VOWELS[i]) {
return true;
}
}
return false;
}
private static int countVowels(final String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
count++;
}
}
return count;
}
}
Like others have pointed out, you never read from the array.
Read for each of the strings, if the counter() returns a value larger than 4, we want to print it. So, this could do the trick:
for(int i=0; i<n; i++)
{
if (counter(array[i]) > 4)
System.out.println(array[i]);
}
Using nextInt won't absorb the newline character \n, that's why you are inputting 1 string less. There are some workarounds that you can read about here.
So this first part makes sense :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store:
");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
after this part I would just do :
for (String s: array) {
if (Objects.isNull(s))
break;
if (count(s) >= 5) {
System.out.println(s);
}
}
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
class Main {
static long counter(String str) {
return Arrays.stream(str.split(""))
.filter(c -> Arrays.asList("a", "e", "i", "o", "u", "y").contains(c.toLowerCase()))
.count();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n = scanner.nextInt();
scanner.nextLine();
String[] array = new String[n];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
String str = scanner.nextLine();
if (counter(str) > 4) {
array[i] = str;
}
}
System.out.println(Arrays.toString(Arrays.stream(array).filter(Objects::nonNull).toArray(String[]::new)));
}
}

Run Time Error_String index out of bound Exception_Printing string odd and even indexes

Code :
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] sa = new String[n];
for(int i=0;i<n;i++){
sa[i] = sc.nextLine();
}
String odd="";
String even="";
for(int i=0;i<n;i++)
{
for(int j=0;j<sa[i].length();j++)
{
if(j%2!=0){
odd = odd+sa[j].charAt(j);
}
else {
even = even+sa[j].charAt(j);
}
}
System.out.println(odd+" "+even);
}
}
}
ISsue : GEtting run time exception while running the code. --> String index out of bound exception
You can try below code. It is because of calling a method like nextInt() before sc.nextLine()
The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for next element.
You need to consume the '\n' before calling nextLine() or You can directly call nextLine() for array size as well.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array size");
int n = Integer.parseInt(sc.nextLine());
String[] sa = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Element "+i);
String val = sc.nextLine();
sa[i]=val;
}
String odd = "";
String even = "";
for (int i = 0; i < n; i++) {
for (int j = 0; j < sa[i].length(); j++) {
if (j % 2 != 0) {
odd = odd + sa[j].charAt(j);
} else {
even = even + sa[j].charAt(j);
}
}
System.out.println(odd + " " + even);
}
}

Dictionary input file and string manipulation

I am writing a program that searches a file imported for a string of characters and length user enters. For example,
"Enter the possible letters in your word: "
Keyboard scans "aeppr"
"Enter the number of letters in your target words:"
"5"
and then proceeds to search my dictionary file and ultimately prints:
1 paper
I was wondering if you can use indexOf or any other methods or classes to display this result. As of now my code only displays words that match the searched letters and length exactly. Any help or advice would be greatly appreciated.
String input;
String altInput;
Scanner inFile = new Scanner(new File("words.txt"));
Scanner scanner = new Scanner(System.in);
String lettersBeingTested;
int numberOfLetters;
System.out.println("Enter the possible letters in your word: ");
lettersBeingTested = scanner.next();
System.out.println("Enter the number of letters in your target words: ");
numberOfLetters = scanner.nextInt();
int count = 0;
while (inFile.hasNext()) {
input = inFile.next();
altInput = "";
for (int i = 0; i < input.length(); i++) {
altInput = altInput + input.charAt(i);
if (input.contains(lettersBeingTested) && altInput.length() == numberOfLetters) {
count++;
System.out.println(count + " " + altInput);
}
}
}
System.out.println("End of list: " + count + " words found");
inFile.close();
}
public static void main(String[] args) throws FileNotFoundException {
findWords(new File("words.txt"));
}
public static void findWords(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the possible letters in your word: ");
String lettersBeingTested = scan.next();
System.out.println("Enter the number of letters in your target words: ");
int numberOfLetters = scan.nextInt();
int[] requiredHistogram = histogram(lettersBeingTested, new int[26]);
Predicate<int[]> predicate = wordHistogram -> {
for (int i = 0; i < requiredHistogram.length; i++)
if (requiredHistogram[i] > 0 && wordHistogram[i] < requiredHistogram[i])
return false;
return true;
};
Set<String> words = findWords(file, predicate, numberOfLetters);
int i = 1;
for (String word : words)
System.out.println(i + " " + word);
System.out.println("End of list: " + words.size() + " words found");
}
}
private static int[] histogram(String str, int[] histogram) {
Arrays.fill(histogram, 0);
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
histogram[str.charAt(i) - 'a']++;
return histogram;
}
private static Set<String> findWords(File file, Predicate<int[]> predicate, int numberOfLetters) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
Set<String> words = new LinkedHashSet<>();
int[] histogram = new int[26];
while (scan.hasNext()) {
String word = scan.next().toLowerCase();
if (word.length() == numberOfLetters && predicate.test(histogram(word, histogram)))
words.add(word);
}
return words;
}
}
This look a bit complicated using histogramm. I think that if lettersBeingTested = "aa", then you're looking for words with at lest 2 'a' in it. Threfore, you have to build a histogram and compare symbol appearance number in the current words and in example one.
P.S.
altInput = altInput + input.charAt(i);
String concatenation within loop flows bad performance. Do look at StringBuilder isntead.

ArrayList not adding String

I'm trying to get a word count of a string entered by a user but I keep getting "0" back as a result. I can't figure out what to do.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
ArrayList<String> A=new ArrayList<String>();
System.out.print("Enter a sentence: ");
String a=reader.next();
int charCount=a.length();
int space;
int period;
int wordCount=0;
//word count\
for (int i=0; i<1; i++){
space=a.indexOf(" ");
if (a.charAt(0)!=' '){
if (space!=-1){
A.add(i, a.substring(0, space-1));
a=a.substring(a.indexOf(" ")+1, charCount-1);
}
if (space==-1&&a.charAt(charCount-1)=='.'){
period=a.indexOf(".");
A.add(i, a.substring(0, period));
}
charCount=a.length();
}
wordCount=A.size();
}
System.out.print("Word Count: "+A.size());
}
Why don't you try like this-
public static void main (String[] args) {
Scanner reader=new Scanner(System.in);
System.out.println("Enter a sentence: ");
String str1 = reader.nextLine();
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}

How to get a user-input string as an array of individual characters?

I want the user to input a string and then each character of that string gets assigned to an element in an array.
Here is my code so far:
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
int arrayLength = name.length();
String ArrayName[] = new String [arrayLength];
for(int counter = 0; counter < arrayLength; counter++){
ArrayName[counter] = name.substring(counter);
System.out.println("Element No" + counter + ": " + name.substring(counter));
}
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
int arrayLength = name.length();
String ArrayName[] = new String [arrayLength];
char[] chars = name.toCharArray();
for(int counter = 0; counter < arrayLength; counter++) {
ArrayName[counter] = chars[counter] + "";
System.out.println("Element No" + counter + ": " + name.substring(counter));
}
}
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
int arrayLength = name.length();
int temp = 1;
String ArrayName[] = new String [arrayLength];
for(int counter = 0; counter < arrayLength; counter++){
ArrayName[counter] = name.substring(counter, name.length()-name.length()+temp);// HAD TO ADD THIS TO GET IT WORKING
temp++;
System.out.println("Element No" + counter + ": " + ArrayName[counter]);
}
You'll want to use the String's toCharArray() method. If you call this method on a String, it will return an array of chars exactly as you needed:
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String name = userInput.nextLine();
char[] nameArray = name.toCharArray();
for(int counter = 0; counter < nameArray.length; counter++){
System.out.println("Element No" + counter + ": " + nameArray[counter]);
}
}
}
Check the documentation linked above to see a full explanation of how it works as well as other methods you can call on a String object.

Categories