Scanner object keeps expecting input - java

I have the following code in which a matrix is defined through system input:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//define size of matrix
int size = in.nextInt();
int primeSum = 0;
int secSum = 0;
int[] matrix = new int[size*size];
//create matrix
for (int i=0; i<size*size;i++) {
matrix[i] = in.nextInt();
}
in.close();
//sum primary diagonal
for (int i=0; i < size*size;i += (size + 1)) {
primeSum = primeSum + matrix[i];
}
////sum secondary diagonal
// for (int i=(size - 1); i < size*size; i += (size - 2)) {
// secSum = secSum + matrix[i];
// }
System.out.println(Math.abs(secSum - primeSum));
}
}
The code above works in that it allows the user to define an NxN matrix through inputting N as the size - so in the case size = 2 the user would define 4 matrix elements. However, after commenting back in the code for the secondary diagonal, the scanner object keeps expecting input past 4 integers - I have no idea why this would affect the program as I close the input stream before that block of code is reached.

You wrote a potentially infinite loop. I.e. if size is not greater than 2, then i will count down or stay 0. You should cover these corner cases, then your code will be fine.
As far as I can see, you're emulating a two-dimensional array on a one-dimensional. This is something that's hard to understand and easy to mess up. You are better off with a two-dimensional array and some nested loops:
int[][] matrix = new int[size][size];
//create matrix
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
matrix[i][j] = in.nextInt();
}
}
// and so on...

Your this part of code:
for (int i=0; i<size*size;i++) {
matrix[i] = in.nextInt();
}
calls the method nextInt which demands for input as long as the array is filled.

Related

How to write a sufficient program for weed lawn problem?

I need to write a program for the problem below :
you have a lawn (a matrix of n*m) and in some cells, weed has grown, and you want to remove them.
there are two operations :
stomping on a cell: by doing so, one of the weeds in that cell dies and two new weeds appear in cells [i][(j+1)%n) and [(i+1)%n][j].
pulling out a weed: this removes the weed and takes the energy of E_(i,j).
Now given a matrix of energy(how much energy removing one weed from each cell takes) and the places where weeds have grown, we want to calculate the least amount of energy we need to get rid of all the weeds.
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class TEST{
public static void main (String[] args)
{
int n=0, m=0 , k=0;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
k = scanner.nextInt();
scanner.nextLine();
int [][] lawn = new int [n][m];
int [][] NumOfWeed = new int [n][m];
for(int j=0; j<m ; j++){
for(int i=0; i < n ; i ++){
lawn[i][j]= scanner.nextInt();
}
scanner.nextLine();
}
int i_index =0, j_index =0;
for(int i=0; i < k ; i ++){
i_index= scanner.nextInt();
j_index=scanner.nextInt();
scanner.nextLine();
NumOfWeed[i_index][j_index] ++;
}
boolean changing = true;
while(changing){
changing = false;
for(int j=0; j<m ; j++){
for(int i=0; i < n ; i ++){
if(NumOfWeed[i][j]>0){
if(lawn[i][j] > lawn[(i+1)%n][j]+lawn[i][(j+1)%n]){
NumOfWeed[(i+1)%n][j] =NumOfWeed[(i+1)%n][j] + NumOfWeed[i][j];
NumOfWeed[i][(j+1)%n] = NumOfWeed[i][(j+1)%n] + NumOfWeed[i][j];
NumOfWeed[i][j]=0;
changing = true;
}
}
}
}
}
int sumEnergy =0;
for(int j=0; j<m ; j++){
for(int i=0; i < n ; i ++){
sumEnergy = sumEnergy + lawn[i][j]*NumOfWeed[i][j];
}
}
scanner.close();
System.out.println(sumEnergy);
}
}
you can see my own code above, but as you see it's not optimal at all.
any ideas on how I can change it so that it takes less time to perform?
Here is one way of doing it, that should lead to correct results but isn't optimized:
Initialize a matrix a (size n * m) for the actual energy needed if you stomp optimally. Set all values to -1.
Find all minima in the original energy matrix ignoring values where the corresponding position in a is not -1. Set the positions of the minima in a to its value.
While there are changes and a isn't completely filled do the following: For each value (i, j) in a that is -1 and the values to the right and down (with wrap-around) are not -1 set (i, j) to the minimum of the sum of the 2 stomped position and the original energy needed for (i, j).
Continue with 2. until a is completely filled. Then "multiply" the lawn matrix with a (no matrix multiplication, just same position with same position) and sum up the values to get the total.

Why is this line printing twice?

So I help tutor an Algebra 2 class at my local high school, and the class is currently looking over matrices. Though not there, they will eventually get to multiplication of matrices. After taking Computer Science last year and learning Java, the teacher I help thought I should try to write a program to multiple matrices.
At the moment, I have up to defining the numbers for the first array that holds the information for the first matrix. However, I have a small issue. As represented by this picture:
the line asking for the index integers is being repeated after already recording the integers. I assume this is due to my layered for loops, but I can't be for certain. Usually new eyes see problems clearer. Any who could help me would be appreciated.
Code:
package matrixmultiplication;
import java.util.*;
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("What is the size of the first matrix?");
int matrix1Rows = matrixRows();
int matrix1Columns = matrixColumns();
int[] matrix1 = new int[matrix1Rows * matrix1Columns];
doubleSpace();
System.out.println("What is the size of the second matrix?");
int matrix2Rows = matrixRows();
int matrix2Columns = matrixColumns();
int[] matrix2 = new int[matrix2Rows * matrix2Columns];
doubleSpace();
if (matrix1Columns != matrix2Rows) {
System.out.println("These cannot be multiplied!");
System.exit(0);
} else {
matrix1Numbers(matrix1Rows, matrix1Columns);
}
}
public static int matrixRows() {
System.out.print("Rows:");
Scanner rowSc = new Scanner(System.in);
int rows = rowSc.nextInt();
return rows;
}
public static int matrixColumns() {
System.out.print("Columns:");
Scanner colSc = new Scanner(System.in);
int cols = colSc.nextInt();
return cols;
}
public static int[] matrix1Numbers(int rows, int cols) {
int[] numb = new int[rows * cols];
for (int j = 0; j <= numb.length; j += rows) {
for (int i = 1; i <= cols; i++) {
for (int k = 1; k <= rows; k++) {
System.out.println("What is the value for index ("
+ k + "," + i + ")?");
Scanner inp = new Scanner(System.in);
if (j + k <= numb.length) {
numb[j + k - 1] = inp.nextInt();
}
}
}
}
for (int i = 0; i < numb.length; i++) {
System.out.println(numb[i]);
}
return numb;
}
public static void doubleSpace() {
System.out.println();
System.out.println();
}
}
I use NetBeans 8.2 and the latest working version of Java for NetBeans.
I'm not familiar with the matrixmultiplication package, so I may be rambling here.
for (int j = 0; j <= numb.length; j += rows){
I'm not entirely sure what the outer for loop your have is for, but this most outer for loop causes you to ask for the values of the indices cols times more than you want.
I feel that you originally wanted to use this outer for loop to iterate through each row, and wasn't planning on having the second for loop iterating through cols perhaps?
Also, Kevin Anderson mentions this above. You might avoid this problem altogether if you return a double int array as opposed to storing all values in the matrix in a single dimension. I personally feel it would make more sense.
Just nitpicking, but I wouldn't make a new scanner every time you want to use one in a different method. You could just make a field at the top of your class, instantiate it once in your main method, and then pass it in as a parameter to all methods using the scanner.

2D Array with variable internal array length JAVA

Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Store random integers in array

package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop

Java 2D array assigning randomly

I have an array a[5][5] and several values. I want to randomly assign values based on random percentages I create. For example one value is 6 and 25% of the elements in the array should have the value 6. With what I have so far: I created the random percentages and I'm able to randomly assign values for different elements in the array. My problem is: more than 25% of the elements have 6. My question is: How do I make sure that when assigning elements with 6, exactly 25% of the elements in the array a[5][5] have that value? I'm new to programming and tried several loops and ifs but nothing is working out for me. Please push me towards the right direction.
25% of 25 is about 6. It is not accurate. Here is a possible solution.
import java.util.Random;
import java.util.Scanner;
public class Matrix25 {
public static void main(String[] args) {
int[][] Matrix = new int[5][5];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number you want to fill the array to 25%: ");
int number = scanner.nextInt();
int percentage=25;
generateMatrix(Matrix,number,percentage);
printMatrix(Matrix);
}
public static void generateMatrix(int Matrix[][],int num, int perc) {
int n;
int max=Matrix.length*Matrix[0].length;
int[] numbers = new int[max];
Random rnd = new Random();
int m = (int)(max * (perc/100.0));
int x=num>m?m-1:m;
for(int i=0;i<max;i++)
numbers[i]=(i<x)?num:i+1;
for(int i=0;i<Matrix.length;i++)
for(int j=0;j<Matrix[i].length;j++) {
n=rnd.nextInt(max);
Matrix[i][j]=numbers[n];
numbers[n]=numbers[max-1];
max--;
}
}
public static void printMatrix(int Matrix[][]) {
for(int i=0;i<Matrix.length;i++) {
for(int j=0;j<Matrix[i].length;j++)
System.out.printf("%3d\t",Matrix[i][j]);
System.out.print("\n");
}
}
}
I would do it like this
import java.util.Random;
import java.util.Scanner;
class Random2darray {
/**
* #param args
*/
public static void main(String[] args) {
// Create array; you specified 5x5 but you probably shouldn't hard code like this
int[][] numbers = new int[5][5];
//Create a scanner to get user input
Scanner scanner = new Scanner(System.in);
//I am not doing anything to make sure they give a decimal so the program won't work
//right if you are not giving a decimal
System.out.println("How much do you want to fill? Enter a decimal.");
//Get a double
double populatePercentage = scanner.nextDouble();
System.out.println("What number do you want to fill with?");
//Get an int
int fillNumber = scanner.nextInt();
//Don't hardcode like this
int fillTimes = numberOfTimesToFill(25, populatePercentage);
//This is declared outside of the loops because otherwise it will be
//reset each time the loop runs
int count = 0;
//Create a random number generator; default seed is current time which is good enough for this
Random rand = new Random();
//Fill the array with numbers
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Check if you have filled with given number enough times
if(count < fillTimes){
numbers[i][j] = fillNumber;
//Increment count by 1; this is how you are keeping track
count++;
}else{
//Otherwise pick a random number generator
//This will pick a random int between 0 - 50 inclusive
int randomNumber = rand.nextInt(51);
//This will make sure that you are not generating random numbers that are the same
//as the number you are filling with; This says if it is the same generate a new number
while(randomNumber == fillNumber){
randomNumber = rand.nextInt(51);
}
//Once we know its random fill the spot in the array
numbers[i][j] = randomNumber;
}
}
}
//Print the array out
printArray(numbers);
}
private static void printArray(int[][] numbers) {
//Just loop through and print every number
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Print with formatting: this says print a digit (%d) followed by a
//tab(\t) and then specifies what number I want to print
System.out.printf("%d\t", numbers[i][j]);
}
//Print a new line after each row
System.out.printf("\n");
}
}
private static int numberOfTimesToFill(int elements, double populatePercentage) {
System.out.println((int)(populatePercentage * elements));
//Cast to an int to truncate the decimal part of the number because you can't have
//a fraction of an element
return (int)(populatePercentage * elements);
}
}
I have commented the code to explain what everything does. However it does not protect against bad user input and it hardcodes the size of the array, you should always try to avoid hardcoding. In this example I did it (and marked where) to be more clear. Also as was mentioned in the comments above, for your situation where you want exactly 25% of 25 is not possible. This is because .25 * 25 = 6.25 and you can't have .25 of an element.

Categories