I am creating an double array called MySize that will hold user input.
How do I clear an array, by filling it in with all zero using an if statement?
I tried creating a function called ClearMySize to allow the user to clear the entire array that they created and fill it full of zeros
package trashmysize;
import java.util.Arrays;
import java.util.Scanner;
public class TrashMySize {
static double [][] MySize;
static int b1 = 0;
static int b2 = 0;
static Scanner scanSize = new Scanner(System.in);
static int columns = 0;
static int rows = 0;
static int NumberOfElements;
static void PrintMySize(){
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print(MySize[r][c] + " ");
}
System.out.println();
}
}
static void BuildMySize(){
System.out.println("Enter the number of columns: ");
rows = Integer.parseInt(scanSize.nextLine());
System.out.println("Enter the number of rows: ");
columns = Integer.parseInt(scanSize.nextLine());
MySize = new double[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print(MySize[r][c] + " ");
}
System.out.println();
}
Menu();
}
static void UserEntryMySize(){
int blue = 0;
double value = 0;
while(blue < 1){
System.out.println("Enter value: ");
value = Double.parseDouble(scanSize.nextLine());
System.out.println("What row: ");
b1 = Integer.parseInt(scanSize.nextLine()) -1;
System.out.println("What column: ");
b2 = Integer.parseInt(scanSize.nextLine()) -1;
try{
if(b1 <= rows-1 && b2 <= columns-1){
System.out.println("Good position");
}
blue++;
}
catch(Exception e){
System.out.println(e.getMessage());
System.out.println("Not a good position");
blue++;
BuildMySize();
}
}
MySize[b1][b2] = value;
PrintMySize();
Menu();
}
static void ClearMySize(){
if(MySize != null){
//for (int i = 0; i < MySize.length; i++)
//MySize[i] = 0;
Arrays.fill(MySize, 0);
} else {
System.out.println("Array is empty");
}
System.out.println("\nArray has been cleared: " + Arrays.toString(MySize));
PrintMySize();
Menu();
}
static public void Menu(){
int choice = 0;
Scanner myScan = new Scanner(System.in);
System.out.println("\nMain Menu\n"
+ "\n1. Build MySize"
+ "\n2. Add to MySize"
+ "\n3. Clear MySize"
+ "\nMake a choice: ");
choice = Integer.parseInt(myScan.nextLine());
switch(choice){
case 1 -> BuildMySize();
case 2 -> UserEntryMySize();
case 3 -> ClearMySize();
case 4 -> Menu();
case 5 -> {
System.out.println("Thank you for playing! Have a good day!");
System.exit(0);
}
}
}
public static void main(String[] args) {
Menu();
}
}
But that doesn't work. It just seems to crash my code.
I keep getting the error message of:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at java.base/java.util.Arrays.fill(Arrays.java:3429)
at trashmysize.TrashMySize.ClearMySize(TrashMySize.java:107)
at trashmysize.TrashMySize.Menu(TrashMySize.java:136)
at trashmysize.TrashMySize.UserEntryMySize(TrashMySize.java:91)
at trashmysize.TrashMySize.Menu(TrashMySize.java:135)
at trashmysize.TrashMySize.BuildMySize(TrashMySize.java:51)
at trashmysize.TrashMySize.Menu(TrashMySize.java:134)
at trashmysize.TrashMySize.main(TrashMySize.java:145)
C:\Users\Amanda\Documents\NetBeansProjects\trashMySize\nbproject\build-impl.xml:1330: The following error occurred while executing this line:
C:\Users\Amanda\Documents\NetBeansProjects\trashMySize\nbproject\build-impl.xml:936: Java returned: 1
BUILD FAILED (total time: 15 seconds)
Everything works as it should except for my clear function.
Well the easiest solution is:
if(condition)
{
for(int i=0; i<array.length; i++)
{
array[i] = 0
}
}
Is this what you're looking for?
Iterate through all indexes and set values to 0.
if(array != null){
for(int i=0;i<array.length;i++) array[i] = 0;
}
OK, so this is more complicated than the other answers have realized.
The first thing to note is that this is not an simple array. The array is declared as a:
static double [][] MySize;
That is an array of arrays.
(And really seriously, that is an awful choice that you have made for the array variable name. It bears no relation to what the variable means, and it is a major Java style violation to boot.)
You try to fill it like this:
Arrays.fill(MySize, 0);
So now we look at the overloads for Arrays.fill and we see that there are three overloads that might be relevant:
Arrays.fill(int[], int); #1
Arrays.fill(double[], double); #2
Arrays.fill(Object[], Object); #3
The first one does not apply because double[][] is not compatible with int[] (though the 2nd argument matches exactly).
The second one does not apply because double[][] is not compatible with double[]. (The second argument is compatible by a primitive widening conversion.)
The third one does apply because double[][] IS compatible with Object[], because double[] is a subtype of Object. However, for that to "work", the Object you are supplying as the 2nd argument needs to be a double[]. It it isn't. It is an int. And Java is performing a boxing conversion to turn that into a Integer ... 'cos that is what the JLS says it should do.
So as a result, fill will attempt to assign an Integer into a cell of an array double[] ... which throws an exception.
Lesson #1. Be careful with multi-dimensional array types in Java. They are not entirely intuitive.
Lesson #2. Only use Array.fill(...) for 1D arrays.
The actual solution here is this:
for (double[] d: MySize) {
Arrays.fill(d, 0.0);
}
or you could you could use a nested for loop and do the filling by hand.
Related
minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}
I'm currently making a sudoku program, however my current code seems to fail me. The script below should put out a print "Inconsistent sudoku puzzle" if a row contains the same number several times, but sadly it doesn't.. I've tried several different attempts but no succes.
public void checkRow() {
int count = 0;
for(int j = 0; j < list.size(); j++) {
for(int a = 1; a < 10; a++) {
for (int i=0; i < list.get(j).length(); i++) {
if(list.get(j).charAt(i) == a) {
count++;
if(count >= 2) {
System.out.println("Inconsistent sudoku puzzle");
count = 0;
}
}
}
count = 0;
}
}
}
This is the collection of all my error checks:
public void errorCheck() {
this.checkRow();
this.checkColumn();
this.checkBox();
}
Here i load it into my main. The code is a lot more elaborate, but these should be the sections involving the issue.
public static void main(String[] args) throws Exception {
Sudoku s = new Sudoku("C:\\Users\\caspe\\Downloads\\Sudoku001.sdk");
s.printBoard();
s.errorCheck();
s.getNum();
while(getNum() > 0) {
System.out.println("Next move, please (row , column , value )");
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int column = scanner.nextInt() ;
int value = scanner.nextInt();
if (s.moves(row, column, value)); {
s.errorCheck();
}
s.printBoard();
}
}
The issue
You're using charAt and trying to compare the result of that to a number:
list.get(j).charAt(i) == a
However doing so you're comparing the ascii value of the character to the number.
Example:
String a = "3";
System.out.println((int) a.charAt(0)); // This prints 51
The solution
If you wanted to compare number values you'd have to do something like this:
String a = "3";
System.out.println(Character.getNumericValue(a.charAt(0))); // This prints 3
Character.getNumericValue(a.charAt(0)) returns the number value of the character.
Implementation
Implementing that into your code would look like this:
Character.getNumericValue(list.get(j).charAt(i)) == a
This line:
if(list.get(j).charAt(i) == a)
is always false because you compare a char with an int.
Replace it with
if((list.get(j).charAt(i)-'0') == a)
list.get(j).charAt(i)-'0' gives you the numeric representation of the char
the problem is:
'if(list.get(j).charAt(i) == a)'
its comparing with the "a" value on the ascii table
I am practicing making arrays. I have created two classes. The first class (Processor class) contains a parameter that accepts an array of 10 values that the user inputs. It also contains 4 methods to process: the average of the numbers entered, the largest value, the smallest value, and a toString method. This class compiles with no errors.
import java.util.Arrays;
public class Processor {
public int[] value;
int aSum = 0;
int largest = value[0];
int smallest = value[0];
private int number;
public Processor() {
int[] numbers = new int[10];
}
public void arrayAverage(int[] value) {
double average = 0;
for (int i = 0; i < value.length; i++) {
aSum = aSum + value[i];
average = aSum / value.length;
}
}
public void arrayMax() {
for (int i = 1; i < value.length; i++) {
if (value[i] > largest) {
largest = value[i];
}
}
}
public void arrayMin() {
for (int i = 1; i < value.length; i++) {
if (value[i] < smallest) {
smallest = value[i];
}
}
}
public String toString() {
return Arrays.toString(value);
}
}
The second class ProcessorTester creates an instance of Processor and asks for the user to input 10 values for the array. I then call the methods from the first class and print their values. However, when I compile this class I get the following error: "incompatible type- int cannot be converted to Processor".
import java.util.Scanner;
public class ProcessorTester {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Processor[] inputs = new Processor[10];
System.out.println("Input 10 values for the array: ");
for (int i = 0; i < inputs.length; i++) {
inputs[i] = keyboard.nextInt();
}
System.out.println("The average of the numbers inputed is: ");
System.out.println(arrayAverage.inputs());
System.out.println("The largest of the numbers inputed is: ");
System.out.println(arrayMax.inputs());
System.out.println("The smallest of the numbers inputed is: ");
System.out.println(arrayMin.inputs());
System.out.println("The numbers inputed are: ");
System.out.println(toString.inputs());
}
}
Is this a problem with my coding in the main method in the Processor class?
You've declared inputs as an array of Processor:
Processor[] inputs = new Processor[10];
A Processor contains an array of integer, but a Processor is not an integer. Thus, this isn't legal:
inputs[i] = keyboard.nextInt();
that says to take the ith Processor and assign it an integer. But inputs[i] is a Processor so you can only assign Processor to it.
Pro-tip: when the compiler gives you an error, it will tell which line in which file caused the error. When posting a question always indicate the line that causes the compile error as that saves people from having to read every line of your file trying to find the issue.
I will recommend the following changes at the least:
Processor class
Change
public Processor() {
int[] numbers = new int[10];
}
to
public Processor() {
value = new int[10];
}
ProessorTest Class
In the main method,
change
Processor[] inputs = new Processor[10];
System.out.println("Input 10 values for the array: ");
for (int i = 0; i < inputs.length; i++) {
inputs[i] = keyboard.nextInt();
}
to
Processor inputs = new Processor();
System.out.println("Input 10 values for the array: ");
for (int i = 0; i < inputs.length; i++) {
inputs.value.add(keyboard.nextInt());
}
Look at your Code here:
Processor[] inputs=new Processor[10]; //1
for(int i=0; i<inputs.length;i++)
{
inputs[i]=keyboard.nextInt(); //2
}
//1 You make an array of type Processor
//2 You try to fill this Array with integers inputs[i]=keyboard.nextInt();
This causes this specific error.
I have a code where in, an array is to be defined, in which the size is based on user input. How do I do that?
My code is as follows:
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of layers in the network:");
int Nb_Layers = in.nextInt();
int[] Hidden_layer_len = new int[Nb_Layers];
for (int i = 0; i < Nb_Layers-1; i++)
{
System.out.println("Enter the length of layer" +(i+1)+":");
Hidden_layer_len[i] = in.nextInt();
if(i == 0)
{
double [][] E = new double[Hidden_layer_len[i]][1];//This is the array I need based on the size mentioned.
}
}
System.out.println(E);
}
I want this to be a 2D array. Any suggestions would be appreciated. thank you!
You can define the array outside the for loop and assign inside. E.g.
double[][] E = null;
for (int i = 0; i < Nb_Layers - 1; i++) {
System.out.println("Enter the length of layer" + (i + 1) + ":");
Hidden_layer_len[i] = in.nextInt();
if (i == 0) {
E = new double[Hidden_layer_len[i]][1];
}
}
This way it will be available when you print it at the end.
By the way you probably want to print it like this
System.out.println(Arrays.deepToString(E));
Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}