in my program I want the user to be able to print an element from an array. This is how far I've and I can't think of what to put next?
public void viewClub() {
System.out.println("Please enter the name of the country whose details you would like to see");
String Name = input.next();
for (int i = 0; i < countryList.size(); i++) {
Country x = countryList.get(i);
if (Name.equalsIgnoreCase(x.getName())) {
}
You anyways have x.getName in which x points to ith element of the array. So even if you just do a sys out for
x.getName()
you will get the value.
Hope this be of some help
Happy Learning :)
You want to output the details of a country that the user inputs. To do this, you will need a function in your country class that returns a string containing the details of that country:
System.out.println(x.getCountryDetails());
You don't want to output the name, because the user already knows that.
After you find the country, you should break out of your loop, to stop further processing:
for (int i = 0; i < countryList.size(); i++)
{
if (name.equalsIgnoreCase(countryList.get(i).getname()))
{
System.out.println(countryList.get(i).getCountryDetails());
break; //Exit the for loop because you found the specified country
}
}
firstly you take a array in your program, then by using buffered input streams or any other take the input from the user, store it into the array and then print the array index which contain the values
Related
I am trying to print user input from an array to display in java. When i run this, it just prints out "null" for each amount no matter what the user inputs. I am a beginner at java and want to learn more about arrays, and I can't seem to figure this out.
String itemAmount = ss.getInputString("How many items?");
int amount = Integer.parseInt(itemAmount);
String[] Items = new String[amount];
for (int i = 0; i < Items.length; i++) {
ss.getInputString("Please enter items?");
}
for (int i = 0; i < Items.length; i++) {
ss.println((Items[i]));
}
Also, how would i be able to print the items, for example user inputs 3 items -> "Eggs", "Bacon", "Tomato" how would I print this to show in a line separated by commas.
I'm not sure what gt is, but since you're using it this way
String itemAmount = gt.getInputString("How many items?");
I guess it's some sort of wrapper around the standard input.
You can use it the same way to populate an array, one item at a time.
for (int i = 0; i < Items.length; i++) {
Item[i] = gt.getInputString("Please enter items?");
}
You seem to be able to use the array in the other loop, so I'll assume you don't need further explanation.
Then to print them on a single line, separated by a comma you can use the join method of String (note: you need to convert your array to a List, first)
String joinedString = String.join(", ", Arrays.asList(Items));
I think you are checking the length of wrong array/string in second for loop. It should be Items.length not Appliances.length
I am trying to find a contact by searching the first two names of the array below and then update the phone number associated with the contact. In the coding I've provided, I can find the first name of the contact (strFirstName) in the outer loop but can't verify that it is associated with the appropriate last name (strLastName). Even tho in the array provided there are no duplicates of first or last name, I want my coding to be able to match the exact record.
After I find the appropriate record, I the need to prompt the user for the new phone number. I believe I can figure this part, but I'm open to ideas to accomplish this.
numContacts = the numbers of rows in the array
String [][] contactsArray = {
{"Emily","Watson","913-555-0001"},
{"Madison","Jacobs","913-555-0002"},
{"Joshua","Cooper","913-555-0003"},
{"Brandon","Alexander","913-555-0004"},
{"Emma","Miller","913-555-0005"},
{"Daniel","Ward","913-555-0006"},
{"Olivia","Davis","913-555-0007"},
{"Isaac","Torres","913-555-0008"},
{"Austin","Morris","913-555-0009"}
public static void updateContact(Scanner scanner, String[][] contactsArray, int numContacts) {
System.out.println("Updating contact");
System.out.print("Enter first and last name: ");
String strFirstName = scanner.next();
String strLastName = scanner.next();
for (int i=0; i < numContacts; i++){
System.out.println(i);
if (contactsArray[i][0].equals(strFirstName) ) {
for (int j = 0; j < 3;j++) {
System.out.println(j);
if (contactsArray[1][j].equals(strLastName) ) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}
}
Appreciate all the help resolving this in advance.
I feel you are close to the solution. The string comparison with the last name is unfortunately incorrect.
In fact, you are doing contactsArray[i][0] for firstname, which is correct. However, you are doing contactsArray[1][j] for the lastname, which is incorrect. Maybe contactsArray[i][1] is more correct.
Then you could ask yourself if you really need your second loop? You actually just want to find a record given the first and lastname. Therefore, you only need one loop to iterate over your "records".
Finally, you should break out of your loop if the record was actually found, and print "yes". If none was found after the loop, you should print "no".
I am currently seeking for a bit of help with the use of arrays. Quite a newbie on the Java language, so excuse the poor etiquette towards the programming format and I forwardly thank for any answers provided.
My current quarrel with the Array is how to fetch data from any array element. Currently I use the method System.out.println(Arrays.toString(listarray)) but the problem with this method is that it's not necessarily User friendly and it can't be formatted (to my little knowledge). So I'd like to ask help on how to fetch data from an element of an array and put it in a way so its readable by any given user.
Here is the code I'm utilizing:
import java.util.Arrays;
import java.util.Scanner;
public class principal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Array Example");
String[] listarray = new String[10];
int i = 0;
byte op;
do {
System.out.println("Select your option:");
System.out.println("1-Add");
System.out.println("2-Check");
System.out.println("3-Change");
op = input.nextByte();
switch (op) {
case 1:
input.nextLine();
System.out.println("First String:");
String a1 = input.nextLine();
System.out.println("Second String:");
String a2 = input.nextLine();
System.out.println("Third String:");
String a3 = input.nextLine();
System.out.println("(" + (i + 1) + "/10)");
listarray[i] = a1 + a2 + a3;
i++;
break;
case 2:
System.out.println(Arrays.toString(listarray));
break;
}
}while(op != 9);
}
}
While the code does work, I'd like to know how to format the data, and from a single element, not every element. Or even if I can. Thanks and I appreciate the time spent reading this question.
You have two questions:
How do you reference an array element?
How do you format output?
When you declare an array like
String[10] names;
You have an array that can hold 10 strings, numbered 0 to 9. To reference the fifth element (remembering that array indices start at 0), you would use
names[4]
You can do various things with a reference. If you put it on the right side of an equals sign, then you are assigning the value at that element to something else.
currentName = names[4];
If you put it on the left side, you are assigning something to that element.
names[4] = "Michael";
And if you put it in a println statement, it will output the value to wherever the println statement is putting things at that time, usually the console:
System.out.println(names[4]);
So much for references. And, incidentally, that's what it is called -- you are referencing the 5th element of the array, or you are referencing the indicated element of the array. You can also put the number in a variable:
var i = 4;
System.out.println[i];
Note that most of these uses of the reference assume there is something IN that element of the array. Until something is assigned there, the element is a null.
To format, I recommend looking (carefully) into the Format / Formatter classes and choosing some simple things to do what you want. As an example, you could have:
String formatString = "The name is currently %s.";
String outputString = String.format(formatString, names[i]);
and String's format method will substitute whatever is in names[i] for the %s in the format. There are also formats for ints, doubles, and dates.
For more info, see the Oracle Tutorial on arrays and on manipulating Strings.
Hope that helps
If you want to traverse the Array that is how you can do it:-
for(int i = 0; i < listArray.length; i++) {
System.out.println(listArray[i]);
}
or
for (String s : listArray) {
System.out.println(s);
}
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.
I am new in Java. I'm taking my first java class. I am trying to create a fixed size array ( for example: the array with a size is 10) and I use JOptionPane to let the user input data. My question is how can I let the user stop their input whenever they want. (For example: They just input 3 data instead of 10 and they want to finish it). This is my first post, I'm sorry if the format is not correct. Thank you guys.
import java.util.Arrays;
import javax.swing.JOptionPane;
public class TestArray {
/**
* #param args
*/
public static void main(String[] args) {
String[] lastName = new String[10];
for (int i = 0; i < lastName.length; i++)
{
lastName[i] = JOptionPane.showInputDialog(null,"Please Enter Tutor Last Names: " );
}
JOptionPane.showMessageDialog(null, lastName);
Just break out of the loop when you encounter a null value or empty String. Click cancel or enter an empty String to break from the loop.
for (int i = 0; i < lastName.length; i++) {
lastName[i] =
JOptionPane.showInputDialog(null, "Please Enter Tutor Last Names:");
if (lastName[i] == null || lastName[i].isEmpty()) {
break;
}
}
just put a check using certain variable and prompt user at end of every cycle to continue or not...if user wants to quit simply use break;
but it is good practice that to get the no of iteration prior to rotating loop...ask user that for how much no of time they want to execute the steps...store it in variable and use that as exit condition...