Im trying to practice some java and I am confused. I am trying to enter in multiple numbers into a 3*3 array, however when I run my program I get a compliation error (Exception in thread "main"java.lang.NumberFormatException)? How can parse multiple ints from a Joptionpane into the arrays?
public static int[][] enterMatrix() {
String NumberstoParse = JOptionPane.showInputDialog("Enter list: ");
int UserInput = Integer.parseInt(NumberstoParse);
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = UserInput;
return matrix;
}
}
I think the main issue is when parsing the String from the JOptionPane. Integer.parseInt() sees the commas and throws NumberFormatException. Might be worthwhile to do some testing of this method, possibly with JShell!
Here, I have taken the input String "1, 2, 3, 4, 5, 6, 7, 8, 9" and used method split from class String to make an array of String that is split by (",\s+"). This means, split around the matching regular expression, which here is "a comma and one or more white space characters". Each individual String from the array is then processed with Integer.parseInt().
public static int[][] enterMatrix() {
String numberstoParse = JOptionPane.showInputDialog("Enter list: ");
String[] splitNumbers = numberstoParse.split(",\\s+");
int[][] matrix = new int[3][3];
int ctr = 0;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = Integer.parseInt(splitNumbers[ctr]);
ctr++;
}
return matrix;
}
Adding to what Alex already added below is the code which will take care of some border line issues there are some test cases include few test cases. The code is documented, I hope this helps...
public class Dummy
{
public static void main(String[] args)
{
String temp = "";
for(int x = 0; x <10; x++){
temp = temp + x+"";
int[][] matrix = enterData(temp);
System.out.println("Given Input:" + temp);
if(matrix != null){
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
System.out.println("-------------");
temp +=",";
}
}
//Once you understand the test cases, you can remove the argument and use the JOptionPane for input
public static int[][] enterData(String input)
{
//TODO: Please user JOPtionPane I have added this just to make the test cases work
//String input = JOptionPane.showInputDialog("Enter list: ");
//This will split the Input on the basis of ","
String[] inputArr = input.split(",");
//Variable has a counter which which will represent the number of inputs received
int inputArrCount = 0;
int[][] matrix = new int[3][3];
//If the size is greater than 9, then as u suggested an error is printed
if(inputArr.length > 9 ){
System.err.println("Number length > 9");
return null;
}
for(int i = 0; i <matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
//If to just track that inputArrCount never goes beyond the inputArr elements
if(inputArrCount < inputArr.length){
int temp = Integer.parseInt(inputArr[inputArrCount++]);
matrix[i][j] = temp;
}
}
}
return matrix;
}
}
Related
I have assignment where I have to print and fill an array consisting of 50 indices with random integers then print the values out. Then below that print a list of the numbers in the reverse index with a histogram next to each value. Im supposed to use a nested for loop to solve this and only could get the first section of the problem so far. This is my first time using stackoverflow and I am not expecting an upright answer but if someone could help me understand nested for loops a little more, it would be greatly appreciated.
public static void main(String[] args) {
Random ranGen = new Random();
int[] ranArray = new int [SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for(int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
for(int j = 0; j < ranArray[i]; j++) {
System.out.println("Histrogram");
System.out.println(ranArray[i] );
}
}
}
}
How the output of the code should look like
For the second section, you can iterate on each random number again and for each number, print it with System.out.printf("%-5d", number) ("%-5d" pads the number with spaces to the right) and have a nested loop from 0 to number-1 and print the start with System.out.print(stars).
public static void main(String[] args) {
int SIZE = 5;
Random ranGen = new Random();
int[] ranArray = new int[SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for (int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
}
System.out.println("-------------------------");
System.out.println("Histograms:");
for (int i = ranArray.length - 1; i >= 0; i--) {
System.out.printf("%-5d", ranArray[i]);
for (int j=0; j<ranArray[i]; j++) {
System.out.print(stars);
}
System.out.println();
}
}
I have one text file in which each String holds one line of numbers say 203 and I have one 2d array int puzzle[][].
The lines of file are in the array list Arraylist<String> lines .The first String from the array list goes into puzzle[0].The second String goes into puzzle[1], etc.
The problem I'm having is that after splitting the lines I cannot convert those numbers into integers because it gives me number format exception for -1 what if I will split that - and 1 as well.
I tried the following and also making deep copy of the string array and then transforming each string into an integer
public void parseFile(ArrayList<String> lines)
{
ArrayList<String> l = lines;
for(int i =0; i<puzzle.length; i++)
puzzle[i][0] = Integer.parseInt(l.get(i).split(""));
}
it should give me 2d array with integers
Here is a method that will take a list of strings made up of single digit numbers and convert the list to a 2d array of int. This code makes no use of Java 8 streams.
public static int[][] parseFile(List<String> lines) {
int[][] result = new int[lines.size()][];
int multiplier = 1;
int counter = 0;
for (String line : lines) {
List<Integer> row = new ArrayList<>();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '-') {
multiplier = -1;
continue;
}
int n = (int)c - 48;
row.add(n * multiplier);
multiplier = 1;
}
int[] rowArray = new int[row.size()];
for (int j = 0; j < row.size(); j++) {
rowArray[j] = row.get(j);
}
result[counter] = rowArray;
counter++;
}
return result;
}
Below is my test code, execute from main
List<String> list = new ArrayList<>();
list.add("-111");
list.add("2-13");
int[][] result = parseFile(list);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.printf("%d ", result[i][j]);
}
System.out.print("\n");
}
Output
-1 1 1
2 -1 3
Im creating a program that will generate a word search game but am still in the early stages. I have taken all the input from a text file and converted it into an array that provides the word, its initial row and column starting point, and whether its horizontal or vertical. I have started a new method that will create the basic puzzle array that contains only the word to be hidden. My problem is that im consistently getting:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at WordSearch.createPuzzle(WordSearch.java:50)
at WordSearch.main(WordSearch.java:25)
The snippet of code that is the issue is as follows:
public static char[][] createPuzzle(int rows, int cols, Word[] words) {
char[][] puzzle = new char[rows][cols];
for (int i = 0; i <= 9; i++) {
int xcord = words[i].getRow();
int ycord = words[i].getCol();
if (words[i].isHorizontal() == true) {
String word = words[i].getWord();
for (int j = 0; j < word.length(); j++ ) {
puzzle[xcord + j][ycord] = word.charAt(j);
}
} else {
String word = words[i].getWord();
for (int k = 0; k < word.length(); k++) {
puzzle[xcord][ycord + k] = word.charAt(k);
}
}
}
return puzzle;
}
public static void displayPuzzle(String title, char[][] puzzle) {
System.out.println("" + title);
for(int i = 0; i < puzzle.length; i++) {
for(int j = 0; j < puzzle[i].length; j++) {
System.out.print(puzzle[i][j] + " ");
}
System.out.println();
}
}
with:
displayPuzzle(title, createPuzzle(11, 26, words));
in my main method alongside the code that creates the words array.
puzzle[xcord + j][ycord] = word.charAt(j);
If xcord is 8 and j is > 1 you will get an index out of bounds error because your puzzle board only has 9 rows.
You need to make sure your words don't go past the puzzle boundaries.
I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.
Ok, so here are my codes (main method and method I'm trying to call)
I want my method "rotateRR" to basically take the value from board[0] and put it on [1] and keep doing that for that single row. For example:
old array -> [1][2][3][4][5] to become [5][1][2][3][4] <- what new array should look like.
but after I call my method, I put my regular input which should be "1 rr", but it returns the same array. I need to return the updated array from rotateRR method, but it doesn't let me add a return statement.
public class Numbrosia {
static int [][] board = new int[5][5];
public static void main(String [] args){
Scanner scan = null;
try{
scan = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e){
e.printStackTrace();
return;
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = scan.nextInt();
}
}
Scanner input = new Scanner (System.in);
while (true){
showBoard();
System.out.println("What's your move?");
int rowOrCol = input.nextInt();
String action = ("");
action = input.nextLine();
if (action.equals(rowOrCol + " rr")){
rotateRR(board);
System.out.println("The new board looks like: ");
//Im guessing I should put something here?
}
}
}
public static void showBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
System.out.print(board[row][col] + " ");
}
System.out.println(" ");
}
}
//METHODS
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
//Its not letting me add a "return" type, tells me it is a syntax error on and an invalid type
The main problem with the method is that it's not even doing what you described as the functionality:
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
Should be changed to:
public static void rotateRR (int [][] board){
// Saves the last entry of board, because
// each entry should be shifted to the right
int[] temp = board[board.length - 1];
// Here you should only run till board.length - 2, because
// if you add 1 to i for accessing the next entry
// you can maximal access the entry with number board.length - 1
for (int i = 0; i < board.length - 1; i++){
board[i] = board[i+1];
}
// Set the first entry to temp
board[0] = temp;
}
So after that method your array you inserted as a parameter is changed the way you described above. Notice that you don't need a return type, since the change affects the original array (keyword call-by-reference).
You have made the function void therefore you cannot return anything from it. So what you need to do is change it from void to something like char * and then return the associated char * to solve your problem
Read this: http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html for any further doubts.
Change this:
public static void showBoard()
to this
public static return-type showBoard()