I'm trying to create a program in BlueJ that allows the reader to type any word, then print out: that word, the length of the word, and whether or not the word contains "ing". I've figured out how to print the word and its length, but I can't figure out how to include whether "ing" is in the word.
Here is my code:
import java.util.*;
public class One
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "";
System.out.println("Type in a word");
str = sc.nextLine();
//System.out.println(str);
System.out.println(str.length());
}
}
How can I tell whether "ing" is included in the word?
You can do that using the contains() method on your resulting string:
if (str.contains("ing")) System.out.println("Contains ING");
If you need to match either lowercase or uppercase, you can just convert str to upper case and check that instead:
if (str.toUpperCase().contains("ING")
I am trying to write a program in Java so I can read a file, reverse every single word, meaning if the sentence is "Hello Java" the output should be "olleH avaJ".I have been able to do the reverse but with the program I have written the output is "olleHavaJ" with no space. Can someone help me fix it? Thank you!
import java.util.Scanner;
import java.io.*;
public class ReadWords {
public static void main(String[] args) throws FileNotFoundException {
File f=new File("words.txt");
Scanner input=new Scanner(f);
String result="";
while(input.hasNextLine()) {
String fjala=input.next();
for(int i=fjala.length()-1;i>=0;i--) {
result+=fjala.charAt(i);
}
}
input.close();
System.out.print(result+" ");
}
}
Making my initial comment as an answer.
You can add a space once you have constructed the reversed word.
for(int i=fjala.length()-1;i>=0;i--) {
result+=fjala.charAt(i);
}
result += " ";
You can use nextLine() instead of next( ) (though this can be solved using next also) method, and do split(" ") and assign it in String[ ] as follows.
String[ ] words = in.nextLine( ).trim( ).split(" ");
Now apply reverse function on each word and push it in the output file.
Hope this solves your problem :)
Problem Statement
Given a string s , matching the regular expression [A-Za-z !,?._'#]+, split the string into tokens. We define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed by each token on a new line.
Input Format
A single string, s.
s is composed of English alphabetic letters, blank spaces, and any of the following characters: !,?._'#
Output Format
On the first line, print an integer,n, denoting the number of tokens in string s (they do not need to be unique). Next, print each of the n tokens on a new line in the same order as they appear in input string s .
Sample Input
He is a very very good boy, isn't he?
Sample Output
10
He
is
a
very
very
good
boy
isn
t
he
My Code:
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String[] splitString = (s.replaceAll("^[\\W+\\s+]", "").split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
}
}
This code works fine for the Sample Input but do not pass this test case.
Test case:
Input:
YES leading spaces are valid, problemsetters are evillllll
Expected Output:
8
YES
leading
spaces
are
valid
problemsetters
are
evillllll
What changes in the code will pass this test case ?
Speaking about trimming non-word chars in the beginning of the string, your regex is not correct.
The ^[\\W+\\s+] matches 1 character at the beginning of a string, either a non-word (\W), a + or a whitespace. Using replaceAll makes no sense since only 1 char at the start of the string will get matched. Also, \W actually matches whitespace characters, too, so there is no need including \s into the same character class with \W.
You may replace that .replaceAll("^[\\W+\\s+]", "") with .replaceFirst("^\\W+", ""). This will remove 1 or more non-word chars at the beginning of the string (see this regex demo).
See this online Java demo yielding your expected output.
NOTE: to split a sentence into word char chunks, you may actually use
String[] tokens = s.replaceFirst("^\\W+", "").split("\\W+");
Java demo:
String s = " YES leading spaces are valid, problemsetters are evillllll";
String[] splitString = s.replaceFirst("^\\W+", "").split("\\W+");
Then,
System.out.println(splitString.length); // => 8
for (String string : splitString) {
System.out.println(string);
}
// => [ YES, leading, spaces, are, valid, problemsetters, are, evillllll]
Try this one it's working
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
s = s.trim();
if (s.length() == 0) {
System.out.println(0);
} else {
String[] strings = s.split("['!?,._# ]+");
System.out.println(strings.length);
for (String str : strings)
System.out.println(str);
}
}
}
You can trim the string before splitting it. In the given test case, it will count blankspace at the starting of the string as well. Try this:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine().trim();
if(s.isEmpty())
System.out.println("0");
else {
String[] S = s.split("[\\s!,?._'#]+");
System.out.println(S.length);
for(int i=0;i<S.length;i++) {
System.out.println(S[i]);
}
}
scan.close();
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
StringTokenizer st = new StringTokenizer(s,("[_\\#!?.', ]"));
System.out.println(st.countTokens());
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
scan.close();
}
if(s.trim().isEmpty()){
System.out.println("0");
System.out.println(s);
} else {
String[] splitString = (s.replaceAll("^\\W+", "").split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for(String str: splitString) {
System.out.println(str);
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
String[] arr = s.split("\\s+|\\,+|\\'+|[\\-\\+\\$\\?\\.#&].*");
// Write your code here.
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
scan.close();
}
}
The following should help
public static void regexTest() {
String s="isn't he a good boy?";
// Replace any non alphabetic characters with a space.
// [^a-zA-Z]
// [ - Start a custom character class
// ^ - Anything that is not
// a-zA-Z - a lowercase character or upper case character.
// for example a-z means everything starting from 'a' up to
// and including 'z'
// ] - End the custom character class.
// Given the input string, the single quote and question mark will be replaced
// by a space character.
s=s.replaceAll("[^a-zA-Z]", " ");
// Split the string (that only contains letters and spaces into individual words.
String[] array_s=s.split(" ");
for(int i=0;i<array_s.length;i++) {
System.out.println(array_s[i]);
}
This will pass all test cases
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if(s.trim().isEmpty()) {
System.out.println(0);
}
else {
System.out.println(s.trim().split("[!,?. #_']+").length);
for(String a : s.trim().split("[!,?. #_']+")){
System.out.println(a);
}
}
scan.close();
}
}
I'm trying to determine if an input string is in a valid 24-hour date format (ie. hh:mm:ss). I'm using a few different logics and have been mostly successful with my test cases. My code currently fails for all the inputs I've tried (including the ones below).
The expression is supposed to work in the following way:
Inputting 11:24:10 should output Valid form
inputting 00:13:42 should output Valid form
Inputting 24:52:25 should output Invalid form
Inputting 05:62:55 should output Invalid form
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("String to check: ");
String input = new Scanner(System.in).nextLine();
if (input.matches("((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]")) {
System.out.println("Valid form");
} else {
System.out.println("Invalid form");
}
}
}
I've only recently started learning Java and I apologize if this question has been asked before (I googled!). Thanks for your help!
It should be
(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]
According to your regex
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]
It will match ((0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]
You can also use non capturing group if you just want to match it as
(?:(?:(?:0|1)[0-9])|(?:2[0-3])):[0-5][0-9]:[0-5][0-9]
Your regex can be simplified further as by modifying hours part
[01][0-9]
IDEONE DEMO
EDIT
Little bit modification
(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]
REGEX DEMO
The issue is that your current regex will match (0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]. You want your || operator to work on the (0|1)[0-9]) and (2[0-3]). So what you want is this:
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]
You also have a resource leak because you do not close your Scanner. It is best to store the new Scanner in a variable so that you can close it later. Here is the full code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("String to check: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.matches("(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]")) {
System.out.println("Valid form");
} else {
System.out.println("Invalid form");
}
sc.close();
}
}
I'm trying to Display one String Which is User Input.
Display With Space and starting letter of the word as Upper Case.
For example If the user input is like mobileScreenSize output Will be Mobile Screen Size.
Any help Thankful to Them.
To be able to split the input into valid words you need a dictionary of valid words.
With such a dictionary you can first split the input in words and in a second pass uppercase the first letters.
1. Thanks a lot for all your support guys
2. Finally I found the solution.
----------
package demo.practice.java;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
System.out.println("Enter String");
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
//split into words
String[] words = input.split("(?=[A-Z])");
words[0] = capitalizeFirstLetter(words[0]);
//join
StringBuilder builder = new StringBuilder();
for ( String s : words ) {
builder.append(s).append(" ");
}
// System.out.println(builder.toString());
System.out.println("Output String--->" +builder.toString());
}
private static String capitalizeFirstLetter(String in) {
return in.substring(0, 1).toUpperCase() + in.substring(1);
}
}