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")
Related
I have to create a program in java that reads a string from the user which contains dot (.) sign on it. I need to delete the dot and the char before it, and print the result.
So if the input is : mx.erw.ho.abe.a
It should print : merhaba
Or if the input is : lok.okl. u.ay.t t.tho.p.e e.sku.y
It should print : look at the sky
This is what i have done so far, which kind of works but it cuts out even the last letter of the word (if it is merhaba, this code prints merhab and if it is look at the sky, it prints look at the sk
How can i fix this?
public class HiddenMessage {
public static void main (String [] args) {
String [] message="lok.okl. u.ay.t t.tho.p.e e.sku.y".split("[.]");
for(int i=0;i<message.length;i++) {
System.out.print(message[i].substring(0, message[i].length()-1));
}
}
}
Update:
So now my code looks like this if i want to take the input from the user. It prints merhaba just fine but it only prints "look" not "look from the sky"
import java.util.Scanner;
public class HiddenMessage {
public static void main (String [] args) {
Scanner input=new Scanner (System.in);
System.out.println("Please enter the message: ");
String message=input.next();
String m1=message.replaceAll("\\w\\*", "");
System.out.print(m1);
}
}
You can use replaceAll() method and the regex \\w\\.
Try this:
String result = "lok.okl. u.ay.t t.tho.p.e e.sku.y".replaceAll("\\w\\.", "");
\\w : matches a word character (Letter, digit, underscore)
\\. : matches dot character
If you use the regex ".\\." it literally matches the dot and the char before it.
. : matches any character
Scanner input = new Scanner(System.in);
System.out.println("Please enter the message: ");
String message = input.nextLine();
String m1 = message.replaceAll("\\w\\.", "");
System.out.print(m1);
I wrote this program that should only break down the string when there is greater than sign or a colon. When I enter for example "cars:ford> chevy" , the output gives me the space between the > and "chevy" and then the word "chevy. How do I prevent it from giving me that white space? All I want is the word , here is my code.
import java.util.Scanner;
import java.util.StringTokenizer;
public class wp{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter words");
String ingredients = keyboard.nextLine();
StringTokenizer str = new StringTokenizer(ingredients,">:");
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
As the space is part of the input, it is valid that the tokenizer returns it (think of situations where you want to react to the space).
So all you need to do is postprocess your split results e.g.:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter words");
String ingredients = keyboard.nextLine();
StringTokenizer str = new StringTokenizer(ingredients, ">:");
while (str.hasMoreTokens()) {
String nextToken = str.nextToken();
String trimmed = nextToken.trim();
System.out.println(trimmed);
}
}
}
Answer to trim is ok also, but on line
StringTokenizer str = new StringTokenizer(ingredients, ">:");
you specified delimiters as characters '>' and ':', you can simply add space there too. It depends what your requirements are. If you want for string "cars:ford> chevy 123" to have 4 tokens, this is what you have to do...
So change it to
StringTokenizer str = new StringTokenizer(ingredients, ">: ");
You can use trim() method of String class to remove all preceding and succeeding white spaces:
str.nextToken().trim().
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);
}
}
The sentence String is expected to be a bunch of words separated by spaces, e.g. “Now is the time”.
showWords job is to output the words of the sentence one per line.
It is my homework, and I am trying, as you can see from the code below. I can not figure out how to and which loop to use to output word by word... please help.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
int space = sentence.indexOf(" ");
sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
System.out.println(sentence);
}
}
You're on the right path. Your showWords method works for the first word, you just have to have it done until there are no words.
Loop through them, preferably with a while loop. If you use the while loop, think about when you need it to stop, which would be when there are no more words.
To do this, you can either keep an index of the last word and search from there(until there are no more), or delete the last word until the sentence string is empty.
Since this is a homework question, I will not give you the exact code but I want you to look at the method split in the String-class. And then I would recommend a for-loop.
Another alternative is to replace in your String until there are no more spaces left (this can be done both with a loop and without a loop, depending on how you do it)
Using regex you could use a one-liner:
System.out.println(sentence.replaceAll("\\s+", "\n"));
with the added benefit that multiple spaces won't leave blank lines as output.
If you need a simpler String methods approach you could use split() as
String[] split = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : split) {
if (word.length() > 0) { // eliminate blank lines
sb.append(word).append("\n");
}
}
System.out.println(sb);
If you need an even more bare bones approach (down to String indexes) and more on the lines of your own code; you would need to wrap your code inside a loop and tweak it a bit.
int space, word = 0;
StringBuilder sb = new StringBuilder();
while ((space = sentence.indexOf(" ", word)) != -1) {
if (space != word) { // eliminate consecutive spaces
sb.append(sentence.substring(word, space)).append("\n");
}
word = space + 1;
}
// append the last word
sb.append(sentence.substring(word));
System.out.println(sb);
Java's String class has a replace method which you should look into. That'll make this homework pretty easy.
String.replace
Update
Use the split method of the String class to split the input string on the space character delimiter so you end up with a String array of words.
Then loop through that array using a modified for loop to print each item of the array.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
String[] words = sentence.split(' ');
for(String word : words) {
System.out.println(word);
}
}
}
I need help doing the following:
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
The below code is what I have so far but it is only returning user input and not removing numbers:
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1.replaceAll("[^0-9]","");
System.out.println(firstname1);
Updated Code. Thank you Hovercraft. I am now investigating how to retrieve all alpha characters as with the code below, I am only getting back the letters prior to the numeric values entered by the user:
import java.util.Scanner;
public class Assignment2_A {
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceAll("[^A-Z]","");
System.out.println(firstname1);
String input = yourScannerObject.nextLine ();
where "yourScannerObject" is the name you give your scanner.
What method did you use to scan? is it {scanner object name}.next() ?
if so you have got a string and all that you have to do is create some string, and save the input to it, e.g.:
String str="";
str = {scanner object name}.next();
before using anything in java, I would advise you to read the API :
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next()
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
Here's an example:
String in;
Scanner scan = new Scanner("4r1e235153a6d 6321414t435hi4s 4524str43i5n5g");
System.out.println(in = (scan.nextLine().replaceAll("[0-9]", ""))); // use .next() for space or tab
Output:
read this string
The problem in your code is the regex "[^A-Z]" is set to remove all non-alphabet capital characters. This means you remove all lower case as well. You could say "[^a-zA-Z]", but then you're also removing special characters.