Java: How to fill out two arrays, alternating between the two - java

I have a program that has two String arrays defined and initialized. I now want to accept inputs from the user to fill out the indexes of each array. I want the user to input index[i] for array 1 and then index[i] for array 2 and so on until both arrays are filled.
I attempted to use a nested loop to do this, but I was getting an out of bounds error.
Unfortunately, Google was not helpful as I kept finding the .fill() method, which I cannot currently use in my course.
The code below contains elements for the rest of the program which I haven't written. The below code is meant to complete the first part of the program and that is to get the list of words into the first two arrays and then output them to make sure they were filled correctly.
EDIT: Even though I got my answer, I tried updating the question for clarity. It looks like I was vastly overthinking the problem. It was my first time working with more than one array.
import java.util.Scanner;
public class LabProgram {
public static int findWordInWordList(String[] wordList, String wordToFind, int numInList) {
return -1; //Will replace words in a sentence, to be used coded and used later.
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ogWords; //words to replace.
String[] newWords; //words to replace with.
String[] sentence; //the sentence that will be searched and have words replaced.
int pairSize; //size of the first two arrays.
pairSize = sc.nextInt();
ogWords = new String[pairSize];
newWords = new String[pairSize];
for (int i = 0; i < ogWords.length; i++) {
ogWords[i] = sc.next();
for (int j = 0; j < newWords.length; j++) {
newWords[j] = sc.next();
}
}
for (int i = 0; i < pairSize - 1; i++) { //Testing arrays
System.out.println(ogWords[i] + " " + newWords[i]);
}
}
}
The final for loop is just to test that the arrays were filled correctly, which isn't working right now :p.

Unless I've misunderstood your question, I think you're after:
for (int i = 0; i < pairSize; i++) {
ogWords[i] = sc.next();
newWords[i] = sc.next();
}

Related

Java: how to stop blank arrays position from showing null in the terminal?

I have the following code that gets an element from the terminal with the Scanner class and adds it to a shopping cart array. It works fine, except that when I try to print the cart it'll show the unfilled positions of the array as "null". I digged over some topics here and someone sugested to create the first array with blank spaces for each of the 5 position (like String[] test = new String[]{"","","","",""};, but that didn't work. What should I do to "fix" this?
import java.util.Arrays;
import java.util.Scanner;
public class ex03 {
public static void main(String[] args) {
Scanner frutas = new Scanner(System.in);
String[] nomesFrutas = new String[5];
System.out.println("Insira a sua lista de compras.");
for (int i = 0; i <= nomesFrutas.length; i++) {
nomesFrutas[i] = frutas.next();
System.out.println("As frutas no seu carrinho são: \r\n " + Arrays.toString(nomesFrutas));
}
}
}
it'll show the unfilled positions of the array as null
There's a couple ways to avoid uninitialized elements to show up.
A quick and lazy way would be to use the built-in functionality of the Arrays utility class. You can print a copy of the part that was populated and print it.
By the way, there's a bug in your code: condition i <= nomesFrutas.length would produce an ArrayIndexOutOfBounds during the very last iteration because nomesFrutas[i] would refer to an illegal index.
That's how you can make use of the utility method Arrays.copyOf():
for (int i = 0; i < nomesFrutas.length; i++) {
nomesFrutas[i] = frutas.next();
System.out.println("As frutas no seu carrinho são: \r\n "
+ Arrays.toString(Arrays.copyOf(nomesFrutas, i + 1)));
}
There are several drawbacks of this solution:
a new array needs to be allocated in memory at each iteration step just in order to print non-null elements (it's a good habit to be mindful while your action require creating new objects that are immediately thrown away, especially when it can be avoided);
as I've said it's a "lazy" way, because it doesn't require implementing things yourself, try not to overuse such ready-to-go options when you're learning.
Another approach would be to create your own method responsible for displaying a range of array elements:
for (int i = 0; i < nomesFrutas.length; i++) {
nomesFrutas[i] = frutas.next();
System.out.println("As frutas no seu carrinho são: \r\n ");
display(nomesFrutas, i + 1);
}
public static void display(String[] arr, int len) {
if (len < 1) return;
System.out.print('[');
for (int i = 0; i < len; i++) {
System.out.print(arr[i]);
if (i < len - 1) System.out.print(", ");
else System.out.print(']');
}
}
Fill free to play around with this solution and adjust it in whatever way you see fit.

I need to take a string and output the word that occurs most within the string

I believe that I have the correct code in order to keep going to the next word in the string, however, I am really struggling with how I am supposed to add the most used word into maxW. I also am confused about the maxCnt, will I need to create a whole separate loop just to return the maxCnt?
My professor mentioned using an if statement to compare maxW and maxCnt, but I honestly do not know where to start with implementing that.
String getMode() {
String tmp = "";
for(int i=0; i<s.length(); i++){
if(s.charAt(i)>64 && s.charAt(i)<=122 || s.charAt(i)==32){
tmp = tmp+s.charAt(i);
s = tmp;
}
}
String maxW = "";
int maxCnt = 0;
for(int i=0; i<s.length(); i++) {
int p =s.indexOf(" ",i);
int cnt = 1;
String w = s.substring(i,p);
i = p;
for (int j=p+1; j<s.length(); j++) {
int p1 = s.indexOf(" ",j);
String w1 = s.substring(j,p1);
if(w.equalsIgnoreCase(w1))
cnt++;
j = p1;
maxW = w+s.substring(j,p1);
}
}
return maxW;
}
Everything that I have tried results in a String out of range error code at:
(String.java:1967)
(Hw9.java:36)
(Hw9.java:64)
This is an example of what the result should be: If s = "You are braver than you believe, and stronger than you seem, and smarter than you think.", this method will return "You".
Thanks in advance for any help!
If you can't use maps, then perhaps you could use two parallel lists. One for words and one for count. Search each word in the String list. If you find it, increment its corresponding count list entry by 1. If you don't find it, add it to the list and set the appropriate count entry to 1.
Once you get done building your lists, then find the index of the max count and use that to index into the word list to get the word that occurred most often.
Keep in mind that for some data sets (sentences) there could be a multi-way tie.
I ran your code with your example sentence.
Using the string you supplied, s has a single character, Y. The reason for that is the loop only executes once.
As soon as you set s = tmp inside the loop, the length of s is now 1, so the loop immediately exits after one iteration.
I'd recommend doing this piece by piece. Break the problem down into chunks, and tackle those one-by-one. Use a debugger or, if you're not comfortable with that yet, make liberal use of System.out.println().
Here's some ways of counting words mentioned in comments in code form...since it's helpful to see it in code form sometimes:
//The map easy way:
Map<String, Integer> counts = new HashMap<String, Integer>();
if (!counts.containsKey("word")) {
counts.put("word", 0);
}
counts.put("word", counts.get("word") + 1);
//The double array way (dirty):
int wordsAddedCount = 0;
boolean wordFound = false;
String[] wordsList = new String[500];//assumes max of 500 different words
Integer[] counts2 = new Integer[500];
for (int i = 0; i < wordsAddedCount; i++) {
if ("word".equals(wordsList[i])) {
wordFound = true;
counts2[i]++;
break;
}
}
if (!wordFound) {
wordsList[wordsAddedCount] = "word";
counts2[wordsAddedCount++] = 1;
}

Array splitting seems not to be working , and also Maps and Lists refused to be populated

Can someone please show me what is wrong with this block of code.
What I am trying to do is to create a phone-book that will receive the first input as the amount of entries the user want to enter, and the subsequent inputs will be the input of the phonebook details in
the form of a long string.
It will include the name of the person and the phone number, in a single line and then after the input, I will split the inputted values into two and store each as a key and value in a map.
But my code is not working.
What am I doing with the Lists is this:
The input from stdin will be a single string of the name and the phone number in a single line of input. So what I am trying to do is to split the long string of name and number into two(name and number), and store them both in a list, then when I want to populate the Map I will then call the index of the list where the number is situated and use it as the value, and also call the index of the list where the name is situated and use it as key in the Map.
I have tried using an array but there are problems when splitting the string. With this list now the splitted strings seems not to be saving in the list, probably because of iterations of the loops.
An insight will be helpful
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Testube {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int phoneBookSize = sc.nextInt();
String[] names = new String[phoneBookSize];
String[] numbers = new String[phoneBookSize];
Map<String, String> phoneBook = new LinkedHashMap<>();
String[] inputNameAndNumber = new String[2];
String name;
String number;
List<String> keepStrings = new ArrayList<String>();
for (int i = 0; i < phoneBookSize; i++) {
for (int j = 0; j < 2; j++) {
inputNameAndNumber = sc.next().split(" ");
String holder = inputNameAndNumber[j];
keepStrings.add(holder);
// name = inputNameAndNumber[0];
// number = inputNameAndNumber [1];
}
phoneBook.put(keepStrings.get(0), keepStrings.get(1));
}
System.out.println(phoneBook.entrySet());
}
The list keepStrings needs to be re-instantiated or cleared otherwise the objects would keep piling up in other indexes. The list will maintain its state (+ more objects further down the index) i.e. the objects on the index 0 and 1 will be the same until cleared or re-instantiated.
for (int i = 0; i < phoneBookSize; i++) {
for (int j = 0; j < 2; j++) {
inputNameAndNumber = sc.next().split(" ");
String holder = inputNameAndNumber[j];
keepStrings.add(holder);
// name = inputNameAndNumber[0];
// number = inputNameAndNumber [1];
}
phoneBook.put(keepStrings.get(0), keepStrings.get(1));
keepStrings.clear();
}
OR
for (int i = 0; i < phoneBookSize; i++) {
for (int j = 0; j < 2; j++) {
keepStrings = new ArrayList<String>();
inputNameAndNumber = sc.next().split(" ");
String holder = inputNameAndNumber[j];
keepStrings.add(holder);
// name = inputNameAndNumber[0];
// number = inputNameAndNumber [1];
}
phoneBook.put(keepStrings.get(0), keepStrings.get(1));
}
Though the first solution serves here better.
You should remove your jloop. It let you input your name and number twice to work correctly because of sc.next() is inside this loop.
The 2nd point is that your phonebook will only contains one entry because you always putting the same values. This is because your list is never cleared.
You may change your loop to:
// consume 'new line' after sc.nextInt()
sc.nextLine();
for (int i = 0; i < phoneBookSize; i++) {
// note: change `next` to `nextLine`
inputNameAndNumber = sc.nextLine().split(" ");
name = inputNameAndNumber[0];
number = inputNameAndNumber[1];
phoneBook.put(name, number);
}
So in each iteration to populate your phonebook you're changing name and number by the next input.
Your input holds both name and number in one line like
Alex 123
Ben 456
Ed 789

Cycle while with scanner hasNext()

I have a problem when I try to run my work.
I have to put in some numbers by console and It should arrange in ascending order them and save to an array.
I thought that method hasNext worked well with String.nextLine(), but it seems to still in loop.
thanks for help
import java.util.Scanner;
public class OrdinamentoMaggiore{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Digita dei numeri e te li mettero' in ordine crescente: ");
String Numeri = sc.nextLine();
int dimArray = 0;
while (sc.hasNext(Numeri)){
dimArray++;
System.out.println("Dimensione array: " + dimArray);
}
int min = 0, max = 0, temp;
int[] mioArray = new int[dimArray];
for (int i = 0; i <= mioArray.length; i++){
mioArray[i] = Integer.parseInt(sc.next(Numeri));
}
for (int j = 0; j <= mioArray.length; j++){
for (int h = 1; h <= mioArray.length; h++){
if (mioArray[j] < mioArray[h]){
continue;
}
else {
temp = mioArray[j];
mioArray[j] = mioArray[h];
mioArray[h] = temp;
}
}
}
System.out.println("Min: " + mioArray[0]);
System.out.println("Max: " + mioArray[dimArray]);
sc.close();
}
}
The problem is that you are reading the first line of input into the variable Numeri. Then, you are calling hasNext on Numeri which isn't working the way you think it is. Scanner.hasNext is defined here as:
Returns true if the next token matches the pattern constructed from
the specified string.
So it is using the string in Numeri as the pattern it needs to match. Definitely not what you want.
I would recommend a list and doing something like this:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt()) {
numberList.add(sc.nextInt());
}
Collections.sort(numberList);
A list is nice because you don't have to explicitly tell it the size. That avoids your first loop. Now, the loop goes continues reading from System.in until it encounters something that isn't an integer and adds them to the list.
Finally, it uses Collections.sort to sort the list. How beautiful is that? Your whole program can be reproduced in just a few lines. Definitely try and learn the libraries and functions that are available to you. It can save you a lot of time and effort. Let me know if you have questions.

Sorting Strings as inserted into array in Java

I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;

Categories