Array transformation - java

I am far away from fully understanding Arrays and am really struggling with this. Here is the problem: I need to manipulate an array of ints. My program takes two values separated by comma; first value is the size of the array and the second the type of transformation. Define a constant MAXSIZE that represents the size of the array and is initialized to contain values from 0 to MAXSIZE. Based on the input the program should print out each transformation: halve, double, absolute and accumulate. I think my code doesn't even get to the cases method. The last couple of lines of my code do not want to get formatted for some reason, I finish up with return arrayList;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.useDelimiter("[,\n]");
System.out.println("Enter size of array and case, separated by comma: ");
final int MAXSIZE = input.nextInt();
String transformation = input.next();
int arrayList[] = new int[MAXSIZE +1];
for (int i = 0; i < arrayList.length; i++) {
arrayList[i] = i;
}
for(int i = 1; i<arrayList.length; i++) {
System.out.print(arrayList[i] + "\n");
}
System.out.print(transformation);
cases(transformation, arrayList);
}
public static void caseDouble(String transformation, int[] arrayList) {
for(int i = 1; i<arrayList.length; i++) {
arrayList[i] = arrayList[i]*2;
}
for(int i = 1; i<arrayList.length; i++) {
System.out.print(arrayList[i] + "\n");
}
}
public static void caseAccumulate(String transformation, int[] arrayList) {
int total = 0;
for (int i = 1; i<arrayList.length; i++) {
total += arrayList[i]/arrayList.length;
System.out.println(arrayList[total]);
}
}
public static void caseAbsolute(String transformation, int[] arrayList) {
for(int i = 1; i<arrayList.length;i++) {
System.out.print(Math.abs(arrayList[i]));
}
}
public static void caseHalve(String transformation, int[] arrayList) {
for(int i = 1; i<arrayList.length;i++) {
System.out.print(arrayList[i]/2);
}
}
public static int[] cases(String transformation, int[] arrayList) {
switch(transformation) {
case "absolute":
caseAbsolute(transformation, arrayList);
break;
case "halve":
caseHalve(transformation, arrayList);
break;
case "accumulate":
caseAccumulate(transformation, arrayList);
break;
case "double":
caseDouble(transformation, arrayList);

You should avoid putting spaces between the comma and the transformation name when you are giving the input.
E.g.
type
10,absolute
instead of
10, absolute.

Related

How to pass variables with 2 2D Arrays in Java?

I am having issues passing arrays to my methods it is getting an error of "cannot find symbol"but I am confused on how these 2D arrays should be passed in the method "how many" This program is supposed to prompt for 18 ints and placed into 2 2D arrays then return of they are equal or not. Am I supposed to place the array names in boolean equalOrNot = howmany(FirstArray, SecondArray);
or what?
import java.util.Scanner;
public class n01092281
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int FirstArray [][] = new int[3][3];
int SecondArray [][] = new int[3][3];
System.out.print("Enter List1 and List2 (18 numbers): ");
for (int row = 0; row < FirstArray.length; row++)
{
for(int column = 0; column < FirstArray[row].length; column++)
{
FirstArray[row][column] = input.nextInt();
}
}
for (int row = 0; row < SecondArray.length; row++)
{
for(int column = 0; column < SecondArray[row].length; column++)
{
SecondArray[row][column] = input.nextInt();
}
}
boolean equalOrNot = howmany(FirstArray, SecondArray);
if (equalOrNot)
{
System.out.println("Two Arrays Are Equal");
}
else
{
System.out.println("Two Arrays Are Not equal");
}
}
public class strict
{
public boolean howmany(int[][] FirstArray, int[][] SecondArray)
{
boolean equalOrNot = true;
if(FirstArray.length == SecondArray.length)
{
for (int i = 0; i < FirstArray.length; i++)
{
if(FirstArray[i] != SecondArray[i])
{
equalOrNot = false;
}
}
}
else
{
equalOrNot = false;
}
}
}
}
Few points that could help over the shared code :
Please follow better-naming conventions.
public boolean howmany does not have a return statement to actually return a boolean value, possibly add at the end of the method :
return equalOrNot;
The comparison should also be over the number of columns of the array and the condition should become somewhat like :
if(FirstArray[i][j] != SecondArray[i][j])
You cannot call howmany method currently from a static context even considering Strict to be an inner class(with those inappropriately matched braces).

How do you identify if a char entry is a two or more digit number?

What I mean to say is, if I have an array which is delimited by spaces how can I distinguish if two consecutive chars are two or more digit numbers instead?
Bear with me I'm still pretty new to programming in general.
this is what I have so far:
import java.util.*;
public class calc
{
public static String itemList;
public static String str;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
delimitThis();
sc.close();
}
public static void delimitThis()// Delimiter to treat variable and numbers as seperate
{
List<String> items = Arrays.asList(str.split("\\s+"));
System.out.println(items);
for (int i = 0; i < str.length(); i++)
{
itemList = items.get(i);
category();
}
}
public static void category()////For Filtering between vars and constants and functions
{
for (int x = 0; x < itemList.length(); x++)
{
char ite = itemList.charAt(x);
if(Character.isDigit(ite))
{
System.out.println(ite + "is numeric"); //Will be replaced by setting of value in a 2 dimensional list
}
}
}
First of all, I want to fix your mistakes:
Mistake 1:
// bad
for (int i = 0; i < str.length(); i++)
{
itemList = items.get(i);
category();
}
You are traversing through List<String> items, but str.length is being used. It is wrong. To {print the item then do category()} for every item in items, the code should be:
// fixed
for (int i = 0; i < items.size(); i++)
{
itemList = items.get(i);
category();
}
Mistake 2:
for (int x = 0; x < itemList.length(); x++)
{
System.out.println(itemList);
}
I'm not sure what you wanted to do here. It's just that your code does not make sense to me. I assume you wanted to print line every character from itemList, the code should look like this:
for (int x = 0; x < itemList.length(); x++)
{
System.out.println(itemList.charAt(x));
}
Done with the mistakes. Now checking an a string whether it contains 2 digit numbers or more, we can use String.matches() with regular expression:
if(itemList.matches("\\d\\d+")){
System.out.println(itemList + " is a two or more digit number");
}else{
System.out.println(itemList + " is NOT a two or more digit number");
}
The code looks like this in the end:
import java.util.*;
public class Calc
{
public static String itemList;
public static String str;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
delimitThis();
sc.close();
}
public static void delimitThis()// Delimiter to treat variable and numbers as seperate
{
List<String> items = Arrays.asList(str.split("\\s+"));
System.out.println(items);
for (int i = 0; i < items.size(); i++)
{
itemList = items.get(i);
category();
}
}
public static void category()////For Filtering between vars and constants and functions
{
for (int x = 0; x < itemList.length(); x++)
{
System.out.println(itemList.charAt(x));
}
// is 2 digit number or not?
if(itemList.matches("\\d\\d+")){
System.out.println(itemList + " is a two or more digit number");
}else{
System.out.println(itemList + " is NOT a two or more digit number");
}
}
}
To check whether a string is at least a 2 digit number, use this regex: \d{2,}.
public static boolean is2OrMoreDigits(String s) {
Pattern p = Pattern.compile("\\d{2,}");
return o.matcher(s).matches();
}

Java Array Error

New to java programming and I am currently trying to create a class similar to ArrayList using Arrays.
Am trying to add elements to an array and expand the array by copying them to a new array of bigger size.
I am getting an out of index error at 20.
Code may be messy but currently really stuck.
public class MyArrayList{
private String[] strings;
private int arraySize;
private int storedStrings;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
storedStrings = 0;
for (int i = 0; i < this.arraySize;i ++){
if (strings[i] != null){
storedStrings = storedStrings +1;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
strings[i] = newArray[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize = this.arraySize +10;
}
else{
strings[storedStrings] = string;
}
for(int i = 0; i < strings.length; i++)
{
//System.out.println(strings[i]);
}
}
}
The code is being run in the test class where the error is being generated on line 10 of test class and line 47 of MyArrayList class.
This is the test code
public class TestArrayList{
public static void main(String[] args)
{
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
}
}
you can do it like this:
public void addString(String string){
if (storedStrings == this.arraySize){
this.arraySize += 10;
String[] newArray = new String[this.arraySize];
for (int i = 0; i < this.storedStrings; i++){
newArray[i] = strings[i];
}
this.strings = newArray;
}
if (strings[storedStrings] == null){
strings[storedStrings++] = string;
}
// remove this loop it will show repeating values otherwise
for(int i = 0; i < storedStrings; i++)
{
System.out.println(strings[i]);
}
}
edit: as you are new to java always think about how can you do more with less code, how to avoid repetition of code, how to merge things that do common task. That will help you write better code
edit2 : the problem is with this loop
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
if you have 50 elements in array the getString method on (eg) i = 25 will be 25*5 = 125 which is not the index in the array that's why you are getting ArrayIndexOutOfBound Exception.
you can add
public int size(){
return storedStrings;
}
to check the size of your list which is the maximum item that is inside the list
First with your code there is a mistake in this line
strings[i] = newArray[i];
because you arenĀ“t copying the old data to new array but cleaning the strings array, I suppose that you wish do the contrary action.
In other hand you have extra code that you could improve.
public class MyArrayList{
private String[] strings;
private int arraySize;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
// Since you always do this
// it's better to use a local variale
int storedStrings = 0;
// Use the foreach syntax
// it's less prone to errors
// and easier to read
for (String s : this.strings){
if (s != null){
storedStrings++;
}else{
// since you want to count the strings in your array
// and you put them in this array
// one after the other
// no need to check the whole array
// when you find null you can exit the loop
break;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
// here we need to copy the content of strings in newArray
// NOT the other way
newArray[i] = this.strings[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize += 10;
}else{
this.strings[storedStrings] = string;
}
}
public String[] getStrings(){
return this.strings;
}
}
As for the test class
public static void main(String[] args){
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (String s : a.getStrings()){
System.out.println(a);
}
}

Replacing a number in an array if duplicates are found

Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}
use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}
you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.
Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.
Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}
This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}
Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}

why am i getting a null pointer when converting string to int array?

My main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf("First integer: %s \n", firstInt.display());
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result = "";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
You did not instantiate your array. You need something like:
private int[] intArray = new int[SIZE];
where size is the length of your array.
You are not initialize the array intArray, that way you are getting error, here is the complete program
import java.util.Scanner;
class TestForNull {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf ("First integer: %s \n", firstInt.display());
}
}
and this is LargeInteger
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
private int[] intArray;
Member variables are null by default, so you need to initialize this.
Most likely you want it the same size as your string:
public LargeInteger(String s) {
intArray = new int[s.length()]; // Create the actual array before you try to put anything in it
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
Or you should use a container that resizes itself, like ArrayList.
Diferent approach through Integer.parseInt
Integer.parseInt("yourInt");
To achieve your goal:
String a = "12345667788" //sample
String b = "";
int [] vecInt = new int[a.length()]; // The lack of initialization was your mistake as the above stated
for(int i=0; i< a.length(); i++)
{
b = a.substring(0,1);
a= a.substring(1);
vecInt[i] = Integer.parseInt(b);
}
Please be aware of Double, long have far higher range then Integer which might be enough in your case to avoid an array!
you forgot to initialize the array intArray
I would recommend to use a java.util.List
You forgot to initialize the array. You have written it in constructor and the variables declared in method or constructor needs to be initialize at the same time.
Note : Implementing your logic in Constructor is not recommended unless and until you dont have any other choice.

Categories