I am given this exercise, but I am having trouble finding a way to catch the new line. Can you please help me?
Write a program that reads user input until an empty line. For each non-empty string, the program splits the string by spaces and then prints the pieces that contain av, each on a new line.
Here is mycode:
public class AVClub {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> str = new ArrayList();
String line;
while (!(line = scanner.nextLine()).equals("")){
str.add(line);
}
for(int i=0; i<str.size();i++){
if(str.get(i).contains("av")){
System.out.println(str.get(i));
}
}
}
}
The following requirement has been wrongly implemented in your code:
For each non-empty string, the program splits the string by spaces and
then prints the pieces that contain av, each on a new line.
It should be:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> str = new ArrayList();
String line;
System.out.print("Enter sentences (blank line to terminate): ");
while (!(line = scanner.nextLine()).equals("")) {
str.add(line);
}
System.out.println("Words containig 'av' are: ");
for (int i = 0; i < str.size(); i++) {
line = str.get(i);
String[] words = line.split("\\s+"); // Split the string on spaces
for (String word : words) {
if (word.contains("av")) {
System.out.println(word);
}
}
}
}
}
Explanation: you have to check each word in every sentence whether the word contains av. Your code checks for av in each sentence.
A sample run:
Enter sentences (blank line to terminate): harry is a good boy
my name is avinash
Is there any seats available in the aviation training
hello world
Words containig 'av' are:
avinash
available
aviation
Note: If you need to check av in a case insensitive way, do it as if (word.toUpperCase().contains("AV")).
Related
Trying to split out a string and output the penultimate word inputted by the user, but the .split() only seems to be outputting a single string into the array so its not working?
import java.util.*;
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.next();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
System.out.println("Penultimate word " + words[words.length - 2]);
}
}
Problem is not with the split method, rather you should use nextLine instead of next:
String sentence = sc.nextLine();
The answer by #Aomine should resolve your problem. If you really wanted to use Scanner#next() directly, then you could also try setting the scanner's delimiter to be newline:
Scanner sc = new Scanner (System.in);
sc.useDelimiter(Pattern.compile("\\r?\\n"));
Then, calling Scanner#next() should default to returning the next full line.
You can use the whitespace regex
str = "Hello spilt me";
String[] splited = str.split("\\s+");
The split is working correctly. Reading of information from console is correct. Below changes should work.
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.nextLine();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
for (String currentWord : words ) {
System.out.println("The current word is" + currentWord);
}
}}
Write a method called countWords that accepts an ArrayList of String as argument and
prints out the number of words (i.e. Strings) that start with ―A‖ or ―a‖ and prints all words longer than 5 characters on one line.
My solution is like
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
while(input.hasNext()) {
String st1=input.next();
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("a")||array.get(i).startsWith("A")) {
count++;
}
}
for(int j=0; j<array.size(); j++) {
if(array.get(j).length()>5)
st[j]=array.get(j);
}
System.out.println(count);
System.out.println(st);
}
but there will be no end for typing in Strings
As the last line of your question said
but there will be no end for typing in Strings
Well That is because you did not provided any way to end the while loop.
while(input.hasNext())
Will run forever and ever waiting for next user input. You have to break the while loop once the inputting is done.
AFTERWARDS
As the question said "prints out the number of words that start with A or a and prints all words longer than 5 characters on one line."
For this you can loop through the ArrayList and check for
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")) count++;
if(array.get(i).length()>5) System.out.print(array.get(i)+" ");
and print the number of A or a Occurrence after the loop
System.out.println("\n Number of word with A or a:"+count);
Here is a working implementation of your code
public static void main(String[] args) {
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
//System.out.println(input.hasNext());
while(input.hasNext()) {
String st1=input.next();
//System.out.println((int) st1.charAt(0));
if(st1.equals("exit")) break;
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")){
count++;
}
if(array.get(i).length()>5) {
System.out.print(array.get(i)+" ");
}
}
System.out.println("\nNumber of word with A or a:"+count);
}
to end the loop you have to type exit.
Here is a solution to your problem..
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String... args){
// Sample String sentence
String sentence = "This is the sentence with 5 words starting with
all like allwords alltogether also Allnotout allother and allofus.";
// Splitting above sentence to get each word separately and storing them into List
List<String> strings = Arrays.asList(sentence.split("\\s+"));
// calling a method named countWord() as per your assignment question.
Test.countWords(strings);
}
// implementing that method
static void countWords(List<String> input){
long count = input.stream().filter(word -> word.startsWith("all") || word.startsWith("All")).count();
System.out.print("Total words starting with all/All are : "+ count +"\t");
input.stream().filter(word -> word.length() > 5).forEach( word -> System.out.print(word + "\t"));
}
}
I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];
I want to be able to output the letter size of each word. So far my code only outputs the letter size of the first word. How do I get it to output the rest of the words?
import java.util.*;
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String words = sc.next();
String[] letters = words.split(" ");
for (String str1 : letters) {
System.out.println(str1.length() );
}
}
}
It's just because next returns only the first word (or also called the first 'token'):
String words = sc.next();
To read the entire line, use nextLine:
String words = sc.nextLine();
What you are doing should work then.
The other thing you can do is go ahead and use next all the way (instead of a split) because Scanner already searches for tokens using whitespace by default:
while(sc.hasNext()) {
System.out.println(sc.next().length());
}
Using sc.next() will only let the scanner take in the first word.
String words = sc.nextLine();
Iterate over all of the scanner values:
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String word = sc.next();
System.out.println(word.length() );
}
}
}
I'm trying to find the smallest word in a user entered string. This is what I have so far:
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String myText = sc.next();
String[] myWords = myText.split(" ");
int shortestLength,shortestLocation;
shortestLength=(myWords[0]).length();
shortestLocation=0;
for (int i=1;i<myWords.length;i++) {
if ((myWords[i]).length() < shortestLength) {
shortestLength=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}
If I entered "SMALLEST WORD SHOULD BE A", the output should be A but it just gives me the first word of the string. Any ideas?
Your algorithm is fine, but instead of using next():
String myText = sc.next();
Which will only read a single token, i.e., the first word, use nextLine(), which will read the entire line:
String myText = sc.nextLine();
To take the full string you have to use the method
sc.nextLine();
thus it will take the complete string.