i'm trying to test a program that will print "space" if the user enters a single space.
but nothings displayed when i hit space then enter. my aim was really to count the number of spaces but i guess i'll just start with this. help me guys, thanks for any help
here's my code
import java.util.Scanner;
public class The
{
public static void main(String args[])throws Exception
{
Scanner scanner = new Scanner(System.in);
String input;
System.out.println("Enter string input: ");
input = scanner.next();
char[] charArray;
charArray = input.toCharArray();
for(char c : charArray)
{
if(c == ' ')
{
System.out.println("space");
}
else
{
System.out.println(" not space");
}
}
}
}
Scanner ignores spaces by default. Use BufferedReader to read input.
By default, Scanner will ignore all whitespace, which includes new lines, spaces, and tabs. However, you can easily change how it divides your input:
scanner.useDelimiter("\\n");
This will make your Scanner only divide Strings at new line, so it will "read" all the space characters up until you press enter. Find more customization options for the delimiters here.
public class CountSpace {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String word=null;
System.out.println("Enter string input: ");
word = br.readLine();
String data[] ;
int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" "))
k++;
}
if(k!=0)
System.out.println(k);
else
System.out.println("not have space");
}
}
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 am writing a program checking if n words are anagrams of the initially given word. It the word is an anagram it prints "yes", if it isn't - prints "no". It solves the problem correctly if I input all the data manually in the console. If I copy and paste the data it does not "see" the last line until I hit enter again. So it I paste the following input:
anagram
6
gramana
aaagrnm
anagra
margana
abc
xy
So I get only 5 yes-es and no-s and when I hit enter again I get the last no.
here is my code
import java.util.Scanner;
import java.util.Arrays;
public class WordAnagrams {
public static void anagramCheck (String x, String y) {
char[] initial= new char[x.length()];
for (int i=0; i<x.length(); i++) {
initial[i]=x.charAt(i);
}
Arrays.sort(initial);
char[] isAnagram = new char[y.length()];
for (int i=0; i<y.length(); i++) {
isAnagram[i]=y.charAt(i);
// System.out.println(isAnagram[i]);
}
Arrays.sort(isAnagram);
boolean same=Arrays.equals(initial, isAnagram);
if (same) {
System.out.println ("yes");
}
else {
System.out.println ("no");
}
// return answer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String word = input.nextLine();
int n = Integer.parseInt(input.nextLine());
String anagram=""; // input.nextLine();
// int counter=0;
System.out.println();
/* while (counter<n+1) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
counter++;
}*/
for (int i=0; i<=n; i++) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
// System.out.println(answers[i]);
}
System.out.println();
}
}
The issue is that when you copy paste the input, the last word have no '\n' at the end so the scanner doesn't read this as a line until you press ENTER.
So what I can propose is:
1) Use a File for an Input
Or 2) Use InputStreamReader to fetch from the console. Here is some code to do it:
`
public static void main(String[] args) throws IOException {
char buffer[] = new char[512];
InputStreamReader input = new InputStreamReader(System.in);
input.read(buffer,0,512);
String data[] = (new String(buffer)).split("\n");
}
`
It give you a list of strings at the end. PS: Your loop "for(int i =0;i<=n;i++)" is looping 7 times with n = 6.
#kalina199
You could also shorten your code a bit to save yourself from defining a method to check the input from the console.
I did it by splitting the console input into a String array using a simple regex and immediately sorted it.
Then my loop does a simple check to compare the new user input to the original word by their lengths and if that doesn't match you just print out "no" and continue with the next word.
Here's my code:
package bg.Cholakov;
import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] initWord = scanner.nextLine().split("");
Arrays.sort(initWord);
int num = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < num; i++) {
String[] testWord = scanner.nextLine().split("");
Arrays.sort(testWord);
if (!(initWord.length == testWord.length)) {
System.out.println("no");
} else if (initWord[i].equals(testWord[i])) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}
I’m trying to write a program that reads all words from the input file and writes the words to the output file sentences.txt. It should start a new line whenever a word ends in a period, question mark, or exclamation mark and if the period, question mark, or exclamation mark is followed by a quotation mark. Otherwise, it separates words with spaces.
My code so far has keeps giving me a long line of output in the middle and doesn’t print a new line out when punctuation marks are followed by quotes. Could someone point me in the right direction? This is what I have so far:
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
String outputFileName = "sentences.txt";
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
while (in.hasNextLine())
{
String line = in.nextLine();
if (line.endsWith(".\"") || line.endsWith("!\"") || line.endsWith("?\"") ||
line.endsWith(".") || line.endsWith("!") || line.endsWith("?"))
{
out.println(line);
}
}
out.close();
You're testing each line of input to see if it should end a line of output, which doesn't help you much.
You need to test each word of input instead.
Here's a simplified version that just reads standard input and writes to standard output:
import java.util.Scanner;
public class Lines {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
while (in.hasNext()) {
final String word = in.next();
if (shouldEndLine(word)) {
System.out.println(word);
} else {
System.out.print(word);
System.out.print(" ");
}
}
}
// I hid that big, ugly conditional inside a private method.
private static boolean shouldEndLine(final String word) {
return
word.endsWith(".\"") ||
word.endsWith("!\"") ||
word.endsWith("?\"") ||
word.endsWith(".") ||
word.endsWith("!") ||
word.endsWith("?");
}
}
You should probably add logic to print a final newline if needed before exiting.
This is my simple code.
import java.util.Scanner;
public class WordLines
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
If I were to enter a sentence such as "Good Morning World!" (17 non-blank characters in this line)
How could I be able to display my text and on top of that print out the number of non-blank characters present.
Use a regex to delete all whitespace (spaces, newlines, tabs) and then simply take the string length.
input.replaceAll("\\s+", "").length()
Try this:
System.out.println(s);
System.out.println(s.replace(" ", "").length());
Do something like:
public static int countNotBlank(String s) {
int count = 0;
for(char c : s.toCharArray()) {
count += c == ' ' ? 0 : 1;
}
return count;
}
you can calculate non blank characters from a String as follow:
int non_blank_counter = 0;
//your code to read String
for(int i=0;i<s.length();i++){
// .. inside a loop ..//
if ( myStr.charAt( i ) != ' ' )
non_blank_counter++;
}
System.out.println("number of non blank characters are "+non_blank_counter);
Another way to deal with it
import java.util.Scanner;
public class WordLines {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
String[] splitter = s.split(" ");
int counter = 0;
for(String string : splitter) {
counter += string.length();
}
System.out.println("Here is what you entered: ");
System.out.println(counter);
}
}
import java.util.Scanner;
public class WordLines
{
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String s="";
System.out.println("Enter text from keyboard");
while(myScan.hasNextLine()) s = s+myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
u need to user CTRL+C at last when u want to exit from input.
Hope this will help you if you just want to know the number of non blank character.
String aString="Good Morning World!";
int count=0;
for(int i=0;i<aString.length();i++){
char c = aString.charAt(i);
if(c==' ') continue;
count++;
}
System.out.println("Total Length is:"+count);
I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}
I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.
public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)