During while loops, interpret next character? - java

public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please insert a word.: ");
String word = (" ");
while (in.hasNextLine()){
System.out.println(in.next().charAt(0));
}
}
}
I am attempting to read each letter from the input and seperate it with a space.
For example: Input is Yes.
The output should be
Y
E
S
.
I do not understand how to make the char go to the next letter in the input. Can anyone help?

You've got a bug in 'hasNextLine' your loop -- an extraneous ; semicolon before the loop body. The semicolon (do nothing) will be looped, then the body will be executed once.
Once you fix that, you need to loop over the characters in the word. Inside the 'hasNextLine' loop:
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
// print the character here.. followed by a newline.
}

You could do
while (in.hasNext()) {
String word = in.next();
for (char c: word.toCharArray()) {
System.out.println(c);
}
}

Related

Write a program that prompts the user to input a sequence of characters and outputs the numbers of vowels

import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you

Break while loop when reaching a certain character

I have a program that reads a file. The file will be split into lines with the nextLine() method of scanner.
My file looks like this:
*#* lalala lalala lalaa lalala lalal la
x,v,m,k
221312, stringgg, pwd
...
*#* baba bababaa babababa
I want to go into a while loop when reading *#*, then the while should break when reaching the next *#*.
How can this be done?
Are you sure while should break? This will cause while to stop entirely. I think continue is better option, since it will just skip to next while iteration, i.e. it will skip current line.
while(...) {
String line = scanner.nextLine();
if(line.startsWith("#")) {
continue; // or break, if you're sure it's what you want
}
// your code
}
I hope this will help you
/* If I see the string first time I increase the variable n by one.
* If I see the string second time again I increase n by one, now
* n will be 2, If n is 2 I break the for loop ABC
*/
public static void main(String []args){
int n = 0;
String str;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String line = scanner.nextLine();
// System.out.println(line);
int count = line.length();
// System.out.print(count);
ABC:
for(int i=0; i<line.length()-2;i++){
str =line.substring(i, i+3);
if(str.equals("*#*")){
n++;
System.out.println(n);
while(n==2){
break ABC;
}
}
System.out.println(str);
}
}

How do I take an input and make the program print out each letter on a new line while making every space encounter to print out "<space>"?

import java.util.Scanner;
public class TwoDotSevenNumbaTwo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input;
int num1, num2, leng;
char word;
Scanner inputscan = new Scanner(System.in);
System.out.println("Give me some love baby");
input = inputscan.nextLine();
leng = input.length();
num1 = 0;
num2 = 1;
while (num1 < leng) {
input = input.replaceAll(" ", "<space>");
System.out.println(input.charAt(num1));
num1++;
}
}
}
I can't seem to figure out how to get the <space> on a single line. I know I can't do it because it is a char but I can't find a way around it.
You could do
for(int i = 0; i < leng; ++i) {
char x = input.charAt(i);
System.out.println(x == ' ' ? "<space>" : x);
}
Once you've stored the input as a String, you can write:
// Break the string into individual chars
for (char c: input.toCharArray()) {
if (c == ' ') { // If the char is a space...
System.out.println("<space>");
}
else { // Otherwise...
System.out.println(c);
}
}
Regex powa:
yourText.replaceAll(".", "$0\n").replaceAll(" ","<space>");
Explanation:
First replaceAll takes every charachter (. = any character) and replaces it with the same character ($0 = matched text) followed by a newline \n, thusly every character is on separate line.
Second replaceAll just replaces every acctual space with the word "<space>"
For java regex tutorial, you can follow this link or use your favourite search engine to find plenty more.

Replacing a character in a scanner string

So for an assignment I'm supposed to create a program that doubles every letter and triples every exclamation mark of a phrase that is inputted into a scanner. Here is what I got so far:
import java.util.Scanner;
public class DoubleLetters{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a statement");
String x = scan.nextLine();
String y = x.replace("! ","!!! ");
for(int j=0; j< x.length(); j++){
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
}
}
Doubling the letters work, but not tripling the exclamation marks. I tried to use the replace method and it did not work. Please, any help is appreciated.
Just add if statement inside a loop
if(y.charAt(j) == '!') {
System.out.print(y.charAt(j));
}
and remove empty spaces in replace method
String y = x.replace("!","!!!");
try this
String y = x.replace("!","!!!");
or this
for (char c : x.toCharArray()) {
System.out.print(c);
System.out.print(c);
if (c == '!') {
System.out.print(c);
}
}
Convert String into char array than do double and triplet and display . Start reading from left hand side and move to right hand side using double and triplet condition update char array and finally display result(char array) .
You could go over all the characters and append them to a StringBuilder:
String str = /* recieved from scanner */
StringBuidler builder = new StringBuilder();
for (char c : str.toCharArray()) {
// Any character needs to be included at least once:
builder.append(c);
// If it's a letter, you need another copy (total of 2)
if (Character.isLetter(c)) {
builder.append(c);
// If it's an excalmation mark, you need another two copies (total of 3)
} else if (c == '!') {
builder.append(c);
builder.append(c);
}
}
System.out.println(builder);
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
Try the follwing code, it will work efficiently as you like,
import java.util.Scanner;
public class DoubleLetters
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a statement");
String x = scan.nextLine();
for(int j=0; j< x.length(); j++)
{
if(y.charAt(j)=='!')
System.out.println("!!!");
else
{
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
}
}
}
As u havn't succeeded to replace '!' . so for a another approach instead of replace you can tokenize your string using StringTokenizer as this piece of code. and by this u can add what u want as for your case at the end of each ! u can add 2 more !!. code as.
System.out.println("---- Split by comma '!' ------");
String s = "My Name !is !Manmohan"; //scanner string
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(s, "!");
String now = "";
while (st2.hasMoreElements()) {
now += st2.nextElement() + "!!!";
}
System.out.println(now.substring(0, now.length() - 3));
//op ... My Name !!!is !!!Manmohan

Writing a program to count spaces in a phrase

I'm trying to write a program where a user would enter a phrase, and the program would count the blank spaces and tell the user how many are there. Using a for loop but i'm stuck, could someone help me out?
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for(ch=phrase.charAt()
// and count the blank spaces
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
The for loop for counting spaces would be written as follows:
for(int i=0; i<phrase.length(); i++) {
if(Character.isWhitespace(phrase.charAt(i))) {
countBlank++;
}
}
It reads as follows: “i is an index, ranging from the index of the first character to the index of the last one. For each character (gotten with phrase.charAt(i)), if it is whitespace (we use the Character.isWhitespace utility function here), then increment the countBlank variable.”
Just wondering, couldn't you just split the string entered by blank spaces and take the length of the array subtracted by 1?
In C# it would be as trivial as
string x = "Hello Bob Man";
int spaces = x.Split(' ').Length - 1;
Pretty sure java has a split? Works even if you have two contiguous spaces.
You have probably problem with that for each loop
char[] chars = phrase.toCharArray(); Change string into array of chars.
for(char c : phrase.toCharArray()) { //For each char in array
if(Character.isWhitespace(c) { //Check is white space.
countBlank++; //Increment counter by one.
}
}
or
for(int i =0; i <phrase.lenght(); i++) {
if(Character.isWhitespace(phrase.charAt(i)) { //Check is the character on position i in phrase is a white space.
countBlank++; //Increment counter by one.
}
}
You have to complete for cycle and count spaces
//replace this lines
for(ch=phrase.charAt()
// and count the blank spaces
//to this lines
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
}
Loop through the characters in the string.
Check if the character is a space (char value = 32 or ch == ' ')
If space, add to countBlank, otherwise continue
Display the results.
You might look at the String and Character classes in the Java documentation for assistance.
I'm not very familiar with java, but if you can access each character in the string.
You could write something like this.
int nChars = phrase.length();
for (int i = 0; i < nChars; i++) {
if (phrase.charAt(i) == ' ') {
countBlank++;
}
}
This is at the following Java Tutorials
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
String[] items = p.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
OUTPUT:
one
two
three
four
five
The regex for whitespace is \s
Hope that helps.

Categories

Resources