I have a .txt file and it has some numbers like
0,3,4, ... 9
................
1,2,5, ... 6
This is a sudoku design, I want to take this into an array
Scanner in = new Scanner (new File ("sudoku1.txt")); //here I specified the target of the file like C:\\...
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
String n = in.next();
grid [i][j] = Integer.parseInt(n);
}
}
System.out.println(grid);
when I try to see the array, it give an error because of the " , " in the text file, if I delete commas and put spaces instead of commas, it works but even it shows me only 1 row and it does not work correctly.
Do it as follows:
Scanner in = new Scanner (new File ("sudoku1.txt"));
for(int i=0; i<9 && in.hasNextLine(); i++){
String []nums = in.nextLine().split(",");
for(int j=0; j<nums.length; j++){
String n = nums[j].trim();
grid [i][j] = Integer.parseInt(n);
}
}
System.out.println(Arrays.deepToString(grid));
Scanner can use other delimiters. The default one matches the whitespaces.
Here is an example.
String myDelimiterGroup = "[,\\r\\n]"; // a pattern definition
Scanner scanner = new Scanner(yourFile).useDelimiter(myDelimiterGroup);
Hope it helps.
Related
I want to make an ArrayList of a list of characters.
Right now I have this code:
Scanner scannerMcScannersonTM = new Scanner(System.in); //This is trademarked.
String[] inputs = new String[5];
List<List<char>> list = new ArrayList<List<char>>();
for(int i =0; i < inputs.length; i++){
System.out.println("Enter pair number " + (i+1) + " separated by a space");
inputs[i] = scannerMcScannersonTM.nextLine();
for(int j = 0; j < inputs[i].length(); i++){
list[i] = inputs[i].toChar(); //it is clear that I don't know what I am doing lol
}
}
Thanks for your help! :D
Scanner scannerMcScannersonTM = new Scanner(System.in); //This is trademarked.
//you do not need this if you know the size and not using inputs afterwards.
String[] inputs = new String[5];
// java collections can only contain non-primitive types, hence, use Character instead of char
List<List<Character>> list = new ArrayList<>();
for(int i=0; i < inputs.length; i++) {
System.out.println("Enter pair number " + (i+1) + " separated by a space");
String inputs[i] = scannerMcScannersonTM.nextLine();
// .toCharArray() method on string does exactly what it says.
// and Arrays.asList(.. an array ..) will convert the array to a List!
list.add(Arrays.asList(inputs[i].toCharArray()));
}
I'm trying to make a two dimensional array and output the results [3][3] in 3 lines and 3 colons,
but I get it like 123456789 in a straight line.
Now I know that I get this result because of the "println" command but I would like to know how can I get it work the way I want it to. Sorry, I'm new to programming.
import java.util.Scanner;
public class klasa {
public static Scanner lexo = new Scanner(System.in);
public static void main(String[]args){
int[][] array = new int[3][3];
for(int a=0;a<3;a++){
for(int b=0;b<3;b++){
System.out.println("Shkruaj numrat: ");
array[a][b]= lexo.nextInt();
}
}
for(int a =0; a<3;a++){
for(int b=0;b<3;b++){
System.out.println(array[a][b]);
}
}
}
}
You should try:
for(int a = 0; a < 3;a++){
for(int b = 0; b < 3;b++){
System.out.print(array[a][b] + " ");
}
System.out.println(); //new line
}
to make a new line only after three elements (and add spaces (optional)).
Hope this helps.
for(int a = 0; a<3; a++){
for(int b=0; b<3; b++){
System.out.print(array[a][b]);
System.out.print(" ");
}
System.out.println();
}
(That prints trailing spaces on each line, but it's a decent start.)
Use plain old print for each value, then print a newline after each row in your outer loop.
In general make your code reflect precisely what you are trying to do: Print each element in a row, followed by a newline. The computer generally follows your instructions to the letter.
I am trying to split data by lines, using the method split. This is the code i am trying to use but i can't figure out what to use for the parameters of .split(). This is how the data will be in the txt.
19
23
58
49
Scanner sc = new Scanner(new File("random.txt"));
string line = sc.nextLine();
String[] numbers = line.split(" ");
int nums = new int[numbers.length];
for(int i=0;i<numbers.length;i++)
nums[i] = Integer.parseInt(numbers[i]);
The end goal is so that the data can be put into an array, not to just print it.
You dont need to use split if you have only one number in each line.
just use the following
Scanner sc = new Scanner(new File("C:/projects/random.txt"));
while( sc.hasNext()){
System.out.println(sc.nextInt());
}
Try to use it like this:
Scanner sc = new Scanner(new File("random.txt"));
int[] nums;
int i=0;
while(sc.hasNext()){
String line = sc.nextLine();
nums[i] = Integer.parseInt(line);
i++;
}
Hope this helps.
Just as simple as that, you don't need split since you're reading line by line as #Luiggi Mendoza said
Scanner sc = new Scanner(new File("C:/projects/random.txt"));
while( sc.hasNext()){
nums[i] = Integer.parseInt(numbers[i]); //They're stored in here
i++;
}
int max = i; //To keep length of numbers that have been read
for(i = 0; i < max; i++){
System.out.println(nums[i]); //We print them from the array
}
Try this
while(true){
int tmp=line.indexOf(" ");
if(tmp==-1)
break;
System.out.println(ar[i]);
ar[i++]=Integer.parseInt(line.substring(0,tmp));
line =line.substring(tmp+1);
}
I have a working program which takes the first letter of a word then switches it to the back of the word and adds "ay to the end. It works fine but I am trying to store the original word and the newWord in a 2D array and output all contents of the array. I have tried but have come to a dead end.
import javax.swing.JOptionPane;
public class Decoder1App{
public static void main(String[]args){
String word="";
String newWord="";
String log[][] = new String[3][2];
for(int i=0;i<log.length;i++){
for(int j=0;j<log[i].length;j++){
Decoder1 D1 = new Decoder1();`enter code here`
word = JOptionPane.showInputDialog(null,"Please enter your word");
D1.setWord(word);
D1.compute();
newWord=D1.getNewWord();
}
}
JOptionPane.showMessageDialog(null,"The new word is " + newWord);
}
}
What exactly doesn't work?
Why are you using a 2d array?
If you must use a 2d array:
int numOfPairs = 10;
String[][] array = new String[numOfPairs][2];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
array[i] = new String[2];
array[i][0] = "original word";
array[i][1] = "rearranged word";
}
}
Does this give you a hint?
For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays.
When I run the 'readByte' method (see below) I do not get compiler errors , instead, I can not get the contents of the file to print. Instead the console just displays "File Read", demonstrating that it has successfully processed the nested for loop. I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere, any advice on how I can resolve this will be greatly appreciated.
The contents of the file I am trying to read is also below.
A second question (I thought it would be best to put both questions in one post), in my 'writeByte' method (the user enters values into a 2D array which is then printed in a .txt file), allows me to enter two values before I get the follow error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.gc01.FileManager.ByteManager.writeByte(ByteManager.java:93)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:111)
I am sure its something to do with how the for the loop collects the user input, but I can't work out how to correct it. Ideally the file would look similar to the file being read by the 'readByte' method.
I understand this a long question, but I have run into a brick wall and all help would be greatly appreciated!
File Contents (separated by tab)
1 10
2 11
3 12
4 13
public class ByteManager {
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextInt();
System.out.println("How many rows are in the file?");
final int rows = sc.nextInt();
return fileName;
}
public void readByte(final String fileName, int rows,int columns){
BufferedReader br = null;
String[] line;
String splitBy = "\t";
int [][] data = new int[rows] [columns];
try {
br = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < rows; i++){
line = br.toString().split(splitBy);
//data[i] [0] = Integer.parseInt(line[i]);
for (int j = 0; j < columns; j++){
data[i] [j] = Integer.parseInt(line[j]);
System.out.println(data[i][j]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("*****File Read*****");
}
public String chooseFileOutput(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory for the output of the chosen file");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileNameOUT = sc.nextLine();
return fileNameOUT;
}
public void writeByte(final String fileNameOUT){
Scanner input = new Scanner (System.in);
FileOutput createData = new FileOutput (fileNameOUT);
System.out.println("How many rows?");
int rowsOut = input.nextInt();
System.out.println("How many columns?");
int columnsOut = input.nextInt();
System.out.println("Please enter data.");
int newDataR = 0;
int newDataC = 0;
int [] [] data = new int [rowsOut] [columnsOut];
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newDataR = input.nextInt());
System.out.print("\t");
for (int j = 0; j < columnsOut; i++){
createData.writeInteger(newDataC = input.nextInt());
data[i] [j] = data[newDataR] [newDataC];
System.out.print("\t");
}
}
createData.close();
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
final ByteManager object = new ByteManager ();
System.out.println("1 for Read File, 2 for Write file");
String choice = in.nextLine();
if("1".equals(choice)){
object.readByte(object.getByteFile(), 0, 0);
} else if ("2".equals(choice)){
object.writeByte(object.chooseFileOutput());
} else{
System.out.println("Goodbye!");
System.exit(0);
}
}
}
For your first question (about being unable to read):
In the main method, the following line:
object.readByte(object.getByteFile(), 0, 0);
Provides 0 and 0 for the number of rows and columns to be read from the text file. The method getByteFile() does prompt the user for a number of rows and columns, however it does not return this amount and does nothing with those numbers. You must prompt the user for the number of rows and columns and put those as the second and third arguments of the readByte method in main.
Also, in general, I wonder why you bother to create the object int[][] data in both your readByte and writeByte methods. They are void methods, so you don't return the int[][], or do anything meaningful with it. Do you intend to use this object later?
"Line 93 is: 'data[i] [j] = data[newDataR] [newDataC];"
OK that's your problem. I think what you mean to do is the following:
data[i][j] = newDataC;
A multidimensional array is just an array of arrays. When you have an access like this:
data[i][j]
What that means is you are accessing element #j of array #i.
data[][] is an array of int arrays, data[i] is an array of ints and data[i][j] is an int element in data[i].
So what I would recommend is reviewing how multidimensional arrays work and then generally reviewing your code to look for stuff like this:
createData.writeInteger(newDataR = input.nextInt());
Which basically seems nonsensical. Not meant as a negative comment, this line just doesn't make sense in the context of multidimensional arrays because only the "columns" hold int elements.
For your exception:
I wasn't sure my comment was clear, so I'll try here.
You have:
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newDataR = input.nextInt());
System.out.print("\t");
for (int j = 0; j < columnsOut; i++){ //do you mean to increment j here?
createData.writeInteger(newDataC = input.nextInt());
data[i] [j] = data[newDataR] [newDataC];
System.out.print("\t");
}
}
On your second for loop, your are incrementing i, instead of j. You're incrementing it twice, so you'll go 0,2,4...
So you are almost certainly going to exceed that dimension of your array. As Radiodef said, I think you would benefit from reading up on multi-dimensional arrays.