read csv file into 2d array - java

CSV File:
515.30,516.81
516.81,514.27
516.74,517.68
517.54,516.72
517.61,517.64
517.22,516.99
517.21,517.33
516.99,516.92
516.96,517.5
517.38,516.91
No blank lines in between.
My program so far:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class CSVRead
{
public static void main(String arg[]) throws Exception
{
double[][] test = new double[9][2];
String[] testStr = new String[19];
String delimiter = ",";
Scanner sc = new Scanner("kort.csv");
while (sc.hasNextLine())
{
String line = sc.nextLine();
testStr = line.split(delimiter);
}
for (int i=0; i<10; i++)
{
for (int j=0; j<2; j++)
{
test[i][j] = Double.parseDouble(testStr[2*i+j]);
}
}
for (int y=0; y<10; y++)
{
for (int x=0; x<2; x++)
{
System.out.print(test[y][x] +" ");
}
}
} //main()
} // CSVRead
Exception in thread "main" java.lang.NumberFormatException: For input string: "AEX2008kort.csv"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at CSVRead.main(CSVRead.java:26)
Java Result: 1

Change to
Scanner sc = new Scanner(new File("kort.csv"));
You want to parse the content of the file, not the String "kort.csv"

After you have done what Alex mentioned, you need to change the way testStr is being used. In your current code, testStr will always have the last line elements (517.38 and 516.91). What you probably want to do is to store the Double numbers in a List perhaps,
List<Double> mynumbers = new ArrayList<Double> ();
and use it later on to populate your 2D array. Once you have split the line into testStr, you should add these numbers to the list,
mynumbers.add(testStr[0]);
mynumbers.add(testStr[1]);
Finally, in the parseDouble method, instead of passing testStr you should pass your list:
mynumbers.get(index_you_want);

Related

Java.util.Scanner: NoSuchElementException, on 2nd input from user [duplicate]

This question already has answers here:
Scanner NoSuchElementException
(2 answers)
Closed 2 years ago.
I am running into an error within my program when trying to get input from user. Basically what the program is, it is to pull data from two different exported txt files which I will then cross reference from each of them. At this point I am just trying to test out the file information gathering that the program is going to do prior to cross referencing.
What is happening, I read the one file which is "FromFile.txt" and then it will print out everything and then ask what the other file name that we need to test. At this point it will then throw that error the 2nd time it asks for the input from the user.
I am having difficulties trying to figure out why this is throwing the error
This is the error that is being thrown.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at CrossReferencingTool.getInputString(CrossReferencingTool.java:98)
at CrossReferencingTool.main(CrossReferencingTool.java:23)
Below is the code where it is having the error.
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next(); <----------------- This is the line where it is throwing the error
input.close();
return string;
}
below is the overall code that is being ran.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CrossReferencingTool {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<ArrayList<String>> list1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> list2 = new ArrayList<ArrayList<String>>();
System.out.println("What is the filename of the file you want to cross reference from:");
File file1 = new File(getInputString());
populateList(file1, list1);
printList(list1);
System.out.println("\nwhat is the filename of the file you want to cross reference with:");
File file2 = new File(getInputString());
populateList(file2, list2);
printList(list2);
}
private static void printList(ArrayList<ArrayList<String>> list) {
String row;
for(int x = 0; x < list.size(); x++) {
row = "";
for(int y = 0; y < list.get(x).size(); y++) {
row += list.get(x).get(y);
if( (y + 1) < (list.get(x).size())) {
row += ", ";
}
}
System.out.println(row);
}
}
private static void populateList(File file, ArrayList<ArrayList<String>> list) throws FileNotFoundException {
Scanner reader = new Scanner(file);
String splitLine[];
String line;
ArrayList<String> internalList;
while(reader.hasNextLine()) {
internalList = new ArrayList<String>();
line = reader.nextLine();
splitLine = line.split(",");
for(int x = 0; x < splitLine.length; x++) {
internalList.add(splitLine[x]);
}
list.add(internalList);
internalList = null;
}
reader.close();
}
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next();
input.close();
return string;
}
}
Figured out this was because I closed out the scanner on each time I would use the getInputString() function. this would create and then also close out a scanner everytime it is called I do not know why this is causing this though.
could you try to use input.nextLine() instead of input.next() inside your getInputString() method?

How would I separate one value of an array (for the entire array) into alphabetic and numeric characters, and then into separate arrays? (Java)

I've been struggling to find an answer to my specific problem here. I understand that I can use regex to separate array values, but they both don't seem to work and I can't figure out how to get the two values separately. Thanks!
Here's my code without any separation of arr:
package boomaa;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.lang.*;
public class Solution{
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("A.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
System.out.println(Arrays.toString(arr));
for (int i = 1;i<arr.length;i++) {
System.out.println(arr[i]);
}
}
}
My input is formatted like this:
3
1 CS
2 CS
1 SS
If the numbers and characters are separated by a space, simply iterate over the array and use the String method split to split at the space.
Scanner sc = new Scanner(new File("A.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] numbers = new String[lines.size()];
String[] characters = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
String[] components = lines.get(i).split(" ");
numbers[i] = components[0];
characters[i] = components[1];
}

Why can't I read Strings from a file?

The code is supposed to read an array of strings from a file then print it out. I'm not sure what is wrong with the code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program2 {
public static void main(String[] args) throws IOException {
//PriorityQueue<String> q = new PriorityQueue<String>();
//file that contains strings
File file = new File("infix.txt");
Scanner scnf = new Scanner(file);
// array count
int arycnt = 0;
// gets the count of the array in the file
while(scnf.hasNextLine()){
arycnt++;
scnf.next();
}
// creates array
String[] letter = new String[arycnt];
//reads in array from file
Scanner scnf2 = new Scanner(file);
for(int i = 0; i<arycnt ;i++){
letter[i] = scnf2.next();
}
// suppose to print all of the array
for (int i = 0;i < letter.length;i++){
System.out.println(letter[i]);
}
}
}
You are mixing up between nextLine and next. Replace your hasNextLine() with hasNext() and you should be OK.

Changing input so in can take any length of string, problems with output

Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.

Java, basic array error

I am trying to do a Java program that will let me input 10 words, and then the words should be repeated in reverse order (the last first etc).
This is my current code:
import java.util.Scanner;
import java.lang.String;
public class Words {
public static void main(String[] args){
String word[] = {};
for(int x = 0; x < 10; x+=1) {
System.out.println("Input any word");
Scanner input = new Scanner(System.in);
word = new String[] { input.next() };
}
for(int y = 9; y >= 0; y-=1) {
System.out.println(word[y]);
}
}}
It gives me the following error when trying to compile:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at Words.main(Words.java:21)
I am new to Java and would appreciate help, thanks in advice.
That's not how arrays work.
Change String word[] = {}; to String word[] = new String[10];
Also, change word = new String[] { input.next() }; to word[x] = input.next().
It is also a good idea to move Scanner input = new Scanner(System.in); outside of the for loop. You should read up on how arrays work to make sure this doesn't happen again.
You could try use an ArrayList to do this like so:
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList al = new ArrayList();
do{
System.out.println("Enter word");
String word = sc.nextLine();
al.add(word);
if(al.size()==10){
System.out.println("Words in reverse order");
for(int i = al.size()-1; i>= 0; i--){
System.out.println(al.get(i));
}
}
}while(al.size()<10);
}
}
I think this answers your question properly.
All the best
Sean

Categories

Resources