Finding letters in an array - java

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. ;)

Related

How to find the length of the second word in 3-word phrase without using loops or any built-in methods of java?

I want to know how you can find the length of the second word without using a for or a while loop and any built-in methods of java like substring, match, left or right...etc. This has to be done using the indexOf(); method and the char.
Sample input: The grey elephant ----> Sample output: Second letter has 4 words
I did this task using the for loop but our teacher restricted it, I want to know is that is there any way the for loop can be broken down, meaning keeping everything the same but removing the loop, and manually doing it. I don't want any other solutions, if you could just fix my code cuz the process is right and it works with the for loop. But I need it without it, I think if statements will do but idk where to put them.
Or if none work then I think it involves the overloaded version of the indexOf(); method. How would I use that?
Code:
else if (option == 2){
int first = -1;
int last = -1;
for (int x = 0; x < phrase.length() && x > phrase.indexOf(x); x++){
char n = phrase.charAt(x);
if (n == ' ' && first == -1){
first = x;
}
else if (n == ' '){
last = x;
}
}
int length = last - first - 1;
System.out.print("Second word has "+length+" letters");
}
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index1 = phrase.indexOf(' ');
int index2 = phrase.indexOf(' ', index1 + 1);
System.out.println("Length of the second word is " + (index2 - index1 - 1));
}
}
}
A sample run:
Enter option: 2
Enter phrase: The grey elephant
Length of the second word is 4
Another sample run:
Enter option: 2
Enter phrase: Good morning world!
Length of the second word is 7
[Update]
Posting the following update based on OP's request to find the length of the first word and that of the last word.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int firstIndex = phrase.indexOf(' ');
System.out.println("Length of the first word is " + firstIndex);
System.out.println("Length of the last word is " + (phrase.length() - phrase.lastIndexOf(' ') - 1));
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the first word is 4
Length of the last word is 5
Here it is how you can calculate the length of the 2nd word (assuming the separator character of the string is only one space.
String str = "The grey elephant";
int start = str.indexOf(' ');
int end = str.indexOf(' ', start+1);
int lengthSecondWord = end - start - 1;
System.out.println("2nd word length " + lengthSecondWord);

How to search for space in a Java String?

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();
}

Using java, how do count the occurrences of a character in a string, and then format an output with text listing the locations using loops

I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;
public class GimmeAW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Line\nEntering -1 exits the program")
String aLine;
aLine = input.nextLine();
char one = aLine.charAt(0);
char two = aLine.charAt(1);
if (one == '-' && two == '1') {
System.out.println("System Exit");
System.exit(1);
}
for (int i = 0; i < aLine.length(); i++) {
if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
int location = i;
System.out.print(" " + i);
}
}
}
To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();
for(int i = 0; i < ch.length; i++) {
System.out.print("The character " + ch[i] + " is at locations ");
// searching
for(int j = 0; j < l; j++) {
if(aLine.charAt(j) == ch[i]) {
System.out.print(j + " ");
}
}
System.out.println();
}
And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
// code
// want to repeat ??
choice = in.nextLine();
} while(choice.equals("yes"));

How would I take a user-input number and work on its digits individually?

I'm prompting a user for a number and am trying to determine the amount of even, odd, and zeros in that number
/* This program will determine and print the number of even, zero, and odd digits in
* an integer
*
* Author: Marco Monreal
* Date: 11/01/2016
*/
import java.util.Scanner;
public class PP5_3
{
public static void main(String[] args)
{
String exit_loop, go_again, user_num, first_char_string;
int odds, evens, zeros;
int first_char; //, second_char, third_char, fourth_char, fifth_char, sixth_char, seventh_char, eighth_char, ninth_char, tenth_char;
Scanner scan = new Scanner (System.in);
evens = 0;
odds = 0;
zeros = 0;
exit_loop = "no"; //initializing while loop
while (exit_loop.equals ("no"))
{
System.out.println ("Choose any number between 0 and 2,147,483,647. Don't include commas please.");
user_num = scan.next ();
I'm getting stuck around this area; "first_char" is not returning the digit value that I want/need.
//assigning a variable to each character of user_num
first_char = user_num.lastIndexOf(0);
/*second_char = user_num.charAt(1);
third_char = user_num.charAt(2);
fourth_char = user_num.charAt(3);
fifth_char = user_num.charAt(4);
sixth_char = user_num.charAt(5);
seventh_char = user_num.charAt(6);
eighth_char = user_num.charAt(7);
ninth_char = user_num.charAt(8);
tenth_char = user_num.charAt(9);*/
//copy every character into a string value
first_char_string = String.valueOf(first_char);
if (first_char == 2 || first_char == 4 || first_char == 6 || first_char == 8)
{
evens++;
}
else if (first_char_string.equals("1") || first_char_string.equals("3") || first_char_string.equals("5") || first_char_string.equals("7") ||
first_char_string.equals("9"))
{
odds++;
}
else
zeros++;
} //ends while loop
System.out.println ("There are " +evens+ " even numbers, " +odds+ " odd numbers, and " +zeros+ "zeros in ");
scan.close ();
} //ends main method
} //ends class
Hi take a look on this line:
user_num = scan.next (); // this will scan your user input, but does not jump to the next line
you might want to use:
user_num = scan.nextLine();
Also you made a mistake in your lastIndexOf(char) method.
This method expects a char. you supply this method an int e.g:
first_char = user_num.lastIndexOf(0);
this works because java interprets your number a an ASCI-number. the char representated by ASCI "0" is null. What you want to do is search for the character '0'. Like the following:
first_char = user_num.lastIndexOf('0');
The same for your equalisations:
first_char == 2 ---> first_char == '2';
Another notice. Please use camel case istead of underscores. instead of user_num you should write userNum. Thats the standard.
Yet another notice. The lastIndexOf() method will return the nummber of the last occurence of the parameter. e.g:
String test = "hello test";
test.lastIndexOf(e); // this will return 7 for it is the number ofthe last occurence of 'e'
I think yu want to use charAt(0) this returns the charactere at specified position
Last Notice. why are you comparing char values representing numbers ?
why not do the following:
int userNum = Integer.valueOf(yourCharHere).
Update
If I understood your comment correctly the your 'X' in the snippet below is defined by the user
first_char = userNum.charAt(X);
If I get you right you have a problem because you dont know how long the input of the user is. Instead of assigning the individual numers to variables I would do the following:
//Parsing your String into a int
int userNum = Integer.valueOf(yourUserInputHere);
Arraylist singleDigits = new ArrayList()<>;
//This goes through all digits of your number starting with the last digits
while (userNum > 0) {
singleDigits.add( userNum % 10);
userNum = userNum / 10;
}
//Reverses your list of digits
Collections.reverse(singleDigits);
Example input: 13467
your List should look like: [1],[3],[4],[6],[7]
This enables you to get the single digits by calling:
singleDigits.get(0) -> [1];
singleDigits.get(3) -> [6];
...
I hope that helps
First create sets that are containing odd/even/zero numbers:
Set<Integer> odds = "13579".chars().boxed().collect(Collectors.toSet());
Set<Integer> evens = "02468".chars().boxed().collect(Collectors.toSet());
Set<Integer> zero = "0".chars().boxed().collect(Collectors.toSet());
Then get an input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Choose a number:");
String number = scan.next();
scan.close();
Parse number character by character to find out how many digits are matching each set:
long numberOfOdds = number.chars().filter(odds::contains).count();
long numberOfEvens = number.chars().filter(evens::contains).count();
long numberOfZeros = number.chars().filter(zero::contains).count();
Finally, display the result:
System.out.println("There are " + numberOfEvens + " even numbers, " + numberOfOdds + " odd numbers, and " + numberOfZeros + " zeros in ");

Inputting a number then reversing it

Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}

Categories