Turning text file into a 2d array - java

I need to take a text file like the one below and create a 2d array from the numbers in it. However, it needs to be very general so that it could apply to a text file with more or fewer entries than this one.
1 1 11
1 2 32
1 4 23
2 2 24
2 5 45
3 1 16
3 2 37
3 3 50
3 4 79
3 5 68
4 4 33
4 5 67
1 1 75
1 4 65
2 1 26
2 3 89
2 5 74
This is what I have so far, but it just gives me all zeroes when I print it.
import java.util.*;
public class MySales11 {
//variables
private ArrayList<String> list = new ArrayList<>();
private int numberOfEntries;
private int [][] allSales;
//constructor
public MySales11 (Scanner scan) {
//scan and find # of entries
while (scan.hasNext()){
String line = scan.nextLine();
list.add(line);
}
//define size of AllSales array
allSales = new int[list.size()][3];
//populate AllSales array with list ArrayList
for(int a = 0; a < allSales.length; a++){
String[] tokens = list.get(a).split(" ");
for(int b = 0; b < tokens.length; b++){
allSales[a][b] = Integer.parseInt(tokens[b]);
}
}
}
}

You read all the lines when you wanted to create a array of size numOfEntries.
while (scan.hasNext()) {
scan.nextLine();
numberOfEntries++;//this reads all the lines but never stores
}
allSales = new int[numberOfEntries][3];
while (scan.hasNext()) {//input is empty
//the execution never comes here.
}
Now the input is empty. So it'll never add values to the array.
You can use an arrayList, dynamic - no need to calculate number of lines.
ArrayList<String> list = new ArrayList();
while (scan.hasNext()) {
String s = scan.nextLine();
list.add(s);
}
int [][] myArray = new int[list.size()][3];
for(int i = 0; i < myArray.length; ++i)
{
String[] tokens = list.get(i).split("\\s+");//extra spaces
for(int j = 0; j < tokens.length; ++j)
{
myArray[i][j] = Integer.parseInt(tokens[j]);
}
}

Related

How do I swap columns with a specific indexes in java 2d arrays?

So I've been trying to solve following problem:
Given a two-dimensional array (matrix) and the two numbers: i and j. Swap the columns with indexes i and j within the matrix.
Input contains matrix dimensions n and m, not exceeding 100, then the elements of the matrix, then the indexes i and j.
Sample Input 1:
3 4
11 12 13 14
21 22 23 24
31 32 33 34
0 1
Sample Output 1:
12 11 13 14
22 21 23 24
32 31 33 34
In order to solve it, I wrote following code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int tables = scanner.nextInt();
int[][] matrix = new int[rows][tables];
int i = scanner.nextInt();
int j = scanner.nextInt();
for (int w = 0; w < rows; w++){
int temp = matrix[w][i];
matrix[w][i] = matrix[w][j];
matrix[w][j] = temp;
}
System.out.print(matrix);
}
}
And the error is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 4 at Main.main(Main.java:15).
What might be the problem and solution to it?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 4 at Main.main(Main.java:15).
Above error is because you are directly reading values into i and j but you forgot setting the values inside the matrix[][] as said by vince and jim in the comments.
Use loop to set the values
for(int k=0;k<rows;k++){
for(int l=0;l<cols;l++){
matrix[k][l]=scanner.nextInt();
}
}
and then loop through rows to swap values
Here goes the code
Live: https://onlinegdb.com/rJJ-kMTUL
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] matrix = new int[rows][cols];
for(int k=0;k<rows;k++){
for(int l=0;l<cols;l++){
matrix[k][l]=scanner.nextInt();
}
}
int i = scanner.nextInt();
int j = scanner.nextInt();
for(int k=0;k<rows;k++){
int temp = matrix[k][i];
matrix[k][i] = matrix[k][j];
matrix[k][j]=temp;
}
for(int k=0;k<rows;k++){
for(int l=0;l<cols;l++){
System.out.print( matrix[k][l]+" ");
}
System.out.println();
}
}
}

I want even and odd indexed elements from an array to be stored in separate ArrayLists [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I've declared two ArrayLists and one array which name is str. I want to store even indexed elements of array in number ArrayList and odd indexed in name ArrayList.
Please help me.
Thank you.
import java.util.Scanner;
import java.util.*;
public class Que1 {
public static void main(String[] args)
{
int a=0;
String[] str=new String[1000];
List<String> name = new ArrayList<>();
List<Integer> number = new ArrayList<>();
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
for(int i=0;i<=a;i++)
{
String ns=sc.nextLine();
str=ns.split(" ");
for(int j=0;j<str.length;j=j+2)
{
name.add(str[j]);
Collections.sort(name);
}
for(int k=1;k<str.length;k=k+2)
{
int add=Integer.parseInt(str[k]);
number.add(add);
Collections.sort(number);
}
}
for(int i=0;i<str.length;i++)
{
String valueName = name.get(i);
String valueNumber = number.get(i).toString();
System.out.print(valueName+ " ");
System.out.print(valueNumber+ " ");
}
}
}
output:: here number Arraylist is first printing rather than name ArrayList
and In name arrayList one white space also print i don't know why and last element of name ArrayList is also not printing.
can anyone find solution
2
a 11 b 22 c 33
d 44 e 55 f 66
11 a 22 b 33 c 44 d 55 e 66 BUILD SUCCESSFUL (total time: 20 seconds)
You can write:
for(int j=0; j != str.length; j++) {
if (j % 2 == 0) { // Even
number.add(str[j]);
} else { // Odd
name.add(str[j]);
}
}
And to print the arrays replace the <= with <
You are trying to retrieve the item in the size place but since the counting of items starts from 0, the last item is at size() - 1.
Meaning, you for should write it like this:
for (int i = 0; i < name.size(); i++)

Filling Array List with random data

I have the following variables and ArrayList:
int rowLength, columnLength;
ArrayList<String[]> data = new ArrayList<String[]>();
I need to fill this array list with random data. The data must be string (recommended int that has been converted to String). The main goal is to fill multidimensional array list with random data.
I've tried to do that but I had too many troubles. I'm new in Java, so sometime I need help with basic things as well.
Try using nextInt() from Random. This will create a random int which you can wrap in Integer.toString(int i). Then add it to a String[] then add it to the ArrayList.
For example:
Random r = new Random();
for (int i = 0; i < columnLength; i++) {
String[] s = new String[rowLength];
for (int i = 0; i < s.length; i++) {
s[i] = Integer.toString(r.nextInt());
{
data.add(s);
}
Use nested for loops like below:
int rowLength = 10, columnLength = 5; //Initialize sizes
ArrayList<String[]> data = new ArrayList<String[]>();
for (int row = 0; row<rowLength; row++) {
String[] stringsColumn = new String[columnLength];
for (int col = 0; col <columnLength; col++) {
stringsColumn[col]=Integer.toString(col);
}
data.add(stringsColumn);
}
Output loop
//Note that this output loop will interchange the columns for rows but it works fine for demonstration
for (String[] col:data){
for (String s:col){
System.out.print("\t"+s);
}
System.out.println();
}
Output
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
You can try something like this:
public String generateRandomString(int len) {
String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
And this:
public Integer generateRandomInteger(int range) {
Random rnd = new Random();
Integer val = rnd.nextInt(range);
return val;
}
Having these 2 functions you can add random data to your ArrayList:
data.add(generateRandomString(10));
data.add(generateRandomInteger(200));
There is many, many, many ways to do this. From what I see from your snippet is that you do expect some static range of this "multi dimenesional" "Array":isch thingy.
int rowLength, columnLength;
would then imply two dimensions, is that the case or are you expecting more dimensions, is the dimension(s) dynamic? If two is the limit I guess String[][] would do, else some more dynamic construct of Map or List should work.

Need help writing numbers in the Reverse ORDER

I need some help with this assignment I've been given. Not asking anyone to do my work but I'm really honestly stuck on how to even do this.
I'm supposed to write a program that prompts the user to enter 10 numbers and then have it write all the numbers in reverse order.
Example:
Enter 10 Numbers: 23 89 21 55 67 89 99 13 98 78
Reverse Order: 78 98 13 99 89 67 55 21 89 23
So far all I have is how to get the user inputs. If anyone can push me in the right direction, i'd be very grateful!
import java.util.*;
public class ReverseNumbers
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter 10 numbers:");
for (int i = 0; i< values.length; i++)
{
values[i] = keyboard.nextInt();
}
int[] reverseNums;
reverseNums = new int[10];
for (int i = (values.length -1); i>= 0; i--)
{
reverseNums[ reverseNums.length -1 -i ] = values[ i ];
System.out.println( reverseNums[ i ] );
}
}
}
If you dont want to store the reversed values
for (int i = (values.length -1); i>= 0; i--)
{
System.out.println( values[ i ] );
}
Your code looks good for reading inputs into values. Now you can loop over that array in reverse and print the values:
for (int i = 0; i < values.length; i++)
System.out.println(values[values.length - i - 1]);
Think about it, when i == 0 it will print values[9] since 10 - 0 - 1 = 9. At the end, when i == 9 it will print values[0] since 10 - 9 - 1 = 0.
As you can see, there is no need for the extra reverseNums array.
PS: If you want, you can combine int[] values; and values = new int[10]; into a single line: int[] values = new int[10];
Read in the whole line as a string using Scanner.nextLine(), and then split it into an array using String.split(" ");. After this, you can simply iterate from the end of the array going backwards and print the numbers.
If it's not an assignment then why not try using http://commons.apache.org/proper/commons-lang/ library
ArrayUtils.reverse(int[] array)
I think your code is creating the array correctly. You are just printing out the numbers in the original order because your second for-loop is iterating over them backwards. You can see the correct result by adding the statement below after the last loop:
System.out.println(java.util.Arrays.toString(reverseNums));
You can also perform the complete task with only one iteration:
Scanner keyboard = new Scanner(System.in);
int[] reverseNums= new int[10];
System.out.println("Please enter 10 numbers:");
for (int i = 0; i< values.length; i++) {
reverseNums[values.length -1 - i] = keyboard.nextInt();
}
System.out.println(java.util.Arrays.toString(reverseNums));
To reverse it:
for (int i = 0; i < values.length; i++)
reverseNums[values.length - i - 1] = values[i];

ArrayIndexOutOfBounds. Java Spiral Program

I keep getting the error ArrayIndexOutOfBounds: 4 on line 21. The line is Spiral[VIndx][HIndx]=number. This program is supposed to create a spiral of numbers when given a certain dimension. For example, if given the dimension 3, a 3x3 2d array that spirals numbers. Here's what the spiral should be:
7 8 9
6 1 2
5 4 3
Why aren't my loops working?
import java.util.*;import java.io.*;
public class Spiral{
public static void Spiral(int dimensions, int [][] Spiral)
{
int endNumber = (int)Math.pow(dimensions, 2);
int number = 1;
int rightmovement = 1;
int downmovement = 1;
int leftmovement = 2;
int upmovement = 2;
int HIndx = (dimensions-1)/2;
int VIndx = (dimensions-1)/2;
while(number<=endNumber)
{
for(int i = 0;i<=rightmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
HIndx++;
if(number==endNumber)break;
}
rightmovement++;
for(int i = 0;i<=downmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
VIndx++;
if(number==endNumber)break;
}
downmovement++;
for(int i = 1;i<=leftmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
HIndx--;
if(number==endNumber)break;
}
leftmovement++;
for(int i = 1;i<=upmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
VIndx--;
if(number==endNumber)break;
}
upmovement++;
}
}
public static void main(String[]args)throws IOException
{
File file = new File("spiral.txt");
Scanner input = new Scanner(file);
String [] numbers = new String [2];
int i =0;
while (input.hasNextLine())
{
String line = input.nextLine();
numbers[i]=line;
i++;
}
int dimensions = 0;
input.close();
int [][] Spiral = new int [dimensions][dimensions];
dimensions = Integer.parseInt(numbers[0]);
int range = Integer.parseInt(numbers[1]);
if(dimensions%2==0)
{
dimensions+=1;
}
Spiral(dimensions, Spiral);
for(i = 0; i<dimensions;i++){
for(int j = 0; j<dimensions;j++){
System.out.println(Spiral[i][j]);
}
}
}
}
First, your loop condition should use < rather than <=.
Second, if you think about the spiral you'll realize that you always end with a right movement. You hit the break at the first time you have
if(number==endNumber)break;
but this doesn't exit you out of the while loop - this only leaves the for loop. So then you go into the down movement for loop and get the index out of bounds exception.
Third, you need to first enter the center number before the loop.
Additionally, rightmovement, leftmovement, ... should all be increased by 2 each time. The reason for this is easier to see in a larger grid.
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Notice the first right movement writes 2, then the next one writes 8 9 10, and the last one writes 22 23 24 25 and would have written 26 if you were to continue.
To fix the issue with break not leaving the while loop, just change it into a return statement.

Categories