How to manipulate arrays? - java

I have an array with 2 spots in it(it must have 2 spots in the beginning ). i need to get user input and double the array when user enters more than the array can hold. Also Upon entering -1 the user input should stop. The array must also not accept duplicates.
i don't know how to have the not accept duplicates and end the program when the user entters -1 while still doubling the array every time it fills up.
Here's what i have so far but its flawed and wont run properly.
public class GroupArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] numbers = new int[2];
int x;
int n=0;
for( int i = 0; i<numbers.length; i++){
System.out.println("Please enter number");
int number = input.nextInt();
while ( input.hasNextInt() )
{
x = input.nextInt();
if ( n == numbers.length )
{
int[] h;
h = new int[ 2*numbers.length ];
for ( int i1 = 0; i1 < numbers.length; i1++ )
h[i1] = numbers[i1];
numbers = h;
}
if(x == -1){
break;
}
numbers[n] = x;
n++;
}
for ( int i1 = 0; i1 < numbers.length; i1++ )
System.out.println( numbers[i1] );
}
}
I can figure out how to do all the things individually but it becomes difficult when i have to do them all to 1 array and do user input.
PS. I feel like i have made this more complicated than it needs to be.

I'm only give you hints on how to solve the problem, and on how to write code that is easier to understand and maintain, even (and most importantly) by yourself.
Split the code in methods, doing simple tasks. Don't try to write everything as a giant piece of code.
The pseudo code of the algorithm would be
loop
ask and get input number
if (number is -1)
break out of the loop
else if array already contains number
print error message
else
if no space left in array
array = copy of array with doubled length
store number in next available index in array and increment the next available spot index
end of loop
print the array
Now, you can see that there are things that can be implemented easily as separate methods:
ask and get input number
check if array already contains number
copy of array with doubled length
print the array
Start by writing the signature of these simple methods, without implementing them. Then write the algorithm by calling these methods.
Then implement the simple methods one by one and test them one by one. You can do that, for now, by just writing a main method that calls them with hard-coded arguments, and see if they do what you expect them to do.
Once every of them is written and tested, test the main algorithm. If you made a mistake, iterate, by re-testing the methods you had to modify.
While coding all the methods, choose names that indicate clearly what the variables represent, and what the methods do, even if they're long. For example, nextAvailableIndex is much much clearer than x. Using good names helps everyone, including you, to understand the code and find bugs.
Also, indent the code strictly, as you type. The code you posted is not indented correctly, which makes it difficult to understand its structure. Stick to 4 spaces as indentation level, and always use curly braces around the body of your if, for, etc. ALways place them after the if/for, and not on the next line. Be consistent.

public class GroupArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] numbers = new int[2];
int x;
int n=0;
for( int i = 0; i<numbers.length; i++){
System.out.println("Please enter number");
int number = input.nextInt();
while ( input.hasNextInt() )
{
x = input.nextInt();
if ( n == numbers.length )
{
int[] h;
h = Arrays.copyOf[numbers,2*numbers.length ]; //change
}
if(x == -1){
break;
}
numbers[n] = x;
n++;
}
for ( int i1 = 0; i1 < numbers.length; i1++ )
System.out.println( numbers[i1] );
}
}
Use Arrays.copyOf(array_name,array_length); to create new arrays with varying lengths.

Related

Java: Simple array splitting program

I am trying to make a simple Java program where you input 15 numbers (INTS, positive and negative) first, let's say these will get loaded into arrayOne. After that all numbers that are below '-5' need to be loaded into a second array (arrayTwo). I want to print all numbers of arrayTwo, while still retaining all arrayOne numbers.
I know my code doesn't make any sense at all, as I am still a beginner (about a month on and off). This is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int[] arrayOne = new int[15];
int count = 0;
System.out.println("Input 15 ints: ");
for (int i = 0; i <= arrayOne.length-1; i++){
arrayOne[i] = scanner.nextInt();
if (arrayOne[i] < -5){
count++;
}
}
int[] arrayTwo = new int[count];
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayOne[i] = arrayTwo[i];
}
}
}
}
It's so confusing for me. I don't know what to do to be honest. Do I need to use some kind of nested loop?
Thank you so much in advance, any help will be greatly appreciated.
int[] arrayTwo = new int[count];
int index = 0;
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo[index++] = arrayOne[i];
}
}
index will be used to write into the second array.
index++ is postfix increment operator. You can read about that here - Java: Prefix/postfix of increment/decrement operators?
You were doing the assignment the wrong way. It must be arrayTwo[..] = arrayOne[..] to assign a value from arrayOne into arrayTwo.
I know my code doesn't make any sense at all, as I am still a beginner
You don't need to apologize for being a beginner. We were all there once. Your code has the general right idea. You are just missing a few key concepts.
Look at this line:
arrayOne[i] = arrayTwo[i];
You are assigning values from arrayTwo into arrayOne. However, from what you say, you want it the other way around:
arrayTwo[i] = arrayOne[i];
But now you are assigning to the same index in arrayTwo as you are reading from in arrayOne. This will leave 0 values where the original values in arrayOne were larger than -5. I doubt this is what you want.
Instead, you should use two separate indexes for each array. Maybe i1 and i2. These will increment independently. That is i1 will always increment in the for loop because you are stepping over the elements of arrayOne. But i2 should only increment when you write a value into arrayTwo.
In arrayOne you have 15 integers.But in arrayTwo you have integers that are below -5.
Then you have to understand that size of the arrayTwo is less than(in many cases) or equal to size of arrayTwo.Reason is that the integers below -5 is a subset of integers.
Therefore using same iterator using while loop for two arrays will make an error.
instead using a second for loop , modify the code as below,
int indexArrayOne = 0,
indexArrayTwo=0;
while(indexArrayOne < arrayOne.length){
if(arrayOne[indexArrayOne] < -5){
arrayTwo[indexArrayTwo++] = arrayOne[indexArrayOne];
}
indexArrayOne++;
}
You can use a for loop like what you have done for this.The idea is you have to use two iterators for two arrays.
Use ArrayList for arrayTwo, so that you can hav all element in arrayTwo in just single for loop.
List<Integer> arrayTwo = new ArrayList<>();
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo.add(arrayTwo[i]);
}
}
you can use streams and lambda in this code.but first you have learn Stream API & lambda

Java: taking char input from array results in infinite loop

This is the link the problem that I am trying to solve: https://dmoj.ca/problem/dmopc14c1p5
Here is the code that I have written for taking in input.
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int y = kbd.nextInt(); //number of rows
int x = kbd.nextInt(); //number of columns
int initX = kbd.nextInt(); //initial starting position
int initY = kbd.nextInt();
int endX = kbd.nextInt(); //ending position (main office)
int endY = kbd.nextInt();
char [] [] maze = new char [y][x];
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
maze[i][j] = kbd.next().charAt(0);
}
}
//For checking
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
System.out.print(maze[i][j]);
}
System.out.println();
}
}
However, I don't know how to properly take in the char input in the for loop. I used the scanner.next().charAt(0) method I found with this link (How to take input for 'char' array in Java?), but it results in an infinite loop that does not end no matter how many characters I input.
What am I doing wrong?
Update:
This is the input that I will be receiving (There are no white spaces between characters):
OOXOO
OXOXO
OOOXX
XOXOX
OOOOO
How should I modify my code to make reading this input possible?
Your code works properly. Just remembers that you need to type atleast x*y (your variable name) times of char.
EDIT: I just saw your update. We need to think about it a little bit.
.charAt(0)
Only takes the first character of a string and return it. If you want to take "ooxoo" and turn it into ['o','o','x','o','o'], you can use the toCharArray method on strings. However if you do this, your for loop will loop longer than needed. If you know your sets of input, you can only loop through n numbers of strings and accept them and convert them into array. Let me know if you want me to go more in details.
The java.util.Scanner.next() method finds and returns the next
complete token from this scanner.
Every time you call kbd.next().charAt(0), you call next() and get a complete token. The tokens, by default, are separated by whitespace.
You also need to hit ENTER before System.in makes an data available.
So, enter your characters separated by spaces and end the input with a carriage return.

Adding values to an array of undefined size

I have researched and tried for hours to solve my problem, but the reality is that I can't find anything on it. It is simple really. I need to initialize java arrays of undefined size, and then compare the two. In the process of testing my program, when I have defined the array to a specific length (for example)
int[] array = new int[6];
the code waits until I have entered the six objects to move on to the next segment of code, because it is waiting for 6 integers as defined as the array length. But I can't define the array using
int[] array = {};
it obviously won't work, since array.length function will be 0.
My code is below.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// My problem is in the definition of the arrays or the for loops defining them below.
int[] list1 = new int[]; // undefined
int[] list2 = new int[]; // undefined
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I need to initialize java arrays of undefined size,
You need to use an ArrayList or ask the length at the start.
List<Integer> list1 = new ArrayList<>();
System.out.println("Enter numbers, with a blank line to end");
for (String line; !(line = input.nextLine()).trim().isEmpty(); ) {
list1.add(Integer.parseInt(line));
}
// later
if (list1.equals(list2))
or use an array
System.out.println("Enter the number of numbers, followed by the numbers");
int[] array1 = new int[input.nextInt()]; // enter the size first.
for (int i = 0; i < array1.length; i++)
array[i] = input.nextInt();
// later
if (Arrays.equals(array1, array2))
int[] array = {};
it obviously won't work, since array.length function cannot work.
This works as expected and array.length is always 0
I am still unable to fulfill what I am really trying to accomplish, but I've used my code to compromise. It is to allow the user to specify the length before entering integers.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many variables long is the first list? ");
int n = input.nextInt();
int[] list1 = new int[n];
System.out.print("How many variables long is the second list? ");
n = input.nextInt();
int[] list2 = new int[n];
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I see that this question is an older one but I had the same one (or at least similar) and couldn't find answer I was searching for. And now I believe I have the answer for this and would like to share it. Maybe for someone this will be handy.
According to my understanding the question is about creating a single dimensional array with undefined length and the length of this array is going to be increased by the Scanner input. Lot of answers I have seen were about using the ArrayList. But still I wanted to know how to do it with a single dimensional array. First, let me share with you the code and then the explanation:
public class Main {
static Scanner scanner = new Scanner(System.in);
final static int ARRAY_MAX_LENGTH = 400_000_000;
public static void main(String[] args) {
int[] numbers = createIntArray();
displayArray(numbers);
}
public static int[] createIntArray() {
int[] ints = new int[ARRAY_MAX_LENGTH];
System.out.print("Enter numbers: ");
for (int i = 0; i < ints.length; i++) {
ints[i] = scanner.nextInt();
if (ints[i] == 0) {
break;
}
} return ints;
}
public static void displayArray(int[] ints) {
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
if (ints[i] == 0) {
break;
}
}
}
}
Now the explanation:
We want undefined/infinite array length. The truth is: you can not have it. In programming everything has limit. The byte limit is between -128 to 127 the short limit is -32,768 to 32,767 and the int limit is between -2,147,483,648 to 2,147,483,647. So how do you create array with undefined length? Paradoxically: set the array length. And the length should be the maximum length an array can hold. And then create an exit point when you want the array to accept no more inputs from the Scanner class. I solved it by including in my code the if statement with a break keyword (if(input == 0) break;). Once I do not want to make any input with the Scanner class I just type '0' and press enter and the array does not accept any other input and the inputs made before the '0' is saved int the defined int[] numbers array.
Now coming back to the array max length... I found articles that the array max length is the int max length minus 8 (or something similar). This didn't work for me. I read some posts here on Stack Overflow that the array length depends on the JVM and on other factors I have not explored further. I thing the max array length depends on some settings too but I don't want to lie. This is why I set my array length to 400 000 000. When I set the length to 500 000 000 I got the error:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
If you want to use this code just figure out what is your max array length and use it.
For me this problem was interesting to think about but definitely I would not use it in big programs. It is not efficient at all. For newbies: if you have just learned the one dimensional array, be patient, ArrayList is coming in your later studies and it could make things easier.

How do you count the amount of numbers when the input is given separated by spaces, ended with a letter?

I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);

Trying to figure out how many times a certain set of characters appears in a bigger one with copying Arrays. Getting an error + is this the best way?

I want to write a program that figures out how many times a certain set of characters repeats itself in a longer set of characters (several times for several different set of characters)
I tried to achieve this by "importing" the long set of characters into a char array, and then make a 2D array for all the shorter sets of characters that I want to check the occurence of.
Then, I wanted my for loop to create an "interim" array of the same length as the short arrays have and compare it to each of them, however, the program keeps returning 0 occurences no matte what... And is also taking too long to compute when checking longer arrays with loads of character sets.
import java.util.*;
public class A {
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
//Preberi podatke
int dolzinaDolgi = sc.nextInt(); //D
int dolzinaKratki = sc.nextInt(); //d
int stKratkih = sc.nextInt(); //n
sc.nextLine(); // prehod v novo vrstico
char [] Dolgi = sc.nextLine().toCharArray(); //prebrano dolgo zaporedje
char [][] TabelaKratki = new char [stKratkih][dolzinaKratki];
int [] results = new int [stKratkih];
for (int i=0; i<stKratkih; i++) {
TabelaKratki[i]=sc.nextLine().toCharArray();
}
for (int i=0; i<dolzinaDolgi-dolzinaKratki; i++) {
char [] vmesnoZaporedje = new char [dolzinaKratki];
vmesnoZaporedje = Arrays.copyOfRange (Dolgi, 0+i, dolzinaKratki+i-1);
for (int j=0; j<stKratkih; j++) {
if (TabelaKratki [j] == vmesnoZaporedje) {
results [j] += 1;
}
}
}
for (int index = 0; index<stKratkih; index++) {
System.out.println(results[index]);
}
}
}
Perhaps regular expression is much better.
1. Convert the text to be searched into a pattern.
2. Store all different sets of characters into array.
3. Loop the array and loop to find occurrences using the pattern.
Refer to this answer for count the occurrences. java regex match count

Categories