I cant seem to use .split right, what am i doing wrong - java

I am trying to split a read in file and put it into a 2d array. The file has 3 strings on each
line seperated by a comma, the overall idea is to arrange this with a sorting algorithm but i cant split the strings, its driving me nuts, can anyone help.
/**
*
*
* #author (your name)
* #version (a version number or a date)
*/
import java.util.*;
import java.lang.String;
import java.util.ArrayList;
import java.util.Arrays;
public class Example2{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/ratings.csv");
String[] sep = new String[inputs.length];
for(int i=0;i<inputs.length;i++){
sep[i]=inputs.split(",");
System.out.println(sep[i]);
}
try{
reader.save("C://somefile.csv",inputs);
}catch (Exception e){
System.out.println(e.getClass());
}
}
}

splitis a method in the String class, and inputs is an array of strings. An array access is expected there. You probably just forgot to add [i] in the code. Also, since you are splitting a string in a loop, you are creating a 2D array of strings, which means sep should be a String[][]. Have a go with this.
public class Example2{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/ratings.csv");
String[][] sep = new String[inputs.length][];
for(int i=0;i<inputs.length;i++){
sep[i]=inputs[i].split(",");
System.out.println(Arrays.toString(sep[i]));
}
}
// ...
}
}

I don't know what are you returning but .split will split sep into a list
this code is correct
sep[i]=inputs.split(",");
but here is your problem
String[] sep = new String[inputs.length];
this is 1 dimensional array but you need 2 dimensional array
answer:
String[][] sep = new String[inputs.length][];
this is just to fix the .split problem

Related

Take input as series of string till # is found in JAVA [duplicate]

This question already has answers here:
Scanner input accepting Strings skipping every other input inside a while loop. [duplicate]
(3 answers)
Closed 3 years ago.
I want to take string as an input from user until "#" is the input i.e a series of string (all in different lines) till "#" is found and store the strings in an arraylist of type string. I wrote this code in JAVA but it's not working as required.
import java.util.ArrayList;
import java.util.Scanner;
public class wordMetaMorphism {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> input = new ArrayList<String>();
while(!(sc.next().equals("#"))) {
String s = sc.next();
input.add(s);
}
System.out.println(input);
}
}
and i am getting this output where only the alternate strings are getting stored. I also tried sc.nextLine() but it is all same.
input - dip
lip
mad
map
maple
may
pad
pip
pod
pop
sap
sip
slice
slick
spice
stick
stock
#
#
output - [lip, map, may, pip, pop, sip, slick, stick, #]
import java.util.ArrayList; import java.util.Scanner;
public class wordMetaMorphism {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> input = new ArrayList<String>();
while(sc.hasNext()) {
String s = sc.next();
if(s.equals("#")) break;
input.add(s);
}
System.out.println(input);
}
}
You are calling sc.next() and checking if that line is equal to "#", then reading the next token. This is causing it to occur with every alternate token.
You could do this:
String token = "";
while(!((token = sc.next()).equals("#")))input.add(token);
instead of the while loop you have.
i have modified your code please check below
import java.util.ArrayList;
import java.util.Scanner;
public class wordMetaMorphism {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> input = new ArrayList<String>();
String s = sc.next();
while(!(s.equals("#"))) {
input.add(s);
s = sc.next();
}
System.out.println(input);
}
}

How to convert string text from notepad into array line by line?

I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));

2d arraylist NoSuchElementException

I am trying to create a 2D ArrayList and add values to it. For some reason I keep getting a NoSuchElementException.
Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/java-arraylist
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
int TestCases = input.nextInt();
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<ArrayList<Integer>>();
List<ArrayList<Integer>> Sdarraylist = new ArrayList<ArrayList<Integer>>();
//ArrayList<ArrayList<String>> 2darraylist = new ArrayList<>();
//ArrayList<String> 1darraylist=new ArrayList<>();
for(int i=0;i<TestCases;i++){
ArrayList<Integer> Fdarraylist=new ArrayList<Integer>();
//size of Arraylist
int NumbersOnCurrentLine = input.nextInt();
for(int j=0;i<NumbersOnCurrentLine;j++){
//add numbers on the current line to the list
Fdarraylist.add(input.nextInt());
}
Sdarraylist.add(Fdarraylist);
}
// data.add(new ArrayList<String>());
//data.get(0).add("String");
}
}
That exception occurs when you try to read from an input, but no input is available. One workaround would be to use use the hasNextInt() method to make sure there is readable input available.
ex)
if (input.hasNextInt()) {
Fdarraylist.add(input.nextInt());
}
This could be the result of the input saying there are three numbers on the current line, when in reality there are only two.
1
3 1 4 <= would cause exception.

Scanning from a file and getting a null pointer exception in java

I am very new at this so I apologize if this may seem very basic. Anyway I am trying to read input from a file and put that data into an array so that I can graph it later. the problem I am having is putting the labels of the data into an array.
Here is what I have currently:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class P6 {
static String titlePie = "Pie Chart";
static int numElements;
static String[] labels;
static double[] dataPieElements;
public static void main(String[] args){
P6 p6 = new P6();
p6.readFile(args[0]);
System.out.println(numElements);
System.out.println(Arrays.toString(dataPieElements));
System.out.println(Arrays.toString(labels));
}
private void readFile(String inputFile) {
try {
Scanner in = new Scanner(new File(inputFile));
while (in.hasNext()){
numElements=in.nextInt();
if (in.hasNextDouble()){
for (int i = 0; i<numElements; i++){
dataPieElements[i]=in.nextDouble();
}
}
else if (in.hasNext()){
for (int i = 0; i<numElements; i++){
labels[i]=in.next();
}
}
}
in.close();
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
The input file looks like this:
6
Nokia
Apple
Google
Samsung
Apple
Other
14.2
26.2
13.1
18.9
11.3
16.3
The error I'm getting is:
Exception in thread "main" java.lang.NullPointerException
So my thinking is that because the doubles are after the strings the pointer reaches the end of the file and never gets the strings, but if I change the order of the if statements and get the strings before the doubles it turns the doubles into strings. So what is the best way to get each data type into its respective array?
Thank you so much for any suggestions you might have!
You declared your arrays labels and dataPieElements, but you didn't initialize those arrays, so they're still null.
Initialize them when you know how many are needed. After
numElements=in.nextInt();
then...
labels = new String[numElements];
dataPieElements = new double[numElements];

Convert string user input to array

Ok so I'm trying to create a programmed where the user is asked to enter a word, this word is then stored as a variable, and then its displayed as an array.
This is what I have so far:
package coffeearray;
import java.util.Arrays;
import java.util.Scanner;
import java.lang.String;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String drink;
String coffee;
int [] a =new int[6];
Scanner in = new Scanner(System.in);
System.out.println("Please input the word coffee");
drink = in.next();
So basically I need some code so that the word stored is then displayed as variable. For example "Coffee" would then be displayed but each letter on its own line.
I've searched all over and can't seem to find out how to do this. Thanks in advance.
Given string str :
String str = "someString"; //this is the input from user trough scanner
char[] charArray = str.toCharArray();
Just iterate trough character array. I'm not going to show you this as this can easily be googled. Again if you're really stuck let me know, but you should really know this.
Update
Since you're new to Java. Here is the code per Jeff Hawthorne comment :
(for int i=0, i < charArray.getlength(); i++){
System.out.println(charArray[i]);
}
You can use String.split("")
Try this:
String word = "coffee"; //you get this from your scanner
if(word.length()>0)
String [] characterArray = Arrays.copyOfRange(word.split(""), 1, word.length()+1);
You can convert the String to a CharSequence:
CharSequence chars = inputString.subSequence(0, inputString.length()-1);
you can then iterate over the sequence, or get individual characters using the charAt() method.

Categories

Resources