Reputation: 21
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");
}
}
}
}
Upvotes: 2
Views: 7038
Reputation: 103
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");
}
}
Upvotes: 0
Reputation: 6054
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.
Upvotes: 1