How to count the amount of space delimiters in a string using the for loop? - java

I am new to Java and am working on an assignment where you need to count the amount of delimiters or spaces in a string that the user inputs.
I have to use a method that prompts the user to input a string using the Keyboard class. However, I am using BlueJ and Keyboard is not compatible with the BlueJ library thing. I do know that Scanner could be as an alternative with Keyboard but I am not sure how to read a string using Scanner.
Furthermore, I am not sure how I am suppose to structure my for loop to count the delimiters in a string. I am sorry for my high misunderstanding with this and I know that I am asking a lot but please don't feel obligated to answer everything, just whatever you want to or what you can easily answer. Here is my code below:
import cs1.keyboard;
import java.util.StringTokenizer;
public class Counting_Chars
{
public static void main (String []args)
{
int spaceCount = 0, characterCount = 0;
String line, word;
StringTokenizer tokenizer;
System.out.println("Please enter text (type DONE to quit):");
line = scan.nextLine();
String phrase = line;
for (String ch = phrase.charAt(line);; ch <= line; count++)// I don't really know what I am doing here
{
System.out.println (count);
}
}
}

it sounds like you are having multiple issues here. Perhaps it would be good to break the problem down into smaller parts and build your way back up again.
I would suggest something like:
write a program that just prints out some text (like 'Hello World')
write a program that asks the user to type in a line of text and
then just prints out that exact same text again
then worry about counting the spaces in the string

Related

How to Validate Canadian postal Code in Java? Checking for 2 types of input? ex: accepting A1A1A1 and A1A 1A1

I am trying to make a program that allows the user to input 2 different formats for a postal code (A1A1A1 or A1A 1A1) and I cannot for the life of me get it to work :/
My thought process was identifying both formats first and then using an if statement to check for the identified formats and then decide if its valid or not.
But I keep getting invalid when I try to enter the format with space in them (A1A 1A1).
so far I have this
import java.util.Scanner;
import java.util.regex.Pattern;
public class ValidatingPostcodes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Postcode:");
String Pc1 = "[A-Z][0-9][A-Z][0-9][A-Z][0-9]";
String Pc2 = "[A-Z][0-9][A-Z][ ][0-9][A-Z][0-9]";
while (sc.hasNext())
{ if (sc.hasNext (Pc1))
System.out.println ("Valid Postal Code");
else if (sc.hasNext (Pc2))
System.out.println ("Valid Postal Code");
else System.out.println("Invalid Postal Code");
sc.next();
}
}
}
The easy solution is: simply treat the two kinds of input the same way when processing them internally. Meaning:
Create one method that validates a 6-char potential ZIP code
But before calling that method, you check if your input contains a space as 4th character, and if so, you simply remove that space before giving it as parameter to your validation method.
But keep in mind: you probably want to keep the original string around - if you intend to give back "A1A A2A" later on. Of course, if you decide that users can enter ZIPs in two ways, but that they should get back "unified" format later on, then you can make that "space-dropping" thing permanent.
EDIT: you create a method
public boolean isValid(String zipCode) {
that returns TRUE for valid zipcodes that have 6 (SIX!) chars and no spaces
and another method
public String normalizeZipCode(String incoming) {
return incoming.replaceAll("\\s+","");
}
To be used like:
String zip1 = "A1A 1A1";
String zip2 = "A1A1A1";
String normalizedZip1 = normalizeZipCode(zip1);
String normalizedZip2 = normalizeZipCode(zip2);
System.out.println(isValid(normalizedZip1));
System.out.println(isValid(normalizedZip2));
The simple idea: if one format contains spaces, then just remove those spaces prior validation. In other words: you allow the user to enter data in two formats; but internally, you make sure that any usage of the second format is simply avoided, by turning it into the format that comes without spaces.

print even words from string input?

I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}

Get input from user in one line without space in java

I am a beiggner in java programming and i have a problem i want to get input from user in one line such as in c++
in c++ if i want to make a calculator i make 2 variable for example a band third is op and make user input them by
cin>>a>>op>>b;
if (op=='+')
{
cout<<a+b<<endl;
}
and so on how to make that in Java ?
i make a try in java but i get Error
and one more question how to make user input a char i try char a=in.next(); but get error so i make it string
code java
Scanner in=new Scanner(System.in);
int a=in.nextInt();
String op=in.nextLine();
int b=in.nextInt();
if (op=="+")
{
System.out.println(a+b);
}
else if (op=="-")
{
System.out.println(a-b);
}
.........
First of all, in Java you compare String with a.equals(b), in you example it would be op.equals("+"). And also, after reading a line it have the line break character (\n), so you should remove it to avoid problems. Remove it using String op = in.nextLine().replace("\n", "");.
And answering the how to read a character part, you can use char op = reader.next().charAt(0)

Basic program for a learning programmer [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
So I just started taking my first classing in programming with Java, so don't hurt me for being a new guy. I understand this may be a simple thing to do, but I'm stuck on where to even begin. I want to make a program that simply counts the number of characters in a string using the Scanner utility. So far I have...
import java.util.scanner
class Counter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many
characters are in it.");
String sentence = input.nextString();
And this is as far as I have gotten. What I want to do is the previous plus...
Char character;
and do something with that, maybe a for-loop, but I'm simply stumped.
And even if I did want to do this I wouldn't know how to go about it. Any ideas?
Thanks!
~Andrew
EDIT:
import java.util.Scanner;
class Counter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many
characters are in it.");
String sentence = input.nextLine();
sentence = sentence.trim();
System.out.print("This sentence has " + sentence.length() + "
characters in it.");
}
}
Did not seem to work.
You have to use input.nextLine() instead of input.nextString() to capture the sentence given by the user.
You also have to use the trim() method on that sentence to delete the spaces given by the user in the front and back side of the sentence.
Ex: sentence.trim()
You can get the length of the sentence by the length() method.
Ex: sentence.length()
Now, I am giving you the full code to count letters of a given sentence:
import java.util.Scanner;
public class LetterCount
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many characters are in it.");
String sentence = input.nextLine();
System.out.print("This sentence has " + sentence.trim().length() + " characters in it.");
}
}
First of all, to read by Scanner you have to use input.nextLine(); instead of input.nextString();.
After, you can use .length() function to know how much positions have your String (how much chars have your String) so you won't have to convert it to any char or whatever.
System.out.println(sentence.length());
I expect it will be helpful for you!

Scanner nextLine, stuck in while loop or exiting at odd times

I started doing the CodeAbbey problems last night, they mentioned using stdIn since some the input data is long so copy/paste is much easier than by hand. I had never used the Scanner before so it looked easy enough. I got it working for single line inputs then I got a problem where the input was:
867955 303061
977729 180367
844485 843725
393481 604154
399571 278744
723807 596408
142116 475355
I assumed that nextLine would read each couple, xxxx yyyyy. I put the code in a while loop based on if nextLine is not empty. It runs, but I get weird output, and only after I hit return a few times.
package com.secryption;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input: ");
Scanner scanner = new Scanner(System.in);
String input = "";
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
String[] resultSet = input.split("\\s+");
for(String s : resultSet) {
System.out.println(s);
}
}
}
I thought I might need something after adding scanner.nextLine() to input. I tried a space and that didn't help. I tried a newline and that didn't make it better.
This "should" put all the numbers in a single array, nothing special. What am I missing with scanner?
EDIT: Ok so #Luiggi Mendoza is right. I found this How to terminate Scanner when input is complete? post. So basically it it working, I just expected it to do something.
The problem is here:
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
Scanner#nextLine reads the line and will continue reading. You're reading two lines and not storing the result of the first line read, just reading and storing the results of the second.
Just change the code above to:
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(" ");
}
hasNext() is an end of file indicator that terminates by combining keys control d on Mac ox and control z on windows pressing enter won't send the right message
to JVM

Categories

Resources