I'm trying to read in information from a file in order to create a Graph using Java. I have the code below, however, after running the output is null.
The file gives information similar to below
3
Kentucky Florida Alabama
...
...
Where 3 is the amount of vertices in the graph, and the 3 locations in the following line are those vertices. I'm struggling to figure out what's resulting in a null output.
public class ReadGraph {
static int vertNum = 0;
static String[] output;
public static String[] readVertices(Scanner fileIn) throws FileNotFoundException {
fileIn = new Scanner(new File("input.txt"));
vertNum = fileIn.nextInt();
output = new String[vertNum];
for (int i = 0; i < vertNum - 1; i++) {
output[i] = fileIn.next();
}
Arrays.sort(output);
fileIn.close();
return output;
}
}
output should be a list of the locations in alphabetical order at this point. Any help would be much appreciated.
When fileIn object reads the first line, it found the number 3, with this value you are initializing the output array, in the loop you are subtracting one (vertNum - 1), so when the Arrays try to sort, it does not found the complete array, there are just 2 elements so it throws an exception. To avoid this exception you shouldn't subtract one element in the loop, for example:
for (int i = 0; i < vertNum; i++) {
output[i] = fileIn.next();
}
Update:
Complete example:
public class ReadGraph {
static int vertNum = 0;
static String[] output;
public static void main(String[] args) throws FileNotFoundException {
Scanner fileIn = null;
for (String s : readVertices(fileIn)) {
System.out.println(s);
}
}
public static String[] readVertices(Scanner fileIn) throws FileNotFoundException {
fileIn = new Scanner(new File("input.txt"));
vertNum = fileIn.nextInt();
output = new String[vertNum];
for (int i = 0; i < vertNum; i++) {
output[i] = fileIn.next();
}
Arrays.sort(output);
fileIn.close();
return output;
}
}
Output:
Alabama
Florida
Kentucky
Related
public class ArrayDirectory {
public static void main(String args[]) throws FileNotFoundException {
String file = ("lab4b2.txt");
Scanner scan = new Scanner(new FileReader(file));
// initialises the scanner to read the file file
String[][] entries = new String[100][3];
// creates a 2d array with 100 rows and 3 columns.
int i = 0;
while(scan.hasNextLine()){
entries[i] = scan.nextLine().split("\t");
i++;
}
//loops through the file and splits on a tab
for (int row = 0; row < entries.length; row++) {
for (int col = 0; col < entries[0].length; col++) {
if(entries[row][col] != null){
System.out.print(entries[row][col] + " " );
}
}
if(entries[row][0] != null){
System.out.print("\n");
}
}
//prints the contents of the array that are not "null"
}
}
How do I make the following code to split the string into pieces and store them in the multidimentional array? For example:
Text:
123 abc 456
789 def 101 112
array
[123] [abc] [456]
[789] [def] [101] [112]
The numbers from the text being converted to numbers before stored in the array. I believe I have to use Integer parsed.Int(). not sure how to implement it
With the following corrections, you would end up with the entries array with the splitted strings correctly.
public static void main(String args[]) throws FileNotFoundException
{
String file = ("C:\\array.txt");
Scanner scan = new Scanner(new FileReader(file));
// initialises the scanner to read the file file
String[][] entries = new String[100][3];
// creates a 2d array with 100 rows and 3 columns.
int i = 0;
while(scan.hasNextLine())
{
String [] splittedEntries = new String[3];
splittedEntries = scan.nextLine().split(" ");
for( int inx = 0; inx < splittedEntries.length; ++inx )
{
entries[i][inx] = splittedEntries[inx];
}
i++;
}
}
At this moment, your entries array would look like this:
entries[0] = { 123, abc, 456 };
entries[1] = { 789, def, 101 };
So, you can write your own loops now and process as required.
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.
Assume that i have 4 grades in testgrades.txt I don't know why this wont work.
public static void main(String[] args) throws FileNotFoundException {
File file1= new File("testgrades.txt");
int cnt = 4;
int[] grades = new int[cnt];
String line1;
for (int i=0; i<cnt; i++) {
Scanner inputFile2 = new Scanner(file1);
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
System.out.print(grades);
First of all, you should note that arrays in java hold fixed-size elements of the same type.
You can initialize them in one of two ways (not very sure if there are other ways).
//First method
int[] anArray = new int[10];
// Second method
int[] anArray = {1,2,3,4,5,6,7,8,9,10};
In either case, the array is of size 10 elements. Since you are fetching the data from the text file, I'll suggest you count number of lines into a variable and use that value to initialize the array. Then you can use a loop to fill the values this way:
// Assuming you have cnt as your total count of grades.
int[] grades = new int[cnt];
String line1;
for (int 1=0; i<cnt; i++) {
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
This is coming off my head so let me know if you face any problem.
You can do like this
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
File file= new File("testgrades.txt");
Scanner scan = new Scanner(file);
int arr[] = new int[100];
int i = 0;
do{
String line1 = scan.nextLine();
int grades2 = Integer.parseInt(line1);
arr[i++] = grades2;
}while(scan.hasNextLine());
for(int j = 0; j < i; j++){
System.out.println(arr[j]);
}
}
I have two csv both with a primary key, im trying to comapre both keys so that i can combine the related csvs to one with the correct keys, however for now i just wanted to compare what was in collumns one. My mind is a little blank i hope by the code you can sort of figure out the direction im going. im unable to get my arrays to actually take in the strings . Java.lang.arrayindexoutofboundsexception
import java.io.;
import java.util.;
public class UDC {
public void search(String [][] wat, String [][] ud){
}
public static void main (String [] args) throws IOException
{
String [] [] cols = {};
String [] [] cols1={};
int row =0;
int row1 =0;
int j = 0;
/*Scanner s = new Scanner(new File("Watford Update File.csv"));
Scanner c = new Scanner(new File("udc.csv"));
while (s.hasNextLine()){
String line = s.nextLine();
cols =line.split(",");
System.out.println(cols[0]);*/
Scanner s = new Scanner(new File("file1.csv"));
Scanner w = new Scanner (new File("file.csv"));
while (w.hasNextLine())
{
String line1 = w.nextLine();
System.out.println(cols);
//cols[row]=line1.split(",");
row ++;
if(!w.hasNextLine()){
while (s.hasNextLine()){
String line2 = s.nextLine();
//cols1[row1]=line2.split(",");
//put while loop in diffrent method but break
if(cols[j].equals(cols1[row1]))
{
j++;
row1++;
System.out.print(cols[j]);
System.out.print(" ");
System.out.print(cols1[row1]);
System.out.println();
}else{
row1++;
}
}
}
}
}
}
Instead of using arrays for cols and cols1, you should use List<String[]>. Also, your code is very confusing because you have the comparison loop(s?) intertwined with the reading loops. It would be better to simply read in the data first and then do your comparisons.
public static void main(String [] args)
{
List<String[]> cols;
List<String[]> cols1;
try {
cols = readFile("udc.csv");
cols1 = readFile("Watford Update File.csv");
} catch (IOException e) {
e.printStackTrace();
return;
}
// loop through array lists to do your comparisons
// For example, to compare the first column of rows i and j:
// cols.get(i)[0].equals(cols1.get(j)[0])
}
private static List<String[]> readFile(String fileName) throws IOException
{
List<String[]> values = new ArrayList<String[]>();
Scanner s = new Scanner(new File("udc.csv"));
while (s.hasNextLine()) {
String line = s.nextLine();
values.add(line.split(","));
}
return values;
}
I have a problem in my project math.
My project is to write a program that reads a set of elements and its relations. Your input data will be from a text file. (SetRelation).
{1,2,3} {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
I have no problem reading the text file into the program but I'm stuck when I want to try to put the relation into the two dimensional array.
For example: {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
The two dimensional array would have to be like this:
col[0][1][2]
[0] 1 1 1
[1] 1 1
[2] 1
I don't know how to set one into two dimensional array because there are various relations in the text file.
This is my coding.
import javax.swing.*;
import java.util.ArrayList;
import java.io.*;
import java.util.StringTokenizer;
import java.lang.*;
import java.util.*;
public class tests
{
public static int s1[][];
public static int s2[][];
public static int s3[][];
public static int s4[][];
public static int s5[][];
public static int s6[][];
public static int s7[][];
public static int s8[][];
public static int s9[][];
public static int s10[][];
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader infile = null;
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();
ArrayList arr4 = new ArrayList();
try
{
infile = new BufferedReader (new FileReader ("numbers.txt"));
String indata = null;
while ((indata = infile.readLine())!= null)
{
StringTokenizer st = new StringTokenizer(indata," ");
String set = st.nextToken();
arr1.add(set);
String relation = st.nextToken();
arr2.add(relation);
}
for(int i =0; i < arr2.size(); i++)
{
String r = arr2.get(i).toString();
String result = r.replaceAll("[{}(),; ]", "");
arr3.add(result);
}
for(int i = 0; i < arr3.size(); i++)
{
System.out.println(arr3.get(i).toString());
}
for(int i =0; i < arr1.size(); i++)
{
String s = arr1.get(i).toString();
String result = s.replaceAll("[{}(),; ]", "");
arr4.add(result);
}
int set1 = Integer.parseInt(arr4.get(0).toString());
String ss1 = arr4.get(0).toString();
int a = ss1.length();
s1 = new int[a][a];
int sA[][];
/*for(int row=1;row< a;row++)
{
for(int col=0;col < a;col++)
{
sA = new int[row][col];
int firstNo = Integer.parseInt(arr3.get(row).toString());
int secondNo = Integer.parseInt(arr3.get(col).toString());
sA = new int [firstNo][ secondNo] ;
System.out.print(sA);
}
System.out.println();
}*/
char arrA;
char indOdd=' ',indEven=' ';
char[] cArr = arr3.get(0).toString().toCharArray();
//System.out.println(arr3.get(0).toString().length());
int l = arr3.get(0).toString().length();
int arr10[][] = new int[(l/2)][2];
for(int i=0;i< 2;i++)
{
for(int row = 0; row < (l/2);row++)
{
for(int gh = 0;gh < l;gh++)
{
if(i%2==0)
{
indEven = cArr[gh];
System.out.println(indEven);
arr10[row][i] = indEven;
//System.out.println(arr10[row][i]);
//row++;
}
else
{
indOdd = cArr[gh+1];
System.out.println(indOdd);
arr10[row][i] = indOdd;
//row++;
}
}
}
//arr10 = new int[indOdd][indEven];
//System.out.println(arr10);
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
infile.close();
}
}
But I'm stuck how to set one into the two dimensional array if the relation is {(a,b),(a,c),(b,a),(b,c),(c,c)}; and {(33,33),(45,45),(67,67),(77,77),(78,78)};
So, you have two problems: parsing the input and setting the array.
To parse the input, think about the format you're given. An opening curly brace, a bunch of ordered pairs, then a closing brace. Think about this pseudocode:
Read in a left curly brace
While the next character is not a right curly brace{
Read in a left parenthesis
Get the first number and put it in a variable!
Read in a comma
Get the second number and put it in a variable!
Read in a right parenthesis
Store your relation in the array!
}
Now your issue is just how to put it in the array. Your relations are practically already indexes into the grid! Note the 0-indexing, so just subtract 1 from both, and set the resulting coordinate equal to 1.
array[first number-1][second number-1]=1;
Just a TIP:
If your set is for example {b,c,e} and want to have somewhere stored relation elemnt <-> index like b<==>0, c<==>1, e<==>2 you can store that elements in List and then use method indexOf().
I mean something like this
List<String> list=new ArrayList<String>();
list.add("b");
list.add("c");
list.add("e");
System.out.println(list.indexOf("c"));//return 1
System.out.println(list.indexOf("e"));//return 2
System.out.println(list.indexOf("b"));//return 0
Now you just have to figure out how to use it to create your array.