How to get the nextInt after the nextInt but retain the value - java

My problem is instead of the fixed value of iValueNext, I want the next value on the excel sheet to run, which is 125,152,...
import java.util.*;
import java.io.*;
public class ConvertingData
{
public static void main (String [] args)
{
int i=1;
int j;
int iValue;
int iValueNext;
try
{
Scanner ifsInput = new Scanner(new File("input.csv"));
PrintStream ifsOutput = new PrintStream(new File("output.csv"));
while(ifsInput.hasNextLine())
{
String tokens[] = ifsInput.nextLine().split(",");
String Repeat = tokens[tokens.length - 1];
String Value = tokens[tokens.length - 3];
iValue = Integer.parseInt( Value );
for (i=iValue;i<=iValueNext;i++)
{
System.out.println(i+","+Repeat);
ifsOutput.println(i+","+Repeat);
}
}
ifsInput.close();
ifsOutput.close();
}
catch (FileNotFoundException sMsg)
{
System.out.println("File not found");
}
}
}
Here is part of the csv file:
89,31,31
125,1,32
152,-12,20
155,1,21
181,6,27
287,1,28
290,1,29
308,-8,21

If you need to "peek" at the next line while processing the current line, first read all the lines in:
List<String> lines = new ArrayList<String>();
while(ifsInput.hasNextLine()) {
lines.add(ifsInput.nextLine());
}
ifsInput.close();
then process the lines one by one with access to the next line:
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
String nextLine = i < lines.size() - 1 ? null : lines.get(i + 1);
String tokens[] = line.split(",");
String nextTokens[] = nextLine.split(",");
// whatever logic you need
ifsOutput.close();
}

Related

Accessing indexes that may not exist Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}
The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {
Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code

how can i read and store reattempts?

public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
on hover over component 1 change the style
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadTemps{
public static void main(String[] args) throws IOException {
//taking the word to search from keyboard
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the word you want to search: ");
String input = keyboard.nextLine();
//counter for calculating how many times word wrote in line
int counter = 0;
//counter to find which line we are searching
int counterLine = 1;
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("C:\\KeyWestTemp.txt"));
// Original answer used LinkedList, but probably preferable to use
// ArrayList in most cases
// List<String> temps = new LinkedList<String>();
ArrayList<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.nextLine();
//removing whitespeaces
token1.replaceAll("\\s+","");
//taking all the letters as String
for(int i = 0; i < token1.length(); i++) {
char c = token1.charAt(i);
String s = "" + c;
temps.add(s);
}
//adding a point to find line' end
temps.add("line");
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
//searching on array to find first letter of word
for (int i = 0; i < tempsArray.length; i++) {
String s = temps.get(i);
//if its the end of line time to print
if(s.equals("line")) {
System.out.println("Line" + counterLine + " : " + counter + " occurrence ");
counterLine++;
counter = 0;
}
//if the first letter found need to search rest of the letters
if(s.equalsIgnoreCase("" + input.charAt(0))) {
s = "";
try {
for(int j = i; j < i + input.length(); j++) {
String comp = temps.get(j);
if(comp.equalsIgnoreCase("" + input.charAt(j-i)))
s = s + comp;
}
} catch (IndexOutOfBoundsException e) {
}
//checks if found the word
if(s.equalsIgnoreCase(input))
counter++;
}
}
}
}
This is the code i got for searching char by char for wanted String.
Rather than using inFile1.next();, use inFile1.nextLine(), and don't bother wasting time using a token string.
while (inFile1.hasNext()) {
temps.add(inFile1.nextLine());
}
use BUFFERED READER , it read line by line
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String fullLine;
while ((line = br.readLine()) != null) {
}
}

Reading CSV file in Java with headers and multiple columns

I am reading a CSV file that looks like the following:
Red Blue Green
1st Y N
2nd Y Y N
3rd N Y
I want the output to be something like
1st Red Y
1st Blue N
2nd Red Y
2nd Blue Y
2nd Green N
3rd Red N
3rd Green Y
I am pulling in the colors row into an array, but I am not sure how to get my desired output. Below is my code so far:
public String readFile(File aFile) throws IOException {
StringBuilder contents = new StringBuilder();
ArrayList<String> topRow = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
if(line.startsWith(",")) {
for (String retval: line.split(",")) {
topRow.add(retval);
//System.out.println(retval);
}
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
The first row needs to be read and stored as array/list (I prefer array here, as it will be faster). Then subsequent rows needs to be parsed and stored, with the column name fetched from the first row, now stored as array.
In the code, I have directly written a String with line breaks, I suggest to use a List of String Array (of length 3), so that it can be used easily for any future action.
public String readFile(File aFile) throws IOException {
String data = "";
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null;
int cnt = 0;
String[] topRow = new String[0];
while (( line = input.readLine()) != null){
if(cnt==0){
String[] l = line.split(",");
topRow = new String[l.length-1];
for(int i= 0; i<l.length-1; i++){
topRow[i] = l[i+1];
}
}
else{
String[] l = line.split(",");
for(int i= 1; i<Math.min(l.length, topRow.length+1); i++){
if(!l[i].equals("")){
String row = "";
row = l[0];
row = row + " " + topRow[i-1];
row = row + " " + l[i];
if(data.equals(""))data = row;
else data = data + "\n" + row;
}
}
}
cnt++;
}
}
catch (IOException ex){
ex.printStackTrace();
}
return data;
}

I am working on a program that checks the spelling of a txt file using a given dictionary in java. I am not getting the right outputs

I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}

Read from a file in Java

Does anybody know how to properly read from a file an input that looks like this:
0.12,4.56 2,5 0,0.234
I want to read into 2 arrays in Java like this:
a[0]=0.12
a[1]=2
a[2]=0;
b[0]=4.56
b[1]=5
b[2]=0.234
I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.
This is the code I tried:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IFFTI {
public static int size=0;
public static double[] IFFTInputREAL= new double[100];
public static double[] IFFTInputIMAG= new double[100];
static int real=0;
static int k=0;
public static void printarrays(){
for(int k=0;k<size;k++){
System.out.print(IFFTInputREAL[k]);
System.out.print(",");
System.out.print(IFFTInputIMAG[k]);
System.out.print("\n");
}
}
public static void readIFFT(String fileName){
try {
Scanner IFFTI = new Scanner(new File(fileName));
while (IFFTI.hasNextDouble()) {
if(real%2==0){
IFFTInputREAL[k] = IFFTI.nextDouble();
real++;
}
else{
IFFTInputIMAG[k] = IFFTI.nextDouble();
real++;
k++;}
}
try{
size=k;
}catch(NegativeArraySizeException e){}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
}
I think this will do what you want:
String source = "0.12,4.56 2,5 0,0.234";
List<Double> a = new ArrayList<Double>();
List<Double> b = new ArrayList<Double>();
Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
while ( parser.hasNext() ) {
List use = a.size() <= b.size() ? a : b;
use.add( parser.nextDouble() );
}
System.out.println("A: "+ a);
System.out.println("B: "+ b);
That outputs this for me:
A: [0.12, 2.0, 0.0]
B: [4.56, 5.0, 0.234]
You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].
You will have to read the complete line.
String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read
Then.. you split the line on the commas or the spaces
String[] values = line.split(" |,");
This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]
Now, just reorganize the contents between the two order arrays.
Reading from a file in Java is easy:
http://www.exampledepot.com/taxonomy/term/164
Figuring out what to do with the values once you have them in memory is something that you need to figure out.
You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:
public class SplitTest {
public static void main(String[] args) {
String raw = "0.12,4.56 2,5 0,0.234";
String [] tokens = raw.split(",|\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
}
EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.
Read the content from the file
Split the string on spaces. Create for each element of the splitted array an array.
String input = "0.12,4.56 2,5 0,0.234";
String parts[] = input.split(" ");
double[][] data = new double[parts.length][];
Split each string on commas.
Parse to a double.
for (int i = 0; i < parts.length; ++i)
{
String part = parts[i];
String doubles[] = part.split(",");
data[i] = new double[doubles.length];
for (int j = 0; j < doubles.length; ++j)
{
data[i][j] = Double.parseDouble(doubles[j]);
}
}
File file = new File("numbers.txt");
BufferedReader reader = null;
double[] a = new double[3];
double[] b = new double[3];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
if ((text = reader.readLine()) != null) {
String [] nos = text.split("[ ,]");
for(int i=0;i<nos.length/2;i++){
a[i]=Double.valueOf(nos[2*i]).doubleValue();
b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
}
}
for(int i=0;i<3;i++){
System.out.println(a[i]);
System.out.println(b[i]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}

Categories

Resources