Splitting an array to be input into a Map - java

I am trying to split an array of names such as "Joe Bloggs" Joe and Bloggs are separate and then can be used in a map where the first name is the key. Here is what I have so far.
public static void main(String[] args) {
Map<String, String> snames = new HashMap<String, String>();
int index = -1;
String[] names = new String[8];
Scanner s = new Scanner( System.in );
for( int i = 0; i <= names.length; i++ ){
System.out.println( "Enter student name:" );
names[ i ] = s.next();
}
System.out.println("Please type in the student index you want to view between 0 and 7");
index = s.nextInt();
while (index >7 || index <0){
System.out.println("Please type in a valid index value");
index = s.nextInt();
}
System.out.println("The student with the index of " + index + " is " + names[index]);
}
}

Not too sure what you are asking for
for (String x : names){
String[] temp = x.split(" "); // split "Joe Bloggs" to ["Joe", "Bloggs"]
if (temp.length == 2){
snames.put(temp[0], temp[1]); // Mapping "Joe" to "Bloggs"
}
}
is that what you want?

Related

I want to find the index of the string in an array

I have to search a string in an array from the user input, but I have an error in my logic. Even when the user input is in the array I still get "data not found"
I also have to display the index where the string is located in the array if it's found but got an error there too.
Below is the code I've tried.
This was the original question
create a program that ask user to insert 5 names.
store names in array
ask user to insert the name they want to find from the list created earlier
if name found, display "data found at [index]"
if not, display "data not found". Hint; use Java method equals to compare two strings.
package stringsearch;
import java.util.Scanner;
public class StringSearch
{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
String [] names = new String[5];
for (i = 0; i < names.length; i++)
{
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
if (names.equals(inName)){
System.out.println("Data found at ["+i+"]");
}
else
{
System.out.println("Data not found!");
}
}
}
You need to compare the value of inName with each of the values stored in the array, not with the array itself. You access each of the values stored in the array using the index starting with 0.
for (i = 0; i < names.length; i++) {
if (inName.equals(names[i])) {
System.out.println("Data found at [" + i + "]");
break;
}
}
// If the value stored in `inName` is found, the value of `i` will not reach up
// to the value equal to `names.length` because of the `break` statement. If the
// value of `i` has reached there, it means that the value stored in `inName`
// has not been found.
if (i == names.length) {
System.out.println("Data not found!");
}
Complete program:
import java.util.Scanner;
public class StringSearch {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
String[] names = new String[5];
for (i = 0; i < names.length; i++) {
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
for (i = 0; i < names.length; i++) {
if (inName.equals(names[i])) {
System.out.println("Data found at [" + i + "]");
break;
}
}
// If the value stored in `inName` is found, the value of `i` will not reach up
// to the value equal to `names.length` because of the `break` statement. If the
// value of `i` has reached there, it means that the value stored in `inName`
// has not been found.
if (i == names.length) {
System.out.println("Data not found!");
}
}
}
A sample run:
Enter name 1 > John
Enter name 2 > Harry
Enter name 3 > Sam
Enter name 4 > Cristina
Enter name 5 > Manny
Input Name to compare > Sam
Data found at [2]
You are comparing the whole array to a single string, that will always return false.
It's the same as:
String[] names = {"a", "b", "c"};
names.equals("d");
Iterate the array to see if there string is there
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
return i;
}
i++
}
if (i == names.length ) {
// not found
}
Running example:
public class A {
public static void main(String...args){
String[] names = {"a", "b", "c"};
String inName = "d";
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
System.out.println(i);
break;
//return i;
}
i++;
}
if (i == names.length ) {
System.out.println(-1);
// not found
}
}
}

removing null values for an array

The code takes input for a user for a name and a second input for a birthday. It can store up to 10 entries both name + birthday and can be terminated early by entering "ZZZ". I figured out most of the code but the part I can't figure out is if the entries are terminated before 10 then there is a text that says something along the lines of [adam, john, dave, null, null, null,....]
import java.util.*;
public class BirthdayReminderRedo {
public static void main(String[] args) {
String[] name = new String[10];
String[] birthday = new String[10];
String[] selectName = new String[100];
String inputName;
Scanner userInput = new Scanner(System.in);
int count;
for(count=0; count < 10; count++){
System.out.println("Please enter a name or type ZZZ to end name inputs>>");
inputName = userInput.nextLine();
if(inputName.equals("ZZZ")){
while(name.remove(null)){}
System.out.println(count);
System.out.println(name);
//System.out.println(Arrays.toString(name));
break;
}
else{
name[count] = inputName;
}
if(count == 10){
for(int secondCount = 0; secondCount > 0; secondCount++);
break;
}
else{
System.out.println("Please enter birthday in the format DD/MM/YYYY>>");
birthday[count] = userInput.nextLine();
}
}
String dataCheck = null;
do{
for(int secondCount = 0; secondCount < 10; secondCount++){
System.out.println("Please enter a name to get the birthday or enter ZZZ to end program>>");
userInput = new Scanner(System.in);
dataCheck = userInput.nextLine();
selectName[secondCount] = dataCheck;
boolean valid = false;
if(selectName[secondCount].equals("ZZZ")){
System.out.println("Thank you for using this program");
break;
}
for(int thirdCount = 0; thirdCount < 10; thirdCount++){
if(selectName[secondCount].equals(name[thirdCount])){
System.out.println(birthday[thirdCount]);
valid = true;
}
else if (thirdCount == 9 && !valid){
System.out.println("Not a valid name");
}
}
}
} while(!"ZZZ".equals(dataCheck));
}
}
Any tips on how I can remove the nulls from this println?
Instead of using arrays. Why not utilize Lists and instantiate an ArrayList so that you don't have to worry about extra/undefined elements in your collection?
List<String> name = new ArrayList<String>();
List<String> birthday = new ArrayList<String>();
String[] selectName = new String[100];
String inputName;
Scanner userInput = new Scanner(System.in);
int count;
for(count=0; count < 10; count++){
System.out.println("Please enter a name or type ZZZ to end name inputs>>");
inputName = userInput.nextLine();
if(inputName.equals("ZZZ")){
break;
}
else{
name.add(inputName);
}
if(count == 10){ //Sunny - Count will never be 10
for(int secondCount = 0; secondCount > 0; secondCount++);
break;
}
else{
System.out.println("Please enter birthday in the format DD/MM/YYYY>>");
birthday.add(userInput.nextLine());
}
}
If you insist on using arrays than you either:
Copy the values to a new array initialized to the number of inputs, if you want to use Arrays.toString.
If you don’t care for using that method, you can also print them as follows:
for(String n: name)
{
if(n!=null)
System.out.print(n + " ");
}
If using arrays is not important, do as the other answer suggests; use ArrayList.

Filling and sorting parallel arrays from single user input

I have to accept a single user input of a string and an int ten times, separate them at the space into two parallel arrays. I then have to sort them, find average, etc. Everything I have found on parallel arrays has two different inputs for the string and int. How can I separate the single input into the two arrays?
public static void main(String args[]){
//double[] gradeArray = new double[10];
//String[] nameArray = new String[10];
String name = " "; //name substring
String num = " "; //int substring
String s = " "; //input String
int grade = Integer.parseInt(num); //parsing the numerical string to an int
int x = s.indexOf(' '); //index of " " space
name = s.substring(0, x);
num =s.substring(x + 1);
Scanner input = new Scanner(System.in);
int[] gradeArray = new int[10];
String[] nameArray = new String[10];
//looping to gather 10 user inputs
for(int k = 0; k < 10; k++){
System.out.println("Input Student name and grade: ");
s = input.nextLine();
//not sure how to sepearate String s into String name and String num
}
System.out.println("Highest Grade: " + Grades.highestGrade(gradeArray));
System.out.println("Lowest Grade: " + Grades.lowestGrade(gradeArray));
System.out.println("Class Average: " + Grades.classAverage(gradeArray));
for(int i = 0; i < nameArray.length; i++){
System.out.print(nameArray[i] + ", ");
System.out.print(gradeArray[i]);
System.out.println();
// System.out.print(sort());
}
How can I separate the single input into the two arrays?
First, we will use the already declared array of double to store the grades.
double[] gradeArray = new double[10];
Second, we will use the already declared array of String to store the names.
String[] nameArray = new String[10];
Now, going on to the for loop, we can use the String#split() method to separate the name and the grade on the delimiter " " considering that there will be whitespace between the name and grade as you've mentioned.
for(int k = 0; k < 10; k++){
System.out.println("Input Student name and grade: ");
s = input.nextLine();
String[] tempArray = s.split(" ");
nameArray[k] = tempArray[0]; // store name to nameArray
gradeArray[k] = Double.parseDouble(tempArray[1]); // store grade to gradeArray
}

Count word length with occurrence

I am doing a program to count the length of each word followed by the number of occurrences of that length.
For example:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
So far I tried this,
import java.util.Scanner;
class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
String[] arr = s.split(" ");
String str = "";
int [] len = new int[arr.length];
int [] count = new int[arr.length];
int c = 0;
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
for(int j=0;j<arr.length;j++){
if(str.length() == arr[j].length()){
count[i] = ++c;
}
}
c = 0;
}
for(int i=0;i<len.length;i++){
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
}
}
There is a problem in my logic and that's why it's output is like this:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
No. of words of length 4 are 2.
Any suggestion how to fix that or any other simpler way to do it(without using collections, maps).
You can replace array with a Map<Integer,Integer>, It will easiar.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String :");
String s = sc.nextLine();
String[] arr = s.split(" ");// get the words
Map<Integer, Integer> lengthVsCount=new HashMap<>(); // length vs count
for(String i:arr){ // iterate array
Integer val=lengthVsCount.get(i.length()); // searching count
if(val!=null){ // if count is there
lengthVsCount.put(i.length(),val+1);// increment count by one
}else{ // count not there
lengthVsCount.put(i.length(),1); // add count as one
}
}
for (Map.Entry<Integer,Integer> entry:lengthVsCount.entrySet()) {
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue() + ".");
}
You should use a map:
public static void main(String[] args) {
final String input = "I love my work";
final String[] words = input.split(" ");
final Map<Integer, Integer> occurencesMap = new HashMap<Integer, Integer>();
for (final String word : words) {
final int lenght = word.length();
if (occurencesMap.get(lenght) == null) {
occurencesMap.put(lenght, 1);
} else {
occurencesMap.put(lenght, occurencesMap.get(lenght) + 1);
}
}
System.out.println("The word count is -");
final Iterator<Map.Entry<Integer, Integer>> entries = occurencesMap.entrySet().iterator();
while (entries.hasNext()) {
final Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue());
}
}
class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (String str : s.split(" ")) {
int key = str.length();
if (map.containsKey(key)) {
map.put(key, map.get(key)+1);
}
else {
map.put(key, 1);
}
}
Iterator<Integer> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
int key = iterator.next();
System.out.println("No. of words of length " + key + " are " + map.get(key) + ".");
}
}
}
Here,
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
You should check if len[i] is not a value already in the array. So use
int k;
for(k=0 ; k<i ; k++ )
if( len[i]==len[k] ) //if a match was found
break; //break out of the loop
if(k!=i) //will be true if the break has been executed
{
len[i]=0; //set to 0
continue; //go back to the loop
}
Just after that and use
for(int i=0;i<len.length;i++){
if(len[i]!=0)
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
When printing the results.

Using a scanner to accept String input and storing in a String Array

Can someone help me please. I have done numerous searches but can't find a solution anywhere.
I'm a beginner to Java and currently practicing some code while on a break from college.
I am trying to make a Phonebook program. At the moment I am trying to add a new contact, below is the code i have but i am not sure how to store the information in an array can someone give me some pointers please.
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
//inputs
String name = "";
String phone = "";
String add1 = "";
String add2 = "";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (name.equals(""))
{
System.out.println("Enter contacts name: ");
name = input.nextLine();
name += contactName[];
}
while (add1.equals(""))
{
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[];
}
while (add2.equals(""))
{
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[];
}
while (phone.equals(""))
{
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[];
}
}
}
A cleaner approach would be to create a Person object that contains contactName, contactPhone, etc. Then, use an ArrayList rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index.
The second problem you have is that you don't have the variable index.
What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)
//go through this code I have made several changes in it//
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (i<11)
{
i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}
while (i<12)
{
i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}
}
}
Would this work better?
import java.util.Scanner;
public class Work {
public static void main(String[] args){
System.out.println("Please enter the following information");
String name = "0";
String num = "0";
String address = "0";
int i = 0;
Scanner input = new Scanner(System.in);
//The Arrays
String [] contactName = new String [7];
String [] contactNum = new String [7];
String [] contactAdd = new String [7];
//I set these as the Array titles
contactName[0] = "Name";
contactNum[0] = "Phone Number";
contactAdd[0] = "Address";
//This asks for the information and builds an Array for each
//i -= i resets i back to 0 so the arrays are not 7,14,21+
while (i < 6){
i++;
System.out.println("Enter contact name." + i);
name = input.nextLine();
contactName[i] = name;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact number." + i);
num = input.nextLine();
contactNum[i] = num;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact address." + i);
num = input.nextLine();
contactAdd[i] = num;
}
//Now lets print out the Arrays
i -= i;
while(i < 6){
i++;
System.out.print( i + " " + contactName[i] + " / " );
}
//These are set to print the array on one line so println will skip a line
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactNum[i] + " / " );
}
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactAdd[i] + " / " );
}
System.out.println();
System.out.println("End of program");
}
}
Please correct me if I'm wrong.`
public static void main(String[] args) {
Scanner na = new Scanner(System.in);
System.out.println("Please enter the number of contacts: ");
int num = na.nextInt();
String[] contactName = new String[num];
String[] contactPhone = new String[num];
String[] contactAdd1 = new String[num];
String[] contactAdd2 = new String[num];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num; i++) {
System.out.println("Enter contacts name: " + (i+1));
contactName[i] = input.nextLine();
System.out.println("Enter contacts addressline1: " + (i+1));
contactAdd1[i] = input.nextLine();
System.out.println("Enter contacts addressline2: " + (i+1));
contactAdd2[i] = input.nextLine();
System.out.println("Enter contact phone number: " + (i+1));
contactPhone[i] = input.nextLine();
}
for (int i = 0; i < num; i++) {
System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
}
}
`
There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.

Categories

Resources