Int and String array in Java - java

public class CHECK {
public CHECK(){
String []wrkrs = {"Денис", "Саша", "Наталья", "Анатолий", "Юра", "Коля", "Катя", "Дима", "Антон","Тамара"};
int [] wrkrsPhone = {22626,22627,22628,22629,22630,22631,22632,22633,22634,22635};
String a = JOptionPane.showInputDialog(null, "Hello,friend!Do you wanna know, is that guy at work?Enter name:");
if(Arrays.asList(wrkrs).contains(a)){
JOptionPane.showMessageDialog(null, "That guy is at work!");
JOptionPane.showMessageDialog(null, "calling " + wrkrsPhone[wrkrsPhone.toString().indexOf(a)]);
}else{
JOptionPane.showMessageDialog(null, "Такого сотрудника нет!");
}
}
I have two arrays, which contain ints and strings. As you can see, I want to add the number of elements in the string array (for example, wrkrs number 3) to the int array, called wrkrs phone. How can i do it? I tried IndexOf, but it doesn't work.
The output, i want is something like:
Enter name:
Юра
That guy is at work!
Calling Юра + wrkrsPhone(Юра).

A better solution would be to have a Worker class that would contain the worker's name and their phone number.
Then you can use a HashMap<String,Worker> instead of your arrays to store the data.
This makes the search more efficient :
Map<String,Worker> workersMap = new HashMap<>();
workersMap.put ("Денис", new Worker ("Денис", 22626));
...
Worker worker = workersMap.get(a);
if (worker != null) {
call (worker.getPhone()); // or do whatever you want to do with the phone number
}
This is more efficient than Arrays.asList(wrkrs).contains(a), which performs linear search on the List.

...
List list = Arrays.asList(wrkrs);
if(list.contains(a)){
JOptionPane.showMessageDialog(null, "That guy is at work!");
JOptionPane.showMessageDialog(null, "calling " + wrkrsPhone[list.indexOf(a)]);
}
...
U better use a Map or extract a class Contact which have name and phone property but i think this is what u looking for :)

Related

Is there a function to count iterations of for each loops in Java?

I'm starting out on Java and I'm creating a basic phonebook application.
I'd like to implement a "Search Contacts" function that searches through an ArrayList of contacts and returns a count of how many contacts match the user-inputted String using a for each loop and if statement.
Question is, is it possible to receive a count of the contacts that match the user's search input without first defining an int - say, int counter = 0; - and then updating it within the if statement?
Below is an example of the only method I know could work to tally the number of matching contacts:
int counter = 0;
System.out.println("Please enter name of contact: ");
String nameRequest = scanner.nextLine();
for (Contact c: contactList) {
if (nameRequest.equals(c.getName())){
counter++;
System.out.println(counter + " contact(s) found"
System.out.println("Name: " + c.getName());
}
}
Extras: How could I go about so the code also returns contacts that are only a partial match? e.g. User inputs "Michael" but there are no contacts that only contain "Michael". There are however contacts called "Michael B Jordan" and "Michael Schumacher" which I'd like returned for the partial match.
Thanks in advance!
Using the counter variable it is a standard for people in this cases. But if it is for study purposes, you can achieve this with Lambda, where you first select the contacts, get the names and store in a temporary list:
List<String> contactsFound = contactList.stream()
.map(Contact::getName)
.filter(nameRequest::equals)
.collect(Collectors.toList());
System.out.println(contactsFound.size() + " contact(s) found");
contactsFound.forEach(contactName -> System.out.println("Name: " + contactName));
Here is the same basic solution as Brothers answer but with a for loop (as in the question):
List<String> contactsFound = new ArrayList<>();
for (Contact c: contactList) {
if (c.getName().toLowerCase().contains(nameRequest.toLowerCase())){
contactsFound.add(c.getName());
}
}

How can i turn this chatter bot into an array that scans user input

Hey so basically I have an assignment to make a simple chatter bot, the purpose of he program is to have a user input a string with a JOptionpane and then the program will search the user input the see if anything they wrote contained a key word I specified, if so they program will display a certain message. So far iv written it using if-else statements but the teacher wants us to use Arrays (which I have no idea how they work and we are just expected to know)
import javax.swing.JOptionPane;
public class ChatterBot {
public static void main(String args[]) {
String input = "";
String maths = "";
String science = "";
String chemFact = "";
String bioFact = "";
String zooFact = "";
String algFact = "";
String yes = "Well good for you";
String no = "You learn something new everyday :)";
input = JOptionPane
.showInputDialog("Pick one of the subjects listed to learn a fun fact (english, science, maths) ");
if (input.contains("science")) {
science = JOptionPane.showInputDialog(
"What kind of science fact woukd you like to know about? (chem, Biology, Zoology)");
}
else if (input.contains("maths")) {
maths = JOptionPane.showInputDialog(
"What kind of maths fact would you like to know about? (algebra, fractions, division) ");
}
if (maths.contains("algebra")) {
algFact = JOptionPane.showInputDialog(
"\"Did you know a mathematician who specializes in algebra is called an algebraist? (yes or no)\"");
}
if (algFact.contains("yes")) {
System.out.println(yes);
} else if (algFact.contains("no")) {
System.out.println(no);
}
if (science.contains("chem")) {
chemFact = JOptionPane.showInputDialog(
"Did you know If you pour a handful of salt into a full glass of water the water level will actually go down rather than overflowing the glass? (yes or no)");
}
if (chemFact.contains("yes")) {
System.out.println(yes);
} else if (chemFact.contains("no")) {
System.out.println(no);
}
else if (science.contains("biology")) {
bioFact = JOptionPane.showInputDialog("Did you know The brain itself cannot feel pain? (yes or no)");
}
if (bioFact.contains("yes")) {
System.out.println("Well good for you");
} else if (bioFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
else if (science.contains("zoology")) {
zooFact = JOptionPane
.showInputDialog("Did you know butterflies have taste receptors on their feet? (yes or no)");
}
if (zooFact.contains("yes")) {
System.out.println("Well good for you");
} else if (zooFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
if (input.contains("?")) {
System.out.println("I will be asking the questions");
}
}
There are plenty of good tutorials online about java arrays. Additionally, if your class is following a text book of any sort, then it should also have arrays covered as well. https://www.tutorialspoint.com/java/java_arrays.html
Just from a quick google.
In general an array is a data structure that holds objects in a list like function.
Generically speaking
type[] var = new type[size];
or
type[] var = {foo0, foo1, foo2...};
Real Examples
int[] intergerArray = new int[10];
String[] stringArray = {"Hello", "World"};
Indexes Generically
var = array variable
index = position of object - 1 (computers start at 0)
var[index] will return the value stored in position index from the var array
Index Examples
Make the array:
String[] stringArray = {"This", "is", "my", "first", "array"};
Access the first value:
stringArray[0];
Store the value in a variable:
String firstWord = stringArray[0];
You can even iterate through the entire array all at once:
for (int i = 0; i < stringArray.length; i++){
System.out.print(stringArray[i]);
}
Outputs:
This is my first array
For your code
I'd recommend putting your possible inputs in an array (or even in a couple of arrays)
String[] subjects = {"English", "Science", "Maths"};
You can then accept an input from the user and loop through your array to see if it matches one of your supported inputs. Also, generally you want to include a 'default' case for invalid input.
Possible Implementation
import javax.swing.JOptionPane;
public class ChatterBot{
public static void main(String[] args){
String[] subjects = {"English", "Maths", "Science"};
String userInput = JOptionPane
.showInputDialog("Pick one of the subjects listed to learn a fun fact (english, science, maths) ");
if (userInput.contains(subjects[0]){
// english facts
} else if (userInput.contains(subjects[1]){
// science facts
} else if (userInput.contains(subjects[2])){
// maths facts
}
}
}

How not to allow variable input not of type STRING

I have two questions, first of all I have software that takes names and I want to not allow the reception of a variable that is not String How do I do it? And second thing I did a code section whose goal is to sort songs according to their singer (he gets an array of songs containing the name of the singer and I want him to make a list of songs that each singer has) but something that does not work.
Thank you:)
this is the code:
public void miunBySinger(Song[] song3){
int place =0;
int numChecking = 0;
System.out.println("this is your songs list sorts by name of singer");
for (int i = 0; i < song3.length; i++) {
System.out.println("song of"+song3[i].getSinger()+ ":");
for (int i1 = 0; i1 < song3.length; i1++) {
if (song3[place].getSinger().equals( song3[place+numChecking].getSinger())){
System.out.println(song3[place+numChecking].getName());
}
if (numChecking + place < song3.length) {
numChecking++;
}else {
numChecking =1;
place++;
}
}
}
}
You have the code:
if (numChecking + place < song3.length) {
numChecking++;
The problem is that if numChecking + place is exactly 1 less than song3.length, then when you increment numChecking, numChecking + place will then be equal to song3.length. So when you try to access the array at that index, it will be off the end of the array.
"first of all I have software that takes names and I want to not allow
the reception of a variable that is not String. How do I do it?"
To you.... what would not be considered a String? If you set your input mechanism to only accept a String then golly gee, that's what you'll get. In reality it's all a matter of what characters you would allow to be within a String so you can use the String.matches() method to carry out a mild form of validation on the String contents which is input from User (or whatever the input source might be).
Let's pretend that we have a String variable named artist and we are going to accept User input to fill that variable with a valid name from the Console window. If the name String isn't found to be valid (according to our rules) then we inform the User and let him/her try again.
To begin with you need to decide what the 'name validity rules' are and for the sake of this simple example we are just going to have these:
Allow any alpha letters from a to z or A to Z;
Allow commas (,);
Allow periods (.);
Allow hyphens (-);
Allow apostrophes (');
Allow white-spaces;
Don't allow any other keyboard character other than rules 1 to 6.
The above rules can be easily applied to the String.Matches() method using a Regular Expression (RegEx) since the method accepts them. To institute the above rules we will use the following RegEx:
"[a-zA-Z.,'\\- ]+"
and here is an explanation of what the RegEx does:
To implement what is mentioned above you might have code that looks like this:
Scanner userInput = new Scanner(System.in);
String artist = "";
while (artist.equals("")) {
System.out.print("Please enter a Singer Name (or quit): -> ");
artist = userInput.nextLine();
if (artist.equalsIgnoreCase("quit")) {
System.err.println("Bye-Bye");
System.exit(0);
}
// Regular Expression used to validate input.
// Notice the NOT operator (!).
if (!artist.matches("[a-zA-Z.,'\\- ]+")) {
System.err.println("Invalid Name! Try again...\n");
artist = "";
}
}
// Any Continuing Method Code Here:
System.out.println("Processing songs for the singer: " + artist
+ "\nPlease wait...\n");
Again, you need to be the one that determines the rules for what would be considered "a valid String". This isn't too difficult for names of people. Letter case is not really an issue either in this particular situation since the String class does have the String.equalsIgnoreCase() method as well. Just add the characters you want allowed for validation within the Regular expression but do keep in mind that some characters (like the hyphen) are considered special RegEx characters and need to be Escaped with the Escape character (\).
"second thing I did a code section whose goal is to sort songs
according to their singer (he gets an array of songs containing the
name of the singer and I want him to make a list of songs that each
singer has) but something that does not work."
I had to read this a few times to get a grasp of what I think you're really asking here and to be honest, I'm still not sure. Are you talking about sorting or do you actually mean "display song titles according to their respective Artists in a list type fashion"? Perhaps it's both.
In any case sorting is the way to go and there are a lot ways to do it in Java. At this time it's also important to note that it would of been helpful if you had also provided the code for the Song Class so for the sake of the examples shown below I created a Songs Class:
The Songs Class:
public class Songs {
private String songTitle;
private String artistName;
public Songs(String songName, String singerName) {
this.songTitle = songName;
this.artistName = singerName;
}
public Songs() {
songTitle = null;
artistName = null;
}
public String getTitle() {
return songTitle;
}
public void setTitle(String songName) {
this.songTitle = songName;
}
public String getArtist() {
return artistName;
}
public void setArtist(String singerName) {
this.artistName = singerName;
}
public void sort(Songs[] songs) {
List<String> list = new ArrayList<>();
// Place the songs array into a List collection as a single
// string placing the Artist first and using the Pipe (|)
// character as a delimiter between Artist and Title. This
// ensures that the sorting will be done based on the Artist's
// name will be sorted and because Titles with the same artist
// the titles appear to be sorted as well. This can also be
// done with a Comparator but this allows you to clearly see
// what's going on and allows you to make the sort the way you
// want.
for (Songs song : songs) {
list.add(song.getArtist() + "|" + song.getTitle());
}
// Sort the collection (ascending order)
Collections.sort(list);
// Convert the List back into our original songs Array
for (int i = 0; i < list.size(); i++) {
String[] tmp = list.get(i).split("\\|");
songs[i] = new Songs(tmp[1], tmp[0]);
}
}
#Override
public String toString() {
return songTitle + " By " + artistName;
}
}
You will notice that in this Songs class there are what you would expect to be typical Fields along with Getter and Setter methods but there is also a custom toString() method and a sort() method which only excepts a single dimensional Songs[] Array as an argument. This way you can keep the sorting business in one house so to speak.
Let's create a Songs Array:
Songs[] songs = new Songs[10];
songs[0] = new Songs("Up On The Roof", "The Drifters");
songs[1] = new Songs("On Broadway", "The Drifters");
songs[2] = new Songs("It's All Over Now", "The Rolling Stones");
songs[3] = new Songs("Time Is On My Side", "The Rolling Stones");
songs[4] = new Songs("Dance, Dance, Dance", "The Beach Boys");
songs[5] = new Songs("Do You Wanna Dance", "The Beach Boys");
songs[6] = new Songs("I Don't Believe In You", "Talk Talk");
songs[7] = new Songs("I Believe In You", "Talk Talk");
songs[8] = new Songs("Hold On", "Wilson Phillips");
songs[9] = new Songs("Release Me", "Wilson Phillips");
This array contains 10 song Titles and the 5 Artists that sang them. As you can see there is no real sorting to the elements of the array but we'll take care of that now with our Songs.sort() method and then we'll list the Artists to the Console Window with their related Song Titles beneath them:
// Sort the songs Array..,
new Songs().sort(songs);
// Display the Array by artist and their related titles.
String currentArtist = "";
// Iterate through the songs Array
for (int i = 0; i < songs.length; i++) {
String artistName = songs[i].getArtist(); // artist from current song index
String songTitle = songs[i].getTitle(); // Titlet from current song index
// Make sure we only display the Artist once.
if (!currentArtist.equals(artistName)) {
System.out.println("\nSongs By: " + songs[i].getArtist());
}
// Display the Title(s) relate to the current Artist
System.out.println("\t " + songs[i].getTitle());
currentArtist = artistName; // Update who is the current Artist
}
When the above code is run the Console Window will display:
Songs By: Talk Talk
I Believe In You
I Don't Believe In You
Songs By: The Beach Boys
Dance, Dance, Dance
Do You Wanna Dance
Songs By: The Drifters
On Broadway
Up On The Roof
Songs By: The Rolling Stones
It's All Over Now
Time Is On My Side
Songs By: Wilson Phillips
Hold On
Release Me
Notice how the Artists are listed in alphabetical order as are the song Titles beneath them.
Tying it all together...
Now it's time to put it all together whereas we're going to create a console display application where the User is asked to enter the name of a particular Artist and the app will seek through the songs Array and create yet another array named artistSongs based on that artist name supplied if it exists. If the artist name doesn't exist then the User is notified and given the opportunity to enter another Artist name (or quit the application by entering quit).
To completely pull this off we'll need yet another method named getSongsByArtist() which will take our songs array and the User supplied artist name as arguments so as to build our artistSongs Array. Here is the whole runnable code (you will need the Songs class posted above):
The Console Application (requires Songs Class above):
package songsexample;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SongsExample {
public static void main(String[] args) {
new SongsExample().startApp();
}
private void startApp() {
// Declare and initialize the songs array for 10 songs.
Songs[] songs = new Songs[10];
// Fill the Array...
songs[0] = new Songs("Up On The Roof", "The Drifters");
songs[1] = new Songs("On Broadway", "The Drifters");
songs[2] = new Songs("It's All Over Now", "The Rolling Stones");
songs[3] = new Songs("Time Is On My Side", "The Rolling Stones");
songs[4] = new Songs("Dance, Dance, Dance", "The Beach Boys");
songs[5] = new Songs("Do You Wanna Dance", "The Beach Boys");
songs[6] = new Songs("I Don't Believe In You", "Talk Talk");
songs[7] = new Songs("I Believe In You", "Talk Talk");
songs[8] = new Songs("Hold On", "Wilson Phillips");
songs[9] = new Songs("Release Me", "Wilson Phillips");
// displayAllSongs(songs);
Scanner userInput = new Scanner(System.in);
String artist = "";
while (artist.equals("")) {
// Prompt for Artist name from User
System.out.print("\nPlease enter a Artist Name (or quit): -> ");
artist = userInput.nextLine();
if (artist.equalsIgnoreCase("quit")) {
System.out.println("Bye-Bye");
System.exit(0);
}
// Is the supplied name from User valid (meets our rules)?
if (!artist.matches("[a-zA-Z.,'\\- ]+")) {
// No it's not. Inform & allow User to try again
System.err.println("Invalid Artist Name! Try again...\n");
artist = "";
continue; // Go to top of loop.
}
// Name is valid...
System.out.println("Processing songs for the Artist: " + artist
+ "\nPlease wait...");
// Get song titles by the Artist supplied from User
Songs[] artistSongs = getSongsByArtist(songs, artist);
// Are there songs by Artist?
if (artistSongs.length > 0) {
// Yes there is...
new Songs().sort(artistSongs); // Sort the artistSongs Array.
//sortSongs(artistSongs); // Sort the artistSongs Array.
// Display the Artist's name.
System.out.println("\nSongs By: " + artistSongs[0].getArtist());
//Display the Artist's song titles...
for (int i = 0; i < artistSongs.length; i++) {
System.out.println("\t " + artistSongs[i].getTitle());
}
}
else {
// No such artist found.
System.out.println("There are no found Titles by: " + artist);
}
artist = "";
}
}
private void displayAllSongs(Songs[] songs) {
// Sort the songs Array..,
new Songs().sort(songs);
// Display the Array by artist and their related titles.
String currentArtist = "";
// Iterate through the songs Array
for (int i = 0; i < songs.length; i++) {
String artistName = songs[i].getArtist(); // artist from current song index
String songTitle = songs[i].getTitle(); // Titlet from current song index
// Make sure we only display the Artist once.
if (!currentArtist.equals(artistName)) {
System.out.println("\nSongs By: " + songs[i].getArtist());
}
// Display the Title(s) relate to the current Artist
System.out.println("\t " + songs[i].getTitle());
currentArtist = artistName; // Update who is the current Artist
}
}
public Songs[] getSongsByArtist(Songs[] songs, String artistName) {
List<Songs> list = new ArrayList<>();
for (Songs song : songs) {
// See if the artist name in Array contains the
// supplied artist name. Everything is brought to
// lowercase so that there is no case sensitivity
// and the String.contains() method is used to reduce
// some need for name accuracy.
if (song.getArtist().toLowerCase().contains(artistName.toLowerCase())) {
list.add(song);
}
}
return list.toArray(new Songs[0]);
}
}

String concatenation in relation to JOptionPane

So, I haven't done any programming in a few months because I'm taking general prerequisite courses right now and I have a job, so now I'm a little rusty and I'd like to be up to par for when I take my next programming class in the Fall. Long story short, I'm trying to get back on track, so I'm making a silly practice program.
I made this program with all input and output done through the console using a Scanner, but then decided to go ahead and move over to JOptionPane as an interface. It was a pretty easy transition overall, but I'm just having a problem with the output at the very end. I'm trying to make all of the elements of an array into a nice, grammatically correct String for easy output in JOptionPane, but I can't really get my concatenation to work correctly. I realize that the output is not grammatically accurate when the amount of cats is one or two. I'll work on that after this, it's an easy fix.
Here is the code:
import javax.swing.JOptionPane;
public class JavaTestClass {
public static void main(String[] args)
{
//Get number of cats
int numOfCats = Integer.parseInt(JOptionPane.showInputDialog("How many cats do you have?"));
JOptionPane.showMessageDialog(null, "Oh, so you have " + numOfCats + " cats.\n", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
//Get cat's names
String[] catNames = new String[numOfCats];
for(int i=0;i<numOfCats;i++)
{
catNames[i] = JOptionPane.showInputDialog("Enter the name of cat " + (i+1) + ": ");
}
//Output cat's names
String catNameList = null;
for(int i=0;i<numOfCats;i++)
{
if((i+1) == (numOfCats-1))
{
catNameList.concat(catNames[i] + ", and ");
}
else if ((i+1) == numOfCats)
{
catNameList.concat(catNames[i] + ".");
}
else
{
catNameList.concat(catNames[i] + ", ");
}
}
JOptionPane.showMessageDialog(null, "So your cat's names are: " + catNameList, "Names of cats", JOptionPane.INFORMATION_MESSAGE);
}
}
Sorry about the spacing. It didn't really come out the way I wanted it to on here, but I don't have all day the indent all of the lines just for the sake of the post. Anyway, it should be relatively obvious, even without my long description above what I'm trying to do. Any help would be much appreciated. Thanks in advance.
Strings are immutable. Every operation that modifies a String returns a new one.
So it should be:
catNameList = catNameList.concat(catNames[i] + ", and ");
Also don't initialize it to null.
String catNameList = "";
Reference the String concat javadoc. Concat method is returning the result of concatenation.

Prevent duplicate values in an array

How can i ask the user to reenter again if the value from the PID is already existed in the array ?
ex: he enter A then B and he enter A again, then the A he entered from the last will not be accepted because it's already existed.
int[] Process = {};
int NumberofProcess = 0;
String[] PID = new String[10]; //Proces ID
System.out.print("Enter a number of Process from 1 to 10 : ");
while(bError){
if(scan.hasNextInt()){
NumberofProcess = scan.nextInt();
}else{
scan.next();
continue;
}
bError = false;
}
//---------------- Ask for the user to input for the Process id AT and EX -------
for(int i=0;NumberofProcess > i;i++){
System.out.print("Please Enter a ProcessID " + (i + 1) + " : ");
PID[i] = scan.next();
}
I'd not use an array but a LinkedHashSet (assuming you want to preserve input order). Then check using the set's contains(...) method or try to add the PID using add(...) and check the return value (false if it has not been added, i.e. if it already existed in the set).
If you can use a Set instead, do as Thomas suggests and use either a normal HashSet if the order of the values is not important, and LinkedHashSet otherwise.
If you must use an array, use `Arrays.binarySearch' to check if the array already contains the string:
String pid = scan.next();
if (Arrays.binarySearch(PID, pid) < 0) {
PID[i] = pid;
}
Note: of course you need to import java.util.Arrays.
What you need is to create a structure were you would store the PID that user has already put in you system.
Then you should validate every new input, against items in that storage. If you find a collision you just notify user about it and repeat the process until he input valid data or choose to exit.
In Java you can used dedicated data structure called collections, that would speed up the finding process. The simple ArrayList wild be enough for your needs.
To declare
Collection<String> storage = new ArrayList<>();
To use
boolean wasStored = storage.contains(input);

Categories