I have a text file (archive.txt) which has 9 columns of data separated by a tab. I want to read the columns and perform simple math.
In the example below, I want to find the average cost(iCost) by adding all policies with high (3) or unlimited (4) in column cData then dividing by the total of high and unlimited. High and unlimited are represented by a 3 and 4, respectively, in the archive file.
There are two System.out.println() numbered 1 and 2. They are used to see where the program gets to. It doesn't make it past the first System.out.println.
public int highUnlimited() {
Scanner input = new Scanner(System.in);
input = new Scanner("archive.txt");
int iLargeBundle = 0;
int iCost = 0;
System.out.println("1");
String cDate = input.next();
int cMinutes = input.nextInt();
int cData = input.nextInt();
int cLength = input.nextInt();
boolean cIntCalls = input.nextBoolean();
String cReference = input.next();
int cCostPerMonth = input.nextInt();
String cFirstName = input.next();
String cSecondName = input.next();
System.out.println("2");
if (cData == 3 || cData == 4) {
iLargeBundle = iLargeBundle++;
iCost = iCost + cCostPerMonth;
}
int iTotal = iLargeBundle / iCost;
return iTotal;
}
These are the first two lines of the Archive file. They don't have headings normally
15-Sep-2016 2 1 12 N MT230N 617 C Clark
25-Oct-2016 1 1 12 N ED641N 475 Z Clark
input = new Scanner("archive.txt");
This opens up a scanner on the string "archive.txt", not a file with that name.
If you wish to scan a file, you will need to do the following:
input = new Scanner(new File("archive.txt"));
Here you have your code rewritten with comments showing you how to do it, i've added a loop in case you want to read all the lines of the file you are able to do it (in that loop i added the methods hasNextLine(), returns true if there is a line next and nextLine(), it jumps to the next line). It is important that you import java.io.; to import the class file and import java.util.; to import that class Scanner. I hope i could help you.
public int highUnlimited(){
try{ //you all ways need to try catch the Exceptions when you use Scanner and File.
File f = new File("path"); //We need to create first the file object this is
//done with the constructor File(String path)
Scanner input = new Scanner(f); //You dont need the Scanner.in, the Scanner.in
//scanns input data from the terminal and we want
//to scann it from a File. Th constructor
//Scanner(String path) that you used doesn't exist
//on java.
int iLargeBundle = 0;
int iCost = 0;
String cDate, cReference, cFirstName, cSecondName; // I declare the variables outside so there
int cMinutes, cData, cLength, cCostPerMonth; //is no problem with the while
boolean cIntCalls;
int iTotal = 0; //I've used 0 as default value for iTotal
System.out.println("q");
while(input.hasNextLine()){ //I use hasNextLine in case you have various lines of data in your file
cDate = input.next();
cMinutes = input.nextInt();
cData = input.nextInt();
cLength = input.nextInt();
cIntCalls = input.nextBoolean();
cReference = input.next();
cCostPerMonth = input.nextInt();
cFirstName = input.next();
cSecondName = input.next();
input.nextLine(); //To jump a line so it doesn't block on the while
if (cData == 3 || cData ==4){
iLargeBundle++; //if you only want to add 1 to the variable with this is enough
iCost = iCost + cCostPerMonth;
}
}
iTotal = iLargeBundle/iCost; //as iCost is = if it hasn't been modified here is going
//to show an error because you can't divide by 0 so you have
//to change this in cas iCost is 0
}
catch(Exception e){
System.out.println(e.getMessage());
}
return iTotal;
}
Related
Ok hello guys. I'm trying to develop a code for the game Othello. I have come across a question that I need help with. I want to know how to take the input of an int and char in one single scanner. For example, if user enters D for column and 6 for the row, it woud look like this
What I want is to be able to draw the board with the new spot when the user enters D6 instead of asking for column and row seperately, i want it to do the scanner input all in one go. I have looked all over the web but could not come to a conclusion. This is the code i need help with
public static void main (String args[]){
char column;
int row;
Scanner scan = new Scanner(System.in);
Othello game = new Othello();
//game.startGame();
game.displayBoard();
do{
do{
System.out.print("Enter the column: "); //get column from user
column = scan.next().charAt(0);
}while (game.checkColumn(column) == false); //loop until input is valid
do{
System.out.print("Enter the row : "); //get row from user
row = scan.nextInt();
}while (game.checkRow(row) == false); //loop until input is valid
game.takeTurn(game, column, row);
}while (1==1);
I would suggest you read a whole line, then parse what you need.
Note: This solution will only work for single character / digit combos. Use a regular expression if you want something more complex.
public static void main (String args[]){
char column;
int row;
Scanner scan = new Scanner(System.in);
Othello game = new Othello();
//game.startGame();
while (true) {
game.displayBoard();
do {
System.out.print("Enter the column, then row, for example (A0): ");
String line = scan.nextLine();
column = line.charAt(0);
row = Integer.parseInt("" + line.charAt(1));
} while (!( game.checkColumn(column) && game.checkRow(row) ); //loop until input is valid
game.takeTurn(column, row); // Remove game as a parameter here. It is not needed
// if (gameOver) break;
}
}
It's worth noting that Scanner will read space-separated input as a sequence of values, so, something like this would work if the user types "D 6":
System.out.println("Enter ROW COL: ");
char column = scan.next().charAt(0);
int row = scan.nextInt();
scan.nextLine(); // clear new line
If, on the other hand, you want to read "D6", then you'll need to read the input as a string, and extract components from it manually:
System.out.println("Enter ROWCOL: ");
String raw = scan.next();
char column = raw.charAt(0);
int row = Character.getNumericValue(raw.charAt(1)); //get 2nd digit as int
scan.nextLine(); // clear new line
Could someone help me understand what I am doing wrong please?
I have to read through a file with 11 integers and doubles on each line, each line needs to become its own object and stored in an arrayList. However, the delimiter is a single space. And I have used this code, but it doesnt seem to work and I am not sure what I am doing wrong.
package p2_0000000;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class P2_000000 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Which file year would you like to analyze:\n"
+ "1) 2007\n"
+ "2) 2011\n"
+ "3) 2013\n"
+ "(Enter number for choice)");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
ArrayList<dwellingClass> alist = new ArrayList<dwellingClass>();
if (choice == 1) {
try {
File file = new File("2007.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] info = line.split(" ");
int age = Integer.parseInt(info[0]);
int region = Integer.parseInt(info[1]);
double lmed = Double.parseDouble(info[2]);
double fmr = Double.parseDouble(info[3]);
double extremelyLowIncome = Double.parseDouble(info[4]);
double veryLowIncome = Double.parseDouble(info[5]);
double lowIncome = Double.parseDouble(info[6]);
int bedrooms = Integer.parseInt(info[7]);
double value = Double.parseDouble(info[8]);
int rooms = Integer.parseInt(info[9]);
double utility = Double.parseDouble(info[10]);
dwellingClass dwelling = new dwellingClass(age, region, lmed, fmr, extremelyLowIncome, veryLowIncome, lowIncome, bedrooms, value, rooms, utility);
alist.add(dwelling);
}
scanner.close();
} catch (Exception a) {
a.printStackTrace();
System.exit(0);
};
for (dwellingClass each : alist) {
System.out.println(each);
}
}
System.out.println(alist.get(0).getAge());
}
}
I get these errors:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
Thank you everyone for the help!
I also figured out that this could also work for anyone who reads this post later:
public class P2_0000000 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<dwellingClass> alist = new ArrayList<dwellingClass>();
try {
File file = new File("2007.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
int age = input.nextInt();
int region = input.nextInt();
double lmed = input.nextDouble();
double fmr = input.nextDouble();
double extremelyLowIncome = input.nextDouble();
double veryLowIncome = input.nextDouble();
double lowIncome = input.nextDouble();
int bedrooms = input.nextInt();
double value = input.nextDouble();
int rooms = input.nextInt();
double utility = input.nextDouble();
dwellingClass dwelling = new dwellingClass(age, region, lmed, fmr, extremelyLowIncome, veryLowIncome, lowIncome, bedrooms, value, rooms, utility);
alist.add(dwelling);
}
input.close();
} catch (Exception a) {
a.printStackTrace();
System.exit(0);
};
for (dwellingClass each : alist) {
System.out.println(each.getAge() + each.getRegion());
}
System.out.println(alist.get(0).getAge());
}
}
First you can read the file this way:
Scanner in = new Scanner(new FileReader("2007.txt"));
Secondly to parse white spaces you will need to use something like this:
yourString.split("\\s+");
So your this line should become:
String[] info = line.split("\\s+");
Then you can access your String the way you did it.
But make sure that you are passing the right values i.e. the right types to each of the methods otherwise yo will get the error you are getting.
You should do a number validation of the string you read from the file and make sure that it matches the requirements for building your dwellingClass object.
String line = scanner.nextLine();
String[] info = line.split("\\s+");
boolean validInput = true;
//loop through your info array and check each number is valid beforehand
for(int i = 0; i < info.length; i++)
{
if(!info[i].matches("\\d"))
{
validInput = false;
break;
}
}
//now we want to make sure our input was valid or else we don't create the object
if(info.length == 11 && validInput == true)
{
dwellingClass dwelling = new dwellingClass(
Integer.parseInt(info[0]),
Integer.parseInt(info[1]),
Double.parseDouble(info[2]),
Double.parseDouble(info[3]),
Double.parseDouble(info[4]),
Double.parseDouble(info[5]),
Double.parseDouble(info[6]),
Integer.parseInt(info[7]),
Double.parseDouble(info[8]),
Integer.parseInt(info[9]),
Double.parseDouble(info[4]));
alist.add(dwelling);
}
If you put this inside your while loop it will only create objects with lines read from the file that contain only numbers and contains 11 digits, other lines will simply be ignored. This would allow execution of the file even if a line is not formatted correctly.
You are creating a NEW file, not loading your file. To load a file, you need to use a file input stream. your Scanner wont find anything in a new file and thus its all Null
I stand corrected, the syntax is correct and this would load an existing file. As others have mentioned above its a data issue
I'm trying to write a program that scans through a text file line by line and adds certain integers together on each line. The text file in question has the following format:
01-Jan-2012 ED521D 4 100 30 1499 M N Brewer
02-Jan-2012 ED925H 5 488 30 1499 A B Saini
02-Jan-2012 JF560D 3 275 40 949 M S Cooper
02-Jan-2012 ZK201U 1 359 40 474 R S Chadwick
My aim is to add up the numbers in the third column (4,5,3) if the character in the penultimate column is either an "M" or "A". So the program should output 12 using the text file above. Here's what i've got so far.
public static void main(String[] args) throws IOException {
String filename = "policy.txt";
Scanner input = null;
double itemAmount = 0;
String text = "";
int policyCount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String read = input.nextLine();
String clean = read.replaceAll("\\P{Print}", "");
char policyType = clean.charAt(59);
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
if (policyType == 'A' || policyType == 'M' ){
policyCount++;
}
}
else if(input.hasNext()){
text = input.next();
}
}
System.out.println(policyCount);
System.out.println(itemAmount);
}
This seems to work:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException
{
String filename = "policy.txt";
Scanner input = null;
double itemAmount = 0;
int policyCount = 0;
input = new Scanner(new File(filename));
while (input.hasNext())
{
String read = input.nextLine();
String clean = read.replaceAll("\\P{Print}", "");
char policyType = clean.charAt(59);
if (policyType == 'A' || policyType == 'M')
{
policyCount++;
itemAmount += Character.getNumericValue((clean.charAt(24)));
}
}
input.close();
System.out.println(policyCount);
System.out.println(itemAmount);
}
}
Note that this will only work for single digit numbers in the 24th column. If it might contain more digits you'll have to do a substring on clean and then use Double.valueOf().
I guess would want to put
itemAmount = itemAmount + input.nextInt();
Inside
if (policyType == 'A' || policyType == 'M' ){
}
Hope this helps.
Also, you have not used 'read' String. You are seemingly skipping lines.
Use read.split(" ") to get array of tokens.
Then use 3rd token to parse as Integer.
Add it if the condition is true.
I'm working on a java lab and the first step is reading data from the input text file. I've been trying to fix the code but it doesn't help at all. Could you guys please take a look and let me know what I can do about it?
The error I get is:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Restaurant.<init>(Restaurant.java:35)
at RestaurantTester.main(RestaurantTester.java:11)
For the tester class with main method
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class RestaurantTester {
private static Scanner buffer = new Scanner(System.in);
private static int inputInt;
private static Restaurant restaurant;
public static void main(String[] args) throws FileNotFoundException {
restaurant = new Restaurant();
System.out.print("\n Welcome to Java Restaurant\n");
System.out.print("\n\n*************************************\n");
System.out.print("1. Display Menu\n");
System.out.print("2. Display Server List\n");
System.out.print("3. Restaurant Activities\n");
System.out.print("4. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
while (inputInt != 4) {
switch (inputInt) {
case 1: {
restaurant.displayMenu();
break;
} // end case 1
case 2: {
restaurant.displayServerList();
break;
} //end case 2
case 3:{
System.out.print("\n\n*************************************\n");
System.out.print("1. Restaurant Activity\n");
System.out.print("2. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
while (inputInt != 2) {
restaurant.restaurantActivity();
System.out.print("\n\n*************************************\n");
System.out.print("1. Restaurant Activity\n");
System.out.print("2. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
} // end inner while
break;
} // end case 3
} // end switch
System.out.print("\n\n*************************************\n");
System.out.print("1. Display Menu\n");
System.out.print("2. Display Server List\n");
System.out.print("3. Restaurant Activities\n");
System.out.print("4. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
} // end outer while
System.out.print("\nThank you. The Java restaurant is now closed.\n");
} // end main
}
For my Restaurant class
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Restaurant {
...
private Menu menu;
public ArrayList<Server> servers;
private Activity activity;
public Restaurant() throws FileNotFoundException {
input = new Scanner(new File("menu.txt"));
menu = new Menu();
servers = new ArrayList<Server>();
temp = input.nextLine(); // skip 1st line
for (int index = 0; index < 3; index++) {
servers.add(new Server(input.next(), (input.nextLine()).split(",",6)));
} // assume only 6 tables for each server
temp = input.nextLine(); // skip instruction line
while (input.hasNext()) {
str1 = input.next();
str2 = input.next();
value = input.nextDouble();
menu.setMenuItem(str1,str2, value);
}
} // end constructor
....
}
And heres my text file:
Waiters: first name followed by table list
John 1,2,5,9,11,15
Maria 3,4,6,7,17,18
Mike 8,10,12,13,14,26
Menu: listing of the full menu: item code, name, price
A1 Bruschetta 5.29
A2 Caprese_Flatbread 6.10
A3 Artichoke-Spinach_Dip 3.99
A4 Lasagna_Fritta 4.99
A5 Mozzarella_Fonduta 5.99
E1 Lasagna_Classico 6.99
E2 Capellini_Pomodoro 7.99
E3 Eggplant_Parmigiana 8.99
E4 Fettuccine_Alfredo 7.49
E5 Tour_of_Italy 14.99
D1 Tiramisu 2.99
D2 Zeppoli 2.49
D3 Dolcini 3.49
S1 Soda 1.99
S2 Bella_Limonata 0.99
S3 Berry_Acqua_Fresca 2.88
You need to skip one more line.
Skip one
read three
skip blank line?
skip instructions
loop till the end
From http://www.java-made-easy.com/java-scanner-help.html:
Q: What happens if I scan a blank line with Java's Scanner?
A: It depends. If you're using nextLine(), a blank line will be read in as an empty String. This means that if you were to store the blank line in a String variable, the variable would hold "". It will NOT store " " or however many spaces were placed. If you're using next(), then it will not read blank lines at all. They are completely skipped.
My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")
I may be wrong, but it seems you need to skip two lines after finishing the first portion of the file. You skip one line, but that may just be the line space. So you need to skip again to get to your desired content. Try adding another nextLine()
input.nextline();
temp = input.nextLine();
Also, it's possible you may have a problem with the scanner not going to next line after nextDouble(). If the above didn't work, Try adding a nextLine() after it and see if that works?
value = input.nextDouble();
input.nextLine();
Consider even using a split to avoid this problem
while (input.hasNextLine()) {
String line = input.nextLine();
String[] token = line.split("\\s+");
str1 = tokens[0].trim();
str2 = tokens[1].trim();
value = Double.parseDouble(tokens[2].trim());
menu.setMenuItem(str1,str2, value);
}
The above code will read each line, line by line, then split the three into an array of Strings. The last value will need to be parsed into a double.
Edit: Here's another
servers.add(new Server(input.next(), (input.nextLine()).split(",",6)));
You're reading the next, then the nextLine. You need to read all in one line
Edit: try this code
public Restaurant() throws FileNotFoundException {
input = new Scanner(new File("menu.txt"));
menu = new Menu();
servers = new ArrayList<Server>();
temp = input.nextLine(); // skip 1st line
for (int index = 0; index < 3; index++) {
String line = input.nextLine();
String[] tokens = line.split("[\\s,]+");
String name = tokens[0];
String[] nums = new String[6];
for (int i = 1; i < tokens.length; i++) {
nums[i - 1] = tokens[i].trim();
}
servers.add(new Server(name, nums));
} // assume only 6 tables for each server
input.nextLine();
temp = input.nextLine(); // skip instruction line
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split("\\s+");
str1 = tokens[0].trim();
str2 = tokens[1].trim();
value = Double.parseDouble(tokens[2].trim());
menu.setMenuItem(str1,str2, value);
}
}
For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays.
When I run the 'readByte' method (see below) I do not get compiler errors , instead, I can not get the contents of the file to print. Instead the console just displays "File Read", demonstrating that it has successfully processed the nested for loop. I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere, any advice on how I can resolve this will be greatly appreciated.
The contents of the file I am trying to read is also below.
A second question (I thought it would be best to put both questions in one post), in my 'writeByte' method (the user enters values into a 2D array which is then printed in a .txt file), allows me to enter two values before I get the follow error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.gc01.FileManager.ByteManager.writeByte(ByteManager.java:93)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:111)
I am sure its something to do with how the for the loop collects the user input, but I can't work out how to correct it. Ideally the file would look similar to the file being read by the 'readByte' method.
I understand this a long question, but I have run into a brick wall and all help would be greatly appreciated!
File Contents (separated by tab)
1 10
2 11
3 12
4 13
public class ByteManager {
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextInt();
System.out.println("How many rows are in the file?");
final int rows = sc.nextInt();
return fileName;
}
public void readByte(final String fileName, int rows,int columns){
BufferedReader br = null;
String[] line;
String splitBy = "\t";
int [][] data = new int[rows] [columns];
try {
br = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < rows; i++){
line = br.toString().split(splitBy);
//data[i] [0] = Integer.parseInt(line[i]);
for (int j = 0; j < columns; j++){
data[i] [j] = Integer.parseInt(line[j]);
System.out.println(data[i][j]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("*****File Read*****");
}
public String chooseFileOutput(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory for the output of the chosen file");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileNameOUT = sc.nextLine();
return fileNameOUT;
}
public void writeByte(final String fileNameOUT){
Scanner input = new Scanner (System.in);
FileOutput createData = new FileOutput (fileNameOUT);
System.out.println("How many rows?");
int rowsOut = input.nextInt();
System.out.println("How many columns?");
int columnsOut = input.nextInt();
System.out.println("Please enter data.");
int newDataR = 0;
int newDataC = 0;
int [] [] data = new int [rowsOut] [columnsOut];
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newDataR = input.nextInt());
System.out.print("\t");
for (int j = 0; j < columnsOut; i++){
createData.writeInteger(newDataC = input.nextInt());
data[i] [j] = data[newDataR] [newDataC];
System.out.print("\t");
}
}
createData.close();
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
final ByteManager object = new ByteManager ();
System.out.println("1 for Read File, 2 for Write file");
String choice = in.nextLine();
if("1".equals(choice)){
object.readByte(object.getByteFile(), 0, 0);
} else if ("2".equals(choice)){
object.writeByte(object.chooseFileOutput());
} else{
System.out.println("Goodbye!");
System.exit(0);
}
}
}
For your first question (about being unable to read):
In the main method, the following line:
object.readByte(object.getByteFile(), 0, 0);
Provides 0 and 0 for the number of rows and columns to be read from the text file. The method getByteFile() does prompt the user for a number of rows and columns, however it does not return this amount and does nothing with those numbers. You must prompt the user for the number of rows and columns and put those as the second and third arguments of the readByte method in main.
Also, in general, I wonder why you bother to create the object int[][] data in both your readByte and writeByte methods. They are void methods, so you don't return the int[][], or do anything meaningful with it. Do you intend to use this object later?
"Line 93 is: 'data[i] [j] = data[newDataR] [newDataC];"
OK that's your problem. I think what you mean to do is the following:
data[i][j] = newDataC;
A multidimensional array is just an array of arrays. When you have an access like this:
data[i][j]
What that means is you are accessing element #j of array #i.
data[][] is an array of int arrays, data[i] is an array of ints and data[i][j] is an int element in data[i].
So what I would recommend is reviewing how multidimensional arrays work and then generally reviewing your code to look for stuff like this:
createData.writeInteger(newDataR = input.nextInt());
Which basically seems nonsensical. Not meant as a negative comment, this line just doesn't make sense in the context of multidimensional arrays because only the "columns" hold int elements.
For your exception:
I wasn't sure my comment was clear, so I'll try here.
You have:
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newDataR = input.nextInt());
System.out.print("\t");
for (int j = 0; j < columnsOut; i++){ //do you mean to increment j here?
createData.writeInteger(newDataC = input.nextInt());
data[i] [j] = data[newDataR] [newDataC];
System.out.print("\t");
}
}
On your second for loop, your are incrementing i, instead of j. You're incrementing it twice, so you'll go 0,2,4...
So you are almost certainly going to exceed that dimension of your array. As Radiodef said, I think you would benefit from reading up on multi-dimensional arrays.