I am quite new to programming and I am writing this code to count a string (length) to a point when I encounter a space. The aim is - when the user enters his/her name AND surname, the program should split the name from surname and count how many letters/characters were there in the name (and surname).
My code doesn't seem to reach/execute the "if-statement", if I enter two strings (name & surname) separated by space (output: Your name is: (empty space) and it has 0 letters. However, if I enter only one string, the if-statement, it gets executed.
What I am doing wrong?
My example code:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
for(int x = 0; x<=nameAndSurname.length()-1; x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
scan.close();
}
Why bother with all that code? Just skip the for-loop, have an
if (space != -1) nameOnly = nameAndSurname.substring(0,space);
and if you really want to know the amount of letters, it is
space+1
No need for all that complicated stuff.
if(nameAndSurname.indexOf(x) == space)
This line isn't doing what you think it is doing.
It's getting a char (character) from the index of x, and comparing it to the value of space. Space is an integer, so you are comparing the character at position x to the integer position of the first space. In this case, the letter at position x is cast into an integer, and then compared to the actual number value of the first space!
To fix the program, replace your entire if statement with this.
if (nameAndSurname.charAt(x) == ' ') //if there is a space
{
count = c-1; //how many characters/letters was there before space
System.out.println(count);
}
Extra:
Since the way you've solved this problem is a bit overkill, I've posted another solution below which solves it in a way that is easier to read. Also it won't break if you put in more or less than 1 space.
Scanner scan = new Scanner(System.in);
String nameAndSurname;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine().trim();
int indexOfFirstSpace = nameAndSurname.indexOf(' ');
if (indexOfFirstSpace > -1) {
String firstName = nameAndSurname.substring(0, indexOfFirstSpace);
System.out.println("Your first name is " + firstName.toUpperCase());
System.out.println("It is " + firstName.length() + " characters long.");
}
You can verify if your string has space before start the loop, something like this:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
if(space == -1) {
System.out.println("Your name has no spaces");
} else {
for(int x = 0; x<nameAndSurname.length(); x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
}
scan.close();
}
Related
I was hoping that SO could help me with my issue. I have this code:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count +
(count == 1 ? " time" : " times"));
}
So this code asks the user to enter a string, then it asks the user to enter a character, the program will then tell the user how many times that specific character appears. My problem is that I need to convert this code so it will still ask the user for the string, but wont ask for a character. It will instead ask for the user to enter a number. The program will then show what character is at that position in the string. Example: lets say they enter "string" and then 2 for the number, the program will display the character "r". So my question is basically if any one can give me an idea as how to accomplish this. Any help would be great.
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter an integer:\t");
int index = scanner.nextInt();
System.out.println("Character at position " + index + ": " + word.charAt(index));
}
I have created a program that uses the Scanner to ask the user for int values until they insert -1 which makes the program to stop receiving numbers. After doing so, it will add all the values entered by the user. This is my code so far:
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
String string = Integer.toString(value);
while (value != -1)
{
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
string = Integer.toString(value);
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + string + ",");
System.out.println ("The sum is " + sum);
}
}
I want the output to look like this:
Entered numbers: 1,2,3,4,5 //example of number the user might enter
The sum is 15
I wanted to use a String for it to give me the sets of entered numbers, but it only gives me the last entered value. Which is -1 because that is the number that has to be entered to stop the program.
How can I out this problem?
In your
while(value != -1){
...
string = Integer.toString(value);
}
you are replacing string value with new one, so old value is lost. You should add new value to previously stored one. So your code may look like
string = string + "," + value;
You should also place this code before handling value which will be -1.
BTW, when you will learn more about Java you will know that each time you call
string + "," + value
new String is being created. Such string will need to copy content of other chunks. which may be very inefficient in case of long strings. To optimize this we can use StringBuilder and append new parts to it in loop.
In Java 8 we can also use StringJoiner which can automatically add prefixes, delimiters and suffixes for us.
Simply use string += "," + Integer.toString(value); This will give you a comma separated list of all the values you have entered. Your current statement string = Integer.toString(value); causes the variable string to be reset to the string representation of "value" for every iteration.
Check this code.
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
StringBuilder sb = new StringBuilder();
while (value != -1)
{
if(sb.length() == 0){
sb.append(value);
}else{
sb.append(","+value);
}
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + sb.toString());
System.out.println ("The sum is " + sum);
}
}
I'm trying to slice a string for the first time.
With this code, if I input, for example 'one two three' it works fine until the last word.
This is the last few lines of the output:
Current word is thr
Sentence is now e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(String.java:1907)
at TestCurr.main(testCurrentWord.java:18)
Has anyone any idea why it does that to the last word?
class TestCurr
{
public static void main (String []args)
{
String s;
int i;
String currentWord;
int length;
int spacePos;
System.out.println("Enter a sentence ");
s = EasyIn.getString();
spacePos = s.indexOf(" ");
length = s.length();
for (i = length -1; i >= 0; i--)
{
currentWord = s.substring(0,spacePos);
s = s.substring(spacePos +1);
System.out.println("Current word is " + currentWord);
System.out.println("Sentence is now " + s);
}
}
}
First of all, you call
spacePos = s.indexOf(" ");
length = s.length();
only once, but these values should change with each iteration of the loop. Furthermore,
s.substring(spacePos +1);
with
spacePos == s.length()-1
means you are passing an index beyond the end of the string as the start index for substring(). Once you fix the first error, this will be your next exception.
Your problem is that you only get the index of the space once. This causes the program to cut the string every three characters, as the first word is three letters long. You need to update spacePos after each iteration.
I believe your problem is in your usage of your spacePos variable.
Outside the loop, you initialize the variable like so:
spacePos = s.indexOf(" ");
Which in your example string of "one two three", yields 3.
But then inside your loop, you never set the variable again, based on what whatever is left that you haven't processed.
Try re-calculating spacePos's value inside the loop and your problem should go away.
Your current approach is too error prone.
And you have too many variables.
Try this just as an idea.
class TestCurr {
public static void main(String[] args) {
String s = null;
System.out.println("Enter a sentence: ");
s = " one two three ";
System.out.println("|" + s + "|");
int i = 0;
int j = 0;
while (true){
while (i<s.length() && s.charAt(i)==' ') i++;
j = i;
if (i>=s.length()) break;
while (i<s.length() && s.charAt(i)!=' ') i++;
System.out.println("Current word is: [" + s.substring(j, i)+ "]");
System.out.println("Sentence is now: [" + s.substring(i) + "]");
if (i>=s.length()) break;
}
}
}
As others have stated, you only get the index once. But I'm curious, why re-invent the wheel?
String s = "one two three";
String[] split = s.split(" ");
for (String out : split) {
System.out.println("Word: " + out);
}
Question 1:
I am trying to count the frequency of a keyword, my code works except that it also counts
those words that also contain the keyword (for example, if I search "count", words like "account" will also be counted in.) Does someone know how to solve this?
Question 2:
I also wanna count the the number of unique words in a text (which means I count repeated word only once). I don't know how to achieve this either. My code only gives me the number of total words.
Here is my code:
import java.util.Scanner;
public class Text_minining {
/**
* #param args
*/
public static void main(String[] args) {
//Prompt the user for the search word
System.out.print("enter a search word: ");
//Get the user's search word input
Scanner keywordScanner = new Scanner(System.in);
String keyword = keywordScanner.nextLine();
keyword = keyword.toLowerCase();
//Prompt the user for the text
System.out.println("Enter a string of words (words separated by single spaces or tabs): ");
//Get the user's string input
Scanner userInputScanner = new Scanner(System.in);
String userInput = userInputScanner.nextLine();
userInput = userInput.toLowerCase();
int keywordCount = 0, wordCount = 0;
int lastIndex = 0;
while(lastIndex != -1){
lastIndex = userInput.indexOf(keyword,lastIndex);
if(lastIndex != -1){
keywordCount ++;
lastIndex = keyword.length() + lastIndex;
}
}
boolean wasSpace=true;
for (int i = 0; i < userInput.length(); i++)
{
if (userInput.charAt(i) == ' ') {
wasSpace=true;
}
else{
if(wasSpace == true) wordCount++;
wasSpace = false;
}
}
//Print the results to the screen
System.out.println("-------");
System.out.println("Good, \"" + keyword + "\"appears in the text and the word count is " + keywordCount);
System.out.println("The total number of unique words in the text is " + wordCount);
System.exit(0);
}
}
First: userInput.split(keyword).length - 1 will do the trick. Our use regex.
Second:
Set<String> uniqueWords = new HashSet<String>();
for (String word : userInput.split(" ")) {
uniqueWords.add(word);
}
System.out.println("Unique words count " + uniqueWords.size());
Just use string method split.
String words[] = userInput.split(keyword);
and then check and count the keyword...
for ( String w : words) {
// do check
}
Agree. Use split to create the array and then you can use
(new HashSet(Arrays.asList(yourArray))).size();
to find the count
I would suggest you this approach:
Split userInput string by white spaces: userInput.split("\\s+"). You will get an array. See String.split()
For question 1: iterate over the array comparing each string with your keyword. See String.equals() and String.equalsIgnoreCase().
For question 2: add the array to a Set. As this can't contain any duplicate item, its size will give you the answer.
I am trying to make a program, that lets me type in 10 characters and stores them in an array.
just single characters are enough, for example (d, s, a, e, h, j, e,). and then lets me look for one of the chars using linear search algorithm and gives out the position within the array.
I tried to program it but I can only do it with integers.
here is my code so far.
I don't know how to change it to letters / characters?
public static void main(String args[])
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " Letters");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("What letter do you want to find?");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
if (c == n) /* Searching element is absent */
System.out.println(search + " Letter is not found.");
I tried to program it but I can only do it with integers
No, you can do it if you use in.next().charAt(0) rather than in.nextInt() from Scanner Class to take the first Character form String.
I don't know how to change it to letters / characters?
Here you don't need to change it, or some regex or split it, the method in.next() get the String from the input (end-use) and then get the charAt(0) the first one.
Now, what i have changed in your code to be worked as you mentioned above:
Change search and array[] to char Data type.
Change the declaration of array[] to array = new char[n]
Change the input for search and array to in.next().charAt(0).
Try this:
public static void main(String args[]) {
int n,c;
char search,array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new char[n];
System.out.println("Enter " + n + " Letters");
for ( c = 0; c < n; c++) {
array[c] = in.next().charAt(0);
}
System.out.println("What letter do you want to find?");
search = in.next().charAt(0);
for ( c = 0; c < n; c++) {
if (array[c] == search) /* Searching element is present */ {
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
if (c == n) /* Searching element is absent */ {
System.out.println(search + " Letter is not found.");
}
}
}
The problem resides in your line array[c] = in.nextInt();. The nextInt() method of the Scanner class can read an integer, and only an integer.
You could try using array[c] = in.nextLine().charAt(0);, which would take any input from the console, store it temporarily as a String, get that String's first character, and store that. You would need to do the same to your second in.nextInt().
As an aside, it's generally bad practice to store char's in int's, even though it is valid Java. For example, I would change c and search to char's, and change array to a char[].
Here is a simpler approach, using Java's built-in functionality:
final Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of characters:");
final String input = in.next();
System.out.println("What do you want to find?");
final String search = in.next();
int pos = input.indexOf(search);
if (pos < 0) {
System.out.println("No match.");
} else {
while (pos >= 0) {
System.out.println("Found at location: " + pos);
pos = input.indexOf(search, pos + 1);
}
}
Differences:
There is only the scanning of the actual characters, because the length of the input defines how many characters the user actually wants to input.
The indexOf() method does about the same as your function, but it's faster and easier (because you don't actually need to code it).
This allows the user to scan for more than just one char. If that is not what is desired, I will leave it up to you to figure out how to change that. ;)