import java.util.Scanner;
public class WordLines {
public static void main(String [] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sca.nextLine();
int count = 0;
for(int j=0; j<s.length(); j++)
System.out.println(s.charAt(j));
}
}
I am trying to write a program that reads certain line from user input and then displays only one word from than sentence to new line at a time.
For example
Input: The hill is very-steep!!
It would print out
The
hill
is
very-steep!!
So far I have done this much!!
You should use method String::split(String) by regular expression "\s+"
String s = sca.nextLine();
System.out.println("Print out:");
for(final String word : s.split("\\s+"))
{
System.out.println(word);
}
Regular expression \\s+ means "One or more whitespaces in sequence"
Read more about regular expressions you can here
Related
i have figured out a way to replace vowels into * but it only converts the first line
input:
break
robert
yeah
output:
br**k
here is the code
public class Solution {
public static void main(String[] args) {
String enterWord;
Scanner scan = new Scanner (System.in);
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("[aeiou]", "*");
System.out.println(enterWord);
}
}
is there any way that it reads all three words?
Your code works as you want (in:break robert yeah out: br**k r*b*rt y**h) on my env(Windows10, java1.8.0_271), maybe you can set a breakpoint on enterWord = enterWord.replaceAll("[aeiou]", "*"); and check is the enterWord recived whole input string.
You need a loop to keep getting and processing the inputs. Also, I suggest you use (?i) with the regex to make it case-insensitive.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String enterWord, answer = "y";
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter a word: ");
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("(?i)[aeiou]", "*");
System.out.println("After replacing vowels with * it becomes " + enterWord);
System.out.print("Do you wish to conntinue[y/n]: ");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
Enter a word: hello
After replacing vowels with * it becomes h*ll*
Do you wish to conntinue[y/n]: y
Enter a word: India
After replacing vowels with * it becomes *nd**
Do you wish to conntinue[y/n]: n
For a single string spanning multiple lines, the method, String#replaceAll works for the entire string as shown below:
public class Main {
public static void main(String[] args) {
String str = "break\n" +
"robert\n" +
"yeah";
System.out.println(str.replaceAll("(?i)[aeiou]", "*"));
}
}
Output:
br**k
r*b*rt
y**h
Using this feature, you can build a string of multiple lines interactively and finally change all the vowels to *.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "";
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("Keep enter some text (Press Enter without any text to stop): ");
while (true) {
text = scan.nextLine();
if (text.length() > 0) {
sb.append(text).append(System.lineSeparator());
} else {
break;
}
}
System.out.println("Your input: \n" + sb);
String str = sb.toString().replaceAll("(?i)[aeiou]", "*");
System.out.println("After converting each vowel to *, your input becomes: \n" + str);
}
}
A sample run:
Keep enter some text (Press Enter without any text to stop):
break
robert
yeah
Your input:
break
robert
yeah
After converting each vowel to *, your input becomes:
br**k
r*b*rt
y**h
I have the following code:
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String a;
System.out.println("Type in your pinochle deals: ");
a=sc.nextLine();
sc.close();
String[] deals=a.split("");
}
}
I need to split the String I named "a" into a 16 spaced array. But the problem with the splitting is that the input is something like this: ATKQQJ,AKQQ,KQQJN,A. I need to split this into 16 parts and save it to an array I named "deals." I've tried String[] deals=a.split("" && ","); but apparently that isn't valid. I've also tried to split String a into 2 separate arrays and then put them together, but I realized I didn't know how. I want the output to be ["A","T","K","Q","Q","J","A","K","Q","Q","K","Q","Q","J","N","A"] when the input is: ATKQQJ,AKQQ,KQQJN,A. How should I accomplish this?
Try this code
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
String a,b="";
System.out.println("Type in your pinochle deals: ");
a = sc.nextLine();
sc.close();
String[] temp = a.split(",");
for (int i=0; i<temp.length; i++){
for (int j=0; j<temp[i].length(); j++){
b+=temp[i].charAt(j);
}
}
char[] deals=new char[b.length()];
for (int i=0; i<b.length(); i++){
deals[i]=b.charAt(i);
}
}
}
//Split it out into individual characters
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").toCharArray()));
//Split it into strings of a single character
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").split("")));
Here you go:
String a = "ATKQQJ,AKQQ,KQQJN,A";
// Split the string into comma-separated parts
String[] parts = a.split(",");
//Join those parts into a single string
String whole = String.join("",parts);
//Finally, split it up into individual letters
String[] letters = whole.split("");
Could have also generated whole by removing the commas from a.
I 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.String 's' is composed of English alphabetic letters, blank spaces, and any of the following characters: !,?._'#
Here what I'm doing.
import java.io.*;
import java.util.*;
public class apples {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String[] splitString = (s.split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
}
}
When I input a string starting with any of those above characters then my code is counting the character and while printing it gives a empty space, like this.
#dsd sd.sf
4
dsd
sd
sf
What I'm expecting is this.
#dsd sd.sf
3
dsd
sd
sf
Please Help!!
There is no text before the first separator so you get an empty string. I suggest you ignore the first empty string. You could also add a separator at the start so you know there is one you can always ignore. e.g.
String[] split = ("#"+s).split("\\W+");
int words = split.length - 1;
or you can truncate leading non letters
String[] split = s.replaceAll("^\\W+", "").split("\\W+");
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if (!scan.hasNext())
{
System.out.println(0);
}
else
{
String s = scan.nextLine();
scan.close();
s=s.replaceAll("^\\W+", "");
String[] words = s.split("[\\s',!?._#]+");
int len=words.length;
System.out.println(len);
for(String i:words)
{
System.out.println(i);
}
}
}
}
I have a trouble with my code . I think the problem is about delims=[+,-,*,/]+. when i write if (delims.equals("[+]+")) for ex, it takes only [+]. however delims is not equal just [+]. Ithink you got what i mean. delims is equal [+,-,*,/]+.
public static void main(String[] args) {
System.out.println("Please enter your calculation");
Scanner sc = new Scanner(System.in);
String s=sc.next();
String delims="[+,-,*,/]+";
String[] tokens=s.split(delims);
for(int i=0; i<1; i++){
String s1=tokens[i];
for (int j=1; j<2; j++){
String s2=tokens[j];
double n1=Double.parseDouble(s1);
double n2=Double.parseDouble(s2);
if (delims.equals("[+]+")){
System.out.println(n1+n2);
System.exit(0); }
if (delims.equals("[-]+")){
System.out.println(n1-n2);
System.exit(0);}
if (delims.equals("[*]+")){
System.out.println(n1*n2);
System.exit(0);}
if (delims.equals("[/]+")){
System.out.println(n1/n2);
System.exit(0);
}
}}}}
The delimiter is consumed (thrown away), but you need it.
Try this instead:
String[] tokens = s.replace(" ","").split("\\b");
\b means "word boundary", and digits are considered word characters, so this will work when the number parts of the input are whole numbers.
I added a call to `replace' to remove all spaces.
I'm pretty much a complete newbie when it comes to Java. I've dabbled a bit in python and VB.net, and that's about it.
I'm trying to write a program in java that literally reads the user's input and displays it back to them with this code:
import java.util.Scanner;
public class InputTesting
{
public static void main( String[] args )
{
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.nextString();
System.out.println( str1 );
}
}
And I get the error:
InputTesting.java:13: error: cannot find symbol
str1 = input.nextString();
^
symbol: method nextString()
location: variable input of type Scanner
1 error
Can someone tell what why it's not compiling? Thanks!
input.nextString();
There is no method called nextString in the Scanner class. That's why you're getting the error cannot find symbol.
Try
input.nextLine(); // If you're expecting the user to hit enter when done.
input.next(); // Just another option.
import java.util.Scanner;
public class InputTesting
{
public static void main( String[] args )
{
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.next();
System.out.println( str1 );
}
}
You may use one of input.nextXXX() as detailed in Scanner javadoc. to resolve compiler error
in your case
you may use input.nextLine(); get entire line of text.
By Default whitespace delimiter used by a scanner. However If you need to scan sequence of inputs separated by a delimiter useDelimiter can be used to set regex delim
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in);) {
input.useDelimiter(";");
while (input.hasNext()) {
String next = input.next();
if ("DONE".equals(next)) {
break;
}
System.out.println("Token:" + next);
}
}
}
Input
1a;2b;3c;4d;5e;DONE;
Output
Token:1a
Token:2b
Token:3c
Token:4d
Token:5e
Just be cautious while scanning decimal and signed numbers as scanning is Locale Dependent
You need to rather use method nextLine(). This methods prints entire line. By using next() it will print only one word in your sentence.
// That's how i managed solution for input a string
import java.util.Scanner;
public class PalindromeWord {
public static void main(String[] args) {
//System.out.println("Enter a string: ");
Scanner input = new Scanner(System.in);
String S = input.next();
String reverseStr = "";
int strLength = S.length();
for (int i = (strLength - 1); i >=0; --i) {
reverseStr = reverseStr + S.charAt(i);
}
if (S.equals(reverseStr)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}