I have a 2D array with a list of names and numbers. Column 1 contains all the names of people. How do I edit my function to take user input and check to see if the input matches or if the input is partially found inside one of the names in one of the string in the array?
Example:
Daniel Zen, 12, 3
Niel Diam, 15, 5
Arthur Ziel, 16, 99
My function currently takes the first column, the names, but how do I look threw each if they are matching? and how do I determine their row value.
Wanted output: (User input "IeL")
Daniel Zen is row 0
Niel... is row 1
Arth... is row 2
What I have so far takes the input, converts it to lower-case.
public static void print_player_info(String[][] data, String player)
{
String name = player.toLowerCase();
for(int i = 0; i<data[0].length; i++)
{
String namecolumn = data[i][0];
String rownames = data[0][i];
if(name.indexOf(namecolumn)!= -1)//i dont think this is correct
{
// what would need to go here
}
}
}
Something similar would do for you.. I have not tested this, have a check and let us know.
public static void print_player_info(String[][] data, String player) {
String name = player.toLowerCase();
for (int i = 0; i < data.length; i++) {
String temp = Arrays.toString(data[i]);
if(temp.toLowerCase().contains(player)){
System.out.println(player + " - " + i);
}
}
}
public static void print_player_info(String[][] data, String player) {
int i = 0;
for (String[] dd : data) {
for (String d : dd) {
if (d.toLowerCase().contains(player.toLowerCase())) {
System.out.println(d + " is row " + i);
}
}i++; }}
Related
I want a way to count the letters in an string for example:
My string : "Hello my friends "
The characters in the string : {H,e,l,o, ,m,y,f,r,i,n,d,s}
These letters exist without repeating them (with a blank space)
So the result I want is: 13
The goal of all of this is, I want to convert a string to a table of character without repeating the letters
EX: MY String = "Hello"
The table I want to get {H,e,l,o}
My attempt
public static int numberRep(String txt) {
int count = 0;
boolean v = false;
for (int i = 0; i != txt.length(); i++) {
char c = txt.charAt(i);
for (int j = i + 1; j != txt.length(); j++) {
if (txt.charAt(j) == c) {
count++;
}
}
if(count == txt.length()-1){
v = true;
}
}
if(v){
return 1 ;
}
else{
return count;
}
}
Split the string into characters and store them into a Set. A Set keeps only unique elements. The elements of the Set will be the required characters and the size of the Set will give you the count of these characters.
Do it as follows:
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Testing {
public static void main(String[] args) {
String myString = "Hello my friends ";
Set<String> set = Arrays.stream(myString.split("")).collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println("Unique characters including space: " + set);
System.out.println("No. of unique characters including space: " + set.size());
}
}
Output:
Unique characters including space: [H, e, l, o, , m, y, f, r, i, n, d, s]
No. of unique characters including space: 13
What you could do is:
Create an empty list a
for character in list:
If the character is not your list a: add it to your list
This way you won't get any duplicate characters.
You can also use a set like recommended in Arvind's answer, but I think it is better for you to write a function as a task.
Set is the cleaner way to do it once you grasped the concepts of Java.
Well, this could be one of the approach to do so:
String str = "Hello my friends "
String noRepeatStr = "";
for(int i = 0; i < str.length; i++) {
if(noRepeatStr.indexOf(str[i]) == -1) // check if a char already exist, if not exist then return -1
noRepeatStr = noRepeatStr+str[i]; // add new char
}
System.out.println("Letters: " + noRepeatStr.toCharArray())
System.out.println("No of letters: " + noRepeatStr.length)
public static void main(String[] args) {
final String test = "Hello my friends";
final int size = IntStream.range(0, test.length())
.mapToObj(test::charAt)
.collect(Collectors.toSet()).size();
System.out.println(size);
}
What I've done here is iterated over all of the characters in the input string, mapped them to a char object and then collected them into a Set - instead of keeping the raw Set I've used .size() in order to get the output that you were expecting.
For another assignment i needed to program a "number seperator", that splits any given int value into all of its digits and returns it to the main class as a String.
I have the program up and running but there's a small problem with my output.
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
System.out.println("Input a Number: ");
int zahl = readInt();
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
System.out.print(ziffern.charAt(i) + ",");
}
}
}
The output of 1234 should be: 1,2,3,4
and the actual output is: 1,2,3,4,
At the risk of sounding extremely stupid, is there an easy fix to this?
How about printing first element without comma and rest in form ,nextElement like
one, two, three
^^^---------------- - before loop
^^^^^----------- - loop iteration
^^^^^^^---- - loop iteration
It can be achieved like:
if(ziffern.length()>0){
System.out.print(ziffern.charAt(0));
}
for(int i=1; i<ziffern.length(); i++){
System.out.print(", "+ziffern.charAt(i));
}
OR you can convert ziffern to String[] array first and use built-in solution which is: String.join(delimiter, data)
System.our.print(String.join(",", ziffern.split("")));
When it's the last iteration, just don't add it.
In the last iteration, it will make the comma empty so that you won't see it after the last value.
String comma=",";
for (int i = 0; i < ziffern.length(); i++) {
if (i == ziffern.length()-1) {
comma="";
}
System.out.print(ziffern.charAt(i) + comma);
}
with Java 8 and streams you can do it in a single command:
String join = Arrays.asList(ziffern.split(""))
.stream()
.collect(Collectors.joining(","));
System.out.println(join);
or with just plain java 8:
String join = String.join(",", ziffern.split(""));
System.out.println(join);
A simple one liner will do your job:
static String splitNumber(int zahl) {
return String.join(",", String.valueOf(zahl).split(""));
}
Quite often this occurs when you know you have at least two items to print. So here is how you could do it then.
String ziffern = splitNumber(zahl);
String output = ziffern[0];
for (int i = 1; i < ziffern.length(); i++) {
output = "," + ziffern[i];
}
System.out.println(output);
You can just output the string without the last character.
Your modified code should be:
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
int zahl = 1234;
String s="";
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
s+=ziffern.charAt(i) + ",";
}
System.out.println(s.substring(0,s.length()-1));
}
I am having trouble getting my 2D array to print side by side values taking the first array row value index 0 and matching it to the 2nd row array index 0 and continuing on in a vertical list. As it stands, my code compiles and just prints the entire arrays in a horizontal fashion on two lines. Basically, I would like the end result to be formatted like this:
Admin | Password1
Vale.Vicky | BruceIsTheBat!
Lane.Lois | FlyMeToTheMoon1234
Kent.Clark | PhoneBoothsSmell
Wayne.Bruce | ThisBat4You99
...and so on.
public class PasswordArrays { // start of class
public static void main(String[] args) { // Start of main
// TODO Auto-generated method stub
String [][] idArray = {
{"Admin", "Vale.Vicky", "Lane.Lois", "Kent.Clark", "Wayne.Bruce", "Parker.Peter", "Rogers.Steve", "Luther.Lex", "Osborn.Harry","Prince.Diana", "Linda Zoel"},
{"Password1", "BruceIsTheBat!", "FlyMeToTheMoon1234", "PhoneBoothsSmell","ThisBat4You99", "webSlinger","ShieldEnthusiast", "HairClub4Men", "GoblinGoober", "WonderWonderWho?", "WhoIsLindaZoel?"}
};
printArray(idArray);
} //End of main
public static void printArray(String a [][]) { //start of printArray method
for (int row=0; row < a.length ; row++) { // start of row for loop
for (int column = 0; column < a [row].length; column++) { //start of column for loop
System.out.print(a[row][column] + " ");
} // End of column for loop
System.out.println();
} // End of row for loop
} // End of printArray method
} //End of class
I know there's got to be an answer already for this somewhere but I have been unsuccessful in finding it. Any help is greatly appreciated.
A 2D array could be iterated in two ways:
Row wise
Column wise
As per your expected result, what you would want to do is iterate column wise rather than row wise. Here's a solution:
public static void printArray(String a [][]) {
for(int col=0; col < a[0].length; col++) {
for (int row = 0; row < a.length; row++) {
if (row!=a.length-1) {
System.out.print(a[row][col] + "|");
}
else {
System.out.print(a[row][col]);
}
}
System.out.println();
}
}
Helpful Link: Iterate through multi-dimensional array
you are traversing your 2D array incorrectly
you can try this for your array:
if(a.length > 0){
for(int i = 0; i < a[0].length; i++){
for(int j = 0;j < a.length; j++){
System.out.print(a[j][i]+" ");
}
System.out.println("");
}
}
Structure
Are you sure that you understood the structure of your 2d-array? You only have two rows but multiple columns (the array contains 2 arrays containing multiple elements each).
The structure is
idArray = { /* firstArray, secondArray */ }
idArray[0] = { /* Names */ }
idArray[1] = { /* Passwords */ }
Solution
You only need one iteration from int i = 0; to i < idArray[0].length. After that always pair the content of idArray[0][i] with idArray[1][i], that's all.
final int[][] idArray = ...
// Variant 1: Regular for-loop
for (int i = 0; i < idArray[0].length; i++) {
System.out.println(idArray[0][i] + " | " + idArray[1][i];
}
// Variant 2: Stream solution
IntStream.range(0, idArray[0].length) // IntStream
.map(i -> idArray[0][i] + " | " + idArray[1][i]) // Stream<String>
.forEach(System.out::println);
Note that idArray[0].length and idArray[1].length should of course be equal.
Notes
Probably you are better off using proper OOP, creating classes for each Account containing name and password fields and then using a List<Account> and toString for Account or something like that.
public class Account {
private final String mName;
private final String mPassword;
public Account(final String name, final String password) {
this.mName = name;
this.mPassword = password;
}
public String getName() {
return this.mName;
}
public String getPassword() {
return this.mPassword;
}
#Override
public String toString() {
return this.getName() + " | " + this.getPassword();
}
}
And then use it like
final List<Account> accounts = new ArrayList<>();
accounts.add(new Account("Admin", "Password1"));
...
// Variant 1: Enhanced for-loop 'foreach'
for (final Account account : accounts) {
System.out.println(account);
}
// Variant 2: The same using streams
accounts.forEach(System.out::println);
// Variant 3: Using Lists 'toString'
System.out.println(accounts);
I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342
Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.
You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}
If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}
replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.
Clearly, that is almost impossible to understand.
So, here is an example:
If I have an ArrayList = ["abc", "def"]
Then the result I desire is:
ad ae af
bd be bf
cd ce cf
And the same can be assumed if I have an ArrayList = ["ab", "cd", "efg"]:
ace acf acg
ade adf adg
bce bcf bcg
bde bdf bdg
Where all the options are shown. The first index String corresponds to the first 'potential' letter of the result. The second corresponds with the second, and so forth. I have been looking into different forms of recursion, but I seem to have run into a hole. Here is what I have so far:
public static void main(String[] args) {
ArrayList<String> param = new ArrayList<String>();
param.add("jkl");
param.add("mno");
param.add("pqrs");
System.out.println(giveFrag(param, 0));
}
static String giveLetter(String s, int indexForString) {
// return the letter given
return s.substring(indexForString, indexForString+1);
}
static String giveFrag(ArrayList<String> strs, int start) {
String output = "";
if (start == strs.size()-1) {
output = giveLetter(strs.get(start),0);
} else {
for (int i = 0; i < strs.get(start).length(); i++) {
String q = strs.get(start).substring(i,i+1);
output += q;
for (int k = strs.size()-1; k < strs.size(); k++) {
output += giveFrag(strs, start+1);
}
output += " ";
}
output += "\n";
}
return output;
}
NOTICE THAT FOR SIMPLICITY'S SAKE, I IGNORE THE LAST ELEMENT OF THE ARRAYLIST. THIS CAN BE SEEN IN THE IF STATEMENT OF giveFrag().
Currently, my result is as follows:
jmp np op
kmp np op
lmp np op
Now, to the actual question! First of all, if anyone spots any glaring errors that would produce this result instead of:
jmp jnp jop
kmp knp kop
lmp lnp lop
Please let me know. If there aren't any obvious ones, and an entire restructure is needed, could you please be very specific for what I should be doing instead?
In addition, if anyone has any additional time on their hands, could they find a way to include the last array element when iterating?
Thanks so much for your help, and sorry for the incredibly vague title.
The current output doesn't match the description of the problem.
The first line of the output should be:
jmp jmq jmr jms
The implementation is not really close to what you need.
Consider this instead:
private void accumulateFrags(List<String> strings, int start, String prefix, List<String> frags) {
if (start == strings.size()) {
frags.add(prefix);
return;
}
String current = strings.get(start);
for (char c : current.toCharArray()) {
accumulateFrags(strings, start + 1, prefix + c, frags);
}
}
This function will accumulate all combinations in a list.
Call it like this:
List<String> frags = new ArrayList<>();
accumulateFrags(Arrays.asList("jkl", "mno", "pqrs"), 0, "", frags);
System.out.println(frags);
This doesn't produce the line by line output you desire.
But that should be fairly straightforward to do,
so I leave that as an exercise for you.
recursive
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
String arr[] = {"jkl", "mno", "pqrs"};
List<String> res = new ArrayList<String>();
constructStr(res, "", 0, arr);
String s = "";
for (int i=0; i<res.size(); i++) {
int mod = arr[arr.length-1].length();
if (i % mod == 0) {
System.out.println(s);
s = res.get(i) + " ";
}
else {
s += res.get(i) + " ";
}
}
System.out.println(s);
}
private static void constructStr(List<String> result, String curStr, int i, String arr[]) {
if (i + 1 < arr.length) {
for (int k=0; k<arr[i].length(); k++) {
constructStr(result, curStr + arr[i].charAt(k), i + 1, arr);
}
}
else {
for (int k=0; k<arr[i].length(); k++) {
result.add(curStr + arr[i].charAt(k));
}
}
}