Java arrays in 2 arraylist - java

I have to write a program which allows the user to keep track of all the countries he has visited, and their capitals using 2 arraylists: Countries and Capitals. The user has three options to choose from a menu, he may either:
Add a country and its corresponding capital in the Countries and Capital arraylists respectively.
Query the system for the capital of a country by inputing the country's name. (If the country was visited, the capital should be displayed, else he should be given an error message: “You did not visit this country”).
Exit the program
For example the arraylist Countries contains [“England”, “France”, “Reunion”, “Nepal”] and the one for Capitals contains [“London”, “Paris”, “St.Denis”, “Kathmandu”]. If the user has visited Kenya whose capital is Nairobi, and wishes to add this to the arraylists, the Countries and Capitals arraylists should become: [“England”, “France”, “Reunion”, “Nepal”, “Kenya”] and Capitals contains [“London”, “Paris”, “St.Denis”, “Kathmandu”, “Nairobi”] respectively. If he wished to query for the capital of France the system should display “Paris”. If the user wishes to look for the capital of Australia – the system should display “You did not visit this country”.
So here is what I have come up so far:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> countries = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
String country;
String capital;
String search;
countries.add("England");
countries.add("France");
countries.add("Reunion");
countries.add("Nepal");
ArrayList<String> capitals = new ArrayList<String>();
capitals.add("London");
capitals.add("Paris");
capitals.add("St Denis");
capitals.add("Kathmandu");
System.out.println("Please choose one option:");
System.out.println("1. Add a new country and its capital.");
System.out.println("2. Search for the capital of a country.");
System.out.println("3. Exit.");
int opt = sc.nextInt();
if (opt == 1) {
country = sc.nextLine();
capital = sc.nextLine();
countries.add(country);
capitals.add(capital);
} else if (opt == 2) {
System.out.println("Enter the capital of the country.");
search = sc.next();
for (int i = 0; i < countries.size(); i++) {
for (int j = 0; j < capitals.size(); j++) {
if (search.equals(capitals.get(j))) {
System.out.println("The country is " + countries.get(i));
}
}
}
} else {
System.exit(0);
}
}
}
But actually, the for loop apparently does not work as when I enter the capital of the city, the program just terminates right there.
EDIT: I can't use HashMap but lists

You can just use a HashMap, with the country as key and the capital as value:
HashMap<String, String> hashMap = new HashMap<String, String>();
// add data to the HashMap
hashMap.put("England", "London"); //assign value "London" to key "England"
// get data from the HashMap
hashMap.get("England"); //returns "London"
EDIT: If you still want to use lists, you can do the following to retrieve the corresponding value. The benefit of this is that it works both ways:
capitals.get(countries.indexOf("England")); //it will return "London"
countries.get(capitals.indexOf("London")); //it will return "England"
Note this will only work if the lists are properly ordered (so the first country matches the first capital, the second country matches the second capital, etc)

Oh boy. Quite a few problems here.
First of all: Your code has no problem (related to what you call the problem) with the for loop.
You main method executes exactly one of the if branches, and then terminates. If you want the program to run re-prompting the menu after every completed operation until the terminate option is requested, you need to wrap the menu in a while loop:
int opt= sc.nextInt();
while (opt != 3) {
if (...)
}
System.exit(0);
In second place: in Java you usually don't do paired arrays (i.e. two arrays that are semantically linked by the positions of their elements). You can either create a class:
class CountryAndCapital {
String country;
String capital;
//...
}
ArrayListy<CountryAndCapital> myArray = new ArrayList<>();
or, as other have suggested, use a Map, which is a data structure that links one data to another (in this case, the capital to the country), and also prevents duplicates (in a sense...):
Map<String, String> countryToCapital = new HashMap<>();
countryToCapital.put("France", "Paris");
//...
Finally: if your arrays are paired, there is no need to iterate over both! You can iterate over the country one and just take that index over to the capitals one:
for(int i=0; i<capitals.size();i++) {
if(search.equals(capitals.get(i))) {
System.out.println("The country is "+countries.get(i));
}
}

There is a problem with you approach: There are countries with more than one capital
I think a good data structure that fits your needs would be a
Map<County,Capital[]>
Maps are very useful, the docs are here
Bonus dumb thought: If I visited Vatican City State, I'd have been at the same time in Rome, although not in Italy. Well... that would be true if the Vatican City had an airport, otherwise I surely have been in Italy right before

Put your code in while loop
Use HashMap instead
Give message before getting input from user
always try to take whole line as input when getting input from console
HashMap<String, String> countries = new HashMap<>();
Scanner sc = new Scanner(System.in);
String country;
String capital;
String search;
countries.put("England", "London");
countries.put("France", "Paris");
countries.put("Reunion", "St Denis");
countries.put("Nepal", "Kathmandu");
while (true) {
System.out.println("Please choose one option:");
System.out.println("1. Add a new country and its capital.");
System.out.println("2. Search for the capital of a country.");
System.out.println("3. Exit.");
System.out.print("Enter your choice : ");
int opt = Integer.parseInt(sc.nextLine());
if (opt == 1) {
System.out.print("Country : ");
country = sc.nextLine();
System.out.print("Capital : ");
capital = sc.nextLine();
countries.put(country, capital);
} else if (opt == 2) {
System.out.print("Enter the capital of the country : ");
search = sc.nextLine();
for(Map.Entry<String, String> entry : countries.entrySet()){
if(search.equals(entry.getValue())){
System.out.println("The country is " + entry.getKey());
break;
}
}
} else {
System.exit(0);
}
}

Related

How to stop user from selecting the same number once more?

I have created an Array holding [24] data, and I assigned some information in each index. my problem is when I want to call the indexes using Scanner from the keyboard, let's say I called index[12] from the user, next time I call it I want it to say, u already selected that number, choose a different number so on so forth. basically, I shouldn't call the same index twice, what is the best thing to use.
your help is much needed.
Use a java.util.Set to store the selected indexed, for exmaple, java.util.HashSet.
It should look like:
Set<Integer> selected = new HashSet<>();
int userInput = ...; // get input from user
while (selected.contains(userInput)) {
// print u already selected that number, choose a different number so on so forth
userInput = ...; // get input from user
}
selected.add(userInput);
// do something with the index
You must save the index of selected numbers, and then you make a comparison of all new numbers with your list's elements.
Scanner s = new Scanner (System.in);
int choice = s.nextInt();
List<Integer> choiced = new ArrayList<Integer>();
while (true) {//or your condition
label:
for (Integer i : choiced) {
if (choice == i) {
System.out.println("Index already selected, please select a different one");
break label;
}
}
choiced.add(choice);
choice = s.nextInt();
}
I tried both of your ways but still could solve it here is my code how would u have applied the codes that u guys wrote in here.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = 0;
String [] differentChocolate = new String[24];
differentChocolate[0] = "You receive: A star that weighs 7 grams";
differentChocolate[1] = "You receive: Praline Bag Assorted 800g";
differentChocolate[2] = "You receive: Kinder Surprise Santa 75g";
differentChocolate[3] = "You receive: Woolworths Christmas Chocolate Net Bag 72g";
differentChocolate[4] = "You receive: Quality Street Tub 726g";
differentChocolate[5] = "You receive: Cadbury Favourites Snowman Bowl 700g";
differentChocolate[6] = "You receive: Lindt Santa Pouch Bag 80g";
differentChocolate[7] = "You receive: Praline Bag Assorted 800g";
while (true){
System.out.println("Choose a chocolate (0-23): ");
number = in.nextInt();
System.out.println(differentChocolate[number]);
}
}
}

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

Passing arrays as parameters and make calculations

I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].

How to compare a string to multiple string arrays

I'm trying to write a program in which the user inputs their grocery list then based upon the type of item it is the program will give you a good order to shop for your items(i.e puts the meats together and the vegetables together)
here's my current problem, I can't get the user input to compare to the multiple string type arrays I have of store items.
String[] VegiFruit = {"Apples", "Lettuce", "Broccoli"};
String[] Meats = {"Ground beef", "Hambuger"};
Scanner USER_IN = new Scanner(System.in);
Methods Use = new Methods(); //This is another class I have, it just makes printing empty lines and lines of **** look nicer
Use.border();
System.out.println("Enter Item name then follow instructions.");
Use.space();
System.out.print("Item 1: ");
String InptOne = USER_IN.nextLine();
}
for (int i = 0; i < VegiFruit.length; i++)
{
if(Arrays.asList(VegiFruit).contains(InptOne))
{
System.out.println("Item is a VEGI");
}
}
for(int p = 0; p < Meats.length; p++)
{
if(Arrays.asList(Meats).contains(InptOne))
{
System.out.println("Item is a MEAT");
}
}
you need not go through the loops as contains method will compare with all the elements in the list.
I ran your code and the below works fine.
if(Arrays.asList(VegiFruit).contains(InptOne))
{
System.out.println("Item is a VEGI "+InptOne);
}
if(Arrays.asList(Meats).contains(InptOne))
{
System.out.println("Item is a MEAT "+InptOne);
}
However, please note that this is case senstive comparison and if the user does not enter the vegetable in your format then it will not work.
To solve that problem, you can take 2 approaches:
Have the list of veegetables/meat in caps and make the input.toUpperCase() before comparing it in contain method.
2.Use the answer on Array contains() without case sensitive lookup?

Random Generate String from ArrayList without replacement in JAVA

I am trying to create a program that will allow users to enter a list of names. And then the program will pull from the ArrayList randomly and pull each name one at a time until all names have been used. I have the scanner part completed as seen below:
public class Auction
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String> ();
char quit = 'Y';
String playername = null;
while (quit == 'Y')
{
System.out.println("\nPlayer Name:");
playername = scan.next();
names.add (playername);
System.out.print("Enter Another Name? (Y/N) \n");
String word = scan.next();
word = word.toUpperCase();
quit = word.charAt(0);
}
}
}
I have another class where I tried to complete the random generation with no success. There doesn't appear to be any errors but it's not working either. I know I am way off on the "random without replacing" part but I was just trying to get it to work before I moved on. I'm not sure if I am even referencing the ArrayList from the other Auction Class. Like a lot of others, I am new to Java so be gentle. I have spent a week on this which should probably have taken me a few hours. I appreciate your help.
public class Draft
{
Random randomGenerator;
ArrayList<String> names;
String randName() {
int index = randomGenerator.nextInt(names.size());
System.out.println("Next on the Block" + names.get(index));
return names.get(index);
}
}
Just use Collections.shuffle() to shuffle the list itself:
Collections.shuffle(names);
Your list is now randomized and you can take elements from the top until it's empty. For example, using an iterator:
Iterator<List> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
it.remove(); // optionally remove
System.out.println("Next on the block" + name);
}
Or, if there's no need to actually remove the name from the list, using a simple for loop:
for (String name : names) {
System.out.println("Next on the block" + name);
}

Categories