I use sort() to sort my array alphabetically, but it does so from A-Z to a-z. I try to capitalize each word beforehand, but it doesn't work unless it's being printed out, which should be happening after the sorting. At the moment, with this code, it will list the pupils with capital letters, but if it was inputted as lowercase, it will be sorted as lowercase. Putting the capitalize() in the initial for loop, right after assigning the input to the array, doesn't work. Any solutions?
import java.util.Scanner;
import java.util.Arrays;
public class Pupils {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean loop = true;
int names = 0;
String[] ay = new String[1000];
for(int i = 0; loop == true; i++) {
System.out.println("Enter name: ");
ay[i] = scan.nextLine();
names++;
if (ay[i].equals("0")) {
loop = false;
ay[i] = " ";
}
}
String[] aay = new String[names - 1];
for(int i = 0; i < aay.length; i++) {
aay[i] = ay[i];
}
if (names == 1) {
System.out.print("There are no people in our class.");
} else if (names == 2) {
System.out.print("The person in our class is ");
} else {
System.out.print("The people in our class are ");
}
Arrays.sort(aay);
for(int i = 0; i < names - 1; i++) {
if(i == names - 2) {
System.out.print(capitalize(aay[i]) + ".");
} else if (i == names - 3) {
System.out.print(capitalize(aay[i]) + " and ");
} else {
System.out.print(capitalize(aay[i]) + ", ");
}
}
}
public static String capitalize(String line)
{
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
}
What about using Arrays.sort() with a Comparator? Note that there is a suitable comparator defined in String, so:
Arrays.sort(aay, String.CASE_INSENSITIVE_ORDER);
should do the job.
I suggest storing all the data in the array in lowercase. It will simplify sorting as well as search (if you search for a student in the array, and it was entered as, say "Walter" and you are looking for "walter", you won't find it. If you use lowercase both for storage and for search, it will work).
And since you capitalize the names for printing anyway, the names will still be displayed capitalized.
So instead of doing
ay[i] = scan.nextLine();
You can do:
ay[i] = scan.nextLine().toLowerCase();
Related
I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers
I have to search a string in an array from the user input, but I have an error in my logic. Even when the user input is in the array I still get "data not found"
I also have to display the index where the string is located in the array if it's found but got an error there too.
Below is the code I've tried.
This was the original question
create a program that ask user to insert 5 names.
store names in array
ask user to insert the name they want to find from the list created earlier
if name found, display "data found at [index]"
if not, display "data not found". Hint; use Java method equals to compare two strings.
package stringsearch;
import java.util.Scanner;
public class StringSearch
{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
String [] names = new String[5];
for (i = 0; i < names.length; i++)
{
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
if (names.equals(inName)){
System.out.println("Data found at ["+i+"]");
}
else
{
System.out.println("Data not found!");
}
}
}
You need to compare the value of inName with each of the values stored in the array, not with the array itself. You access each of the values stored in the array using the index starting with 0.
for (i = 0; i < names.length; i++) {
if (inName.equals(names[i])) {
System.out.println("Data found at [" + i + "]");
break;
}
}
// If the value stored in `inName` is found, the value of `i` will not reach up
// to the value equal to `names.length` because of the `break` statement. If the
// value of `i` has reached there, it means that the value stored in `inName`
// has not been found.
if (i == names.length) {
System.out.println("Data not found!");
}
Complete program:
import java.util.Scanner;
public class StringSearch {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
String[] names = new String[5];
for (i = 0; i < names.length; i++) {
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
for (i = 0; i < names.length; i++) {
if (inName.equals(names[i])) {
System.out.println("Data found at [" + i + "]");
break;
}
}
// If the value stored in `inName` is found, the value of `i` will not reach up
// to the value equal to `names.length` because of the `break` statement. If the
// value of `i` has reached there, it means that the value stored in `inName`
// has not been found.
if (i == names.length) {
System.out.println("Data not found!");
}
}
}
A sample run:
Enter name 1 > John
Enter name 2 > Harry
Enter name 3 > Sam
Enter name 4 > Cristina
Enter name 5 > Manny
Input Name to compare > Sam
Data found at [2]
You are comparing the whole array to a single string, that will always return false.
It's the same as:
String[] names = {"a", "b", "c"};
names.equals("d");
Iterate the array to see if there string is there
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
return i;
}
i++
}
if (i == names.length ) {
// not found
}
Running example:
public class A {
public static void main(String...args){
String[] names = {"a", "b", "c"};
String inName = "d";
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
System.out.println(i);
break;
//return i;
}
i++;
}
if (i == names.length ) {
System.out.println(-1);
// not found
}
}
}
I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need to test for consecutive numbers in any order. My program seems to work ok when I type in numbers in order like 1,2,3 or 8,3,3, but I need this to read the numbers in any order, for example 3,2,4 should return true.
Examples that should return true:
(1,2,3)
(3,2,4)
(-10,-8,-9)
Examples that should return false:
(3,5,7)
(1,2,2)
(7,7,9)
.
import java.util.*;
public class Consecutive {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println("The numbers (" + numbers + ") is '" + consecutive(numbers) + "'");
}
private static boolean consecutive(String str) {
char c = str.charAt(0);
for (int cc = 1; cc < str.length(); cc++)
if ((c + 1) != str.charAt(cc))
return false;
else
c++;
return true;
}
}
Based on a few assumptions (you want them in any order, they will always be comma-delimited), you will need to check for consecutivity on a sorted array with some like the follows:
String[] split = str.split(",");
int[] numbers = new int[split.length];
for (int i = 0; i < split.length; i++)
numbers[i] = Integer.parseInt(split[i]);
Arrays.sort(numbers);
(...now check for consecutivity...)
Try this approach:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Consecutive {
private ArrayList<Integer> numberList;
public Consecutive() {
numberList = new ArrayList<Integer>();
fetchInput();
sortNumberList();
System.out.println(isConsecutive());
}
private void fetchInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any amount of numbers"
+ " separated by space.\n" + "Exit by typing any letter and"
+ " pressing Enter key.");
while (scanner.hasNextInt()) {
numberList.add(scanner.nextInt());
}
scanner.close();
}
// Sort the list in ascending order
private void sortNumberList() {
Collections.sort(numberList);
}
private boolean isConsecutive() {
// Loop through the sorted number list
for (int index = 0, length = numberList.size() - 1; index < length; index++) {
// Check if the two adjacent numbers are differing by the value 1 or
// not.
if (numberList.get(index + 1) - numberList.get(index) != 1)
return false;
}
return true;
}
public static void main(String[] args) {
new Consecutive();
}
}
First fetch the input, and store the input in an Array. Sort the array, and then check if the sorted array has any adjacent elements which don't differ by the value of 1.
If there is any such adjacent pair, then that means that the elements that were entered weren't consecutive.
Hope it helps.
Using the sort method suggested by stendika; first convert to an array, removing all the commas, then sort and compare elements.
import java.util.*;
public class Consecutive{
public static void main (String [] args){
Scanner console= new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println( "The numbers (" + numbers + ") is '" + consecutive( numbers ) + "'" );
}//end of main
private static boolean consecutive(String str) {
String[] numbers = str.split(",");
Arrays.sort(numbers);
for (int index = 0; index < numbers.length-1; index++){
if (Integer.parseInt(numbers[index]) > Integer.parseInt(numbers[index+1])){
return false;
}
}
return true;
}//end of consecutive method
}
I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}