How to read "Vertically" from data sets such as CSV - java

So my issue right now is that I'm really unsure of how to read data "vertically". As an example:
A B C D E F
1 4 1 3 5 8
2 3 1 3 6 4
3 2 1 3 7 5
4 1 1 3 7 4
I have to manipulate this data in a few ways. I'm pretty fine with anything on the same line although I'm clueless as to how to compare items from the same column. One objective I am trying to achieve is to re-write this with only attributes that have more than one domain. So in this instance, C, D, and all the numbers below them should be omitted.
public void dataProcessing(){
File file = new File("insertFilePathHere");
try {
Scanner input = new Scanner(file);
//Please ignore these, they are more relevant to the actual data set
String titles = input.nextLine();
String types = input.nextLine();
int i = 0;
while (input.hasNext()){
String line = input.nextLine();
//This is refering to a line that is incomplete, they are to be removed
if (line.contains("?")){
continue;
}
//For printing what i have back into a table to check results
String[] row = line.split(" ");
for(String index : row){
System.out.printf("%10s", index);
}
System.out.println();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

I'd solve the problem this way:
use a 2D Array (new XXX[][])
read/scan the file LineByLine (two for/while-loops)
write those lines into the array
and then you should be able to work with that array
It should look something like this (I'm sorry if there are any wrong Functions or Errors because I'm coding this without an IDE with SyntaxHighlighting or IntelliSense - there shouldn't be any Errors though):
char[][] arr = new char[rows][cols];
Scanner scanCol = new Scanner(file);
//if you know the #rows and #cols
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
for(int row = 0; y < rows; y++) {
//incase an Exception comes up
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
}
}
//if you only know the #cols
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(true) { //unfortunately there's no function called hasNextChar()
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
}
//the top one but in a cleaner way if inline ifs work in while-Loops
int totalRows = 0;
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(row=0?true:(row < totalRows)) {
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
totalRows = row;
}
//if you just know the file exists ;)
while(scanCol.hasNextLine()) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(true) {
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
}
//to find out how many cols and rows there are
scanCol = new Scanner(file);
int cols = 0;
while(scan.hasNextLine()) {
cols++;
scan.nextLine();
}
scanRow = new Scanner(new Scanner(file).nextLine());
while(true) {
try {
scanRow.nextChar();
rows++;
} catch (Exception e) {
break;
}
}
Please feel free to correct me or ask questions about my solution!

Related

How to sort multiple indexes in an array and encode them based on value?

So, I have a for loop that loops through an array then performs a try/catch to see if any of those indexes can be made a long from their original string value.
for (int i = 0; i < recordLine.split("\t").length; i++) {
try {
long l = Integer.parseInt(recordLine.split("\t")[i]);
} catch (NumberFormatException numberFormatException) {
System.out.println("Here are the Strings: " + i);
System.out.println("NumberFormatException: " + numberFormatException.getMessage());
}
}
String[] splitRecordLineItems = recordLine.split("\t");
Character[] resultsArray = new Character[splitRecordLineItems.length];
for (int i = 0; i < splitRecordLineItems.length; i++) {
try {
long l = Long.parseLong(splitRecordLineItems[i]);
resultsArray[i] = 'L';
} catch (NumberFormatException nfe) {
resultsArray[i] = 'S';
}
}
You can then print the content of resultsArray for example using following line:
System.out.println(Arrays.toString(resultsArray));

2D Array File Reader

For my computer science class I'm making an website username/password program. I decided to use a 2D string array, and it hasn't been working out the best. I tried to make a file reader to read the logins that get written but I keep getting the ArrayIndexOutOfBoundsException error. My file reader code is below, and also included is my login input code. I am just starting Java so I have very basic programming knowledge.
private void fileReader() throws FileNotFoundException {
File inFile = new File(filePath);
try {
Scanner freader = new Scanner(inFile);
while (freader.hasNextLine()) {
for (int j = 1; j <= pass.length; j++) {
pass[j][0] = freader.nextLine();
pass[j][1] = freader.nextLine();
pass[j][2] = freader.nextLine();
}
}
freader.close();
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
Login input:
private void input() throws InterruptedException, FileNotFoundException {
for (int i = 0; i < pass.length; i ++){
System.out.println(i);
if (i == pass.length){
add();
}
c.print("Please enter the website: ");
pass[i][0] = c.readLine();
c.print("Please enter your username: ");
pass[i][1] = c.readLine();
c.print("Please enter your password: ");
pass[i][2] = c.readLine();
while (true){
c.clear();
synchronized (c) {
c.println("To continue adding logins, press C. To exit the program press ESC.");
c.println(pass[i][0] + " " + pass[i][1] + " " + pass[i][2]);
}
if (c.isKeyDown(KeyEvent.VK_C)){
break;
}
else if (c.isKeyDown(KeyEvent.VK_ESCAPE)){
fileWriter();
pass();
}
Thread.sleep(10);
}
}
}
Any help is greatly appreciated!! Thanks!
The main reason is because of this:
for (int j = 1; j <= pass.length; j++) {
pass[j][0] = freader.nextLine();
pass[j][1] = freader.nextLine();
pass[j][2] = freader.nextLine();
}
An array starts from 0. By making j = 1, you are starting on the second array in the group, you need to start with 0 and read up to but not including the array length.

List<String[]> method Adding always same values

In my Java Project, i want to read values from txt file to List method.Values seems like;
1 kjhjhhkj 788
4 klkkld3 732
89 jksdsdsd 23
Number of row changable. I have tried this codes and getting same values in all indexes.
What can i do?
String[] dizi = new String[3];
List<String[]> listOfLists = new ArrayList<String[]>();
File f = new File("input.txt");
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
int i = 0;
while (s.hasNext() && i < 3) {
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}
} catch (FileNotFoundException e) {
System.out.println("Dosyaya ba?lanmaya çal???l?rken hata olu?tu");
}
int q = listOfLists.size();
for (int z = 0; z < q; z++) {
for (int k = 0; k < 3; k++) {
System.out.print(listOfLists.get(z)[k] + " ");
}
}
String [] dizi = new String [3];
dizi is a global variable getting overridden eveytime in the loop. Thats why you are getting same values at all indexes
Make a new instance everytime before adding to the list.
You put the same reference to the list, create a new array in while loop.
while (s.hasNextLine()){
String[] dizi = new String[3]; //new array
int i = 0;
while (s.hasNext() && i < 3)
{
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}

Getting a NullPointerException - how to remove it?

I'm new in programming.
array [row][col] = line.charAt(col);
^ this the line is where I'm getting NullPointerException in my code. How to remove it?
Scanner in = null;
try {
in = new Scanner(new FileReader("C:\\Documents and Settings\\UserXP\\My Documents\\src\\file.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
ArrayList<String>arrayList=new ArrayList<String>();
while((line=in.nextLine())!=null) {
arrayList.add(line);
char [][] array = new char [2337][];
for (int row = 0; row<arrayList.size(); row++)
for(int col = 0; col<line.length(); col++) {
array [row][col] = line.charAt(col);
System.out.print(""+ array[row][col]);
}
System.out.println("");
}
//Close the input stream
in.close();
You're never allocating any memory for the second dimension of your array:
char [][] array = new char [2337][];
Gives you 2337 char[]s but all of them are null.
You'll need
array[row] = new char[line.length()];
before the column loop.
EDIT (clarify where to insert):
for (int row = 0; row<arrayList.size(); row++) {
array[row] = new char[line.length()];
for(int col = 0; col<line.length(); col++) {
array [row][col] = line.charAt(col);
System.out.print(""+ array[row][col]);
}
}
Note also, as your logic appears inefficient, as you're recreating rows every time you're adding a line.

What's wrong with my loop? Keep getting NoSuchElementException

I keep getting a NoSuchElement Exception at the line maze[r][c]=scan.next();. How can I resolve that?
try {
Scanner scan = new Scanner(f);
String infoLine = scan.nextLine();
int rows=0;
int columns=0;
for(int i = 0; i<infoLine.length();i++){
if(Character.isDigit(infoLine.charAt(i))==true){
rows = (int)infoLine.charAt(i);
columns = (int)infoLine.charAt(i+1);
break;
}
}
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNextLine()==true && r<rows){
for(int c = 0; c<columns;c++){
maze[r][c]=scan.next();
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Look at this part of your code:
while(scan.hasNextLine()==true && r<rows){ // 1
for(int c = 0; c<columns;c++){ // 2
maze[r][c]=scan.next(); // 3
} // 4
r++; // 5
} // 6
In line 1 you are checking to make sure that scan has another line available. But in line 3, you read that line - inside the 2:4 loop. So if there are more than 1 columns, you will be asking for the next scan more than once - and you only checked to see if there was one next line. So on the second column, if you're at the end of scan, you try to read from scan even though it's run out.
Try this:
try {
Scanner scan = new Scanner(f);
String infoLine = scan.nextLine();
int rows = 0;
int columns = 0;
for (int i = 0; i < infoLine.length();i++) {
if (Character.isDigit(infoLine.charAt(i))) {
rows = Character.digit(infoLine.charAt(i), 10);
columns = Character.digit(infoLine.charAt(i + 1), 10);
break;
}
}
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNextLine() && r < rows) {
int c = 0;
while(scan.hasNextLine() && c < columns) {
maze[r][c]=scan.next();
c++
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Categories

Resources