External file with multiple numbers per line Java - java

I need help reading an external file that has more than one number per line. Here is the external data file:
1 1
2 3
3 5
4 7
5 2
6 4
1 6
2 8
3 1
4 3
5 5
6 7
1 8
2 1
3 2
4 3
5 4
6 5
I read it in by using
public class Prog435a
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Super Mario\\Documents\\java programs\\Prog435\\Prog435a.in"));
while(kbReader.hasNext())
{
int data = kbReader.nextInt();
System.out.println(data);
}
}
}
However, it prints out the file with each number line by line. So instead of appearing in columns, it appears in a single column. How can I get this to print out in two columns as shown above? Thanks for the help.

Loop by line. Call nextInt() two times per line.
while(kbReader.hasNextLine()) {
System.out.println(kbReader.nextInt() + " " + kbReader.nextInt());
}

Related

Why is my JAVA code for solving sudoku using backtracking not giving any solution? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
This is a code in JAVA for solving the sudoku problem for any 9*9 sudoku grid using backtracking. It is not printing any output. I am not able to find the mistake in this. Please help. I have included one of the sample input int the main function in the form of a 9*9 grid. is_safe function if it is safe to put the selected character there by checking the same row, same column and the corresponding 3*3 grid. The base case checks when cr becomes 9, that is, reaches the end of board and cl becomes 0, that is, when we reach out of the board. Then a possible solution may have been found. We print the board at that point and return to the calling function. It seems logically correct but it is not printing any output.
public static boolean is_safe(int mat[][],int cr,int cl,int i)
{
for(int k=0;k<mat.length;k++)
{
if(k!=cl&&mat[cr][k]==i)
return false;
if(k!=cr&&mat[k][cl]==i)
return false;
}
int row=cr-cr%3;
int col=cl-cl%3;
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
if(mat[k+row][l+col]==i)
return false;
}
}
return true;
}
public static void print(int mat[][])
{
for(int i=0;i<mat.length;i++)
{
for(int j=0;j<mat[0].length;j++)
{
System.out.println(mat[i][j]);
}
System.out.println();
}
}
public static void func(int mat[][],int cr,int cl)
{
if(cr==mat.length&&cl==0)
{
print(mat);
return;
}
int i=cr,j=cl;
if(mat[cr][cl]!=0)
{
if(cl+1==9)
func(mat,cr+1,0);
else
func(mat,cr,cl+1);
}
else{
for(int k=1;k<=9;k++)
{
if(is_safe(mat,i,j,k))
{
mat[i][j]=k;
if(j+1==mat.length)
func(mat,i+1,0);
else
func(mat, i, j+1);
mat[i][j]=0;
}
}
}
}
public static void main(String[] args) {
int mat[][]={{3,0,6,5,0,8,4,0,0},
{5,2,0,0,0,0,0,0,0},
{0,8,7,0,0,0,0,3,1},
{0,0,3,0,1,0,0,8,0},
{9,0,0,8,6,3,0,1,5},
{0,5,0,0,9,0,6,0,0},
{1,3,0,0,0,0,2,5,0},
{0,0,0,0,0,0,0,7,4},
{0,0,5,2,0,6,3,0,0}};
func(mat,0,0);
}
}```
Your print method is never called! It seems that the sodoku is not solvable!
With the following input your code works fine:
{{3,0,6,5,0,8,4,0,0},
{5,2,0,0,0,0,0,0,0},
{0,8,7,0,0,0,0,3,1},
{0,0,3,0,1,0,0,8,0},
{9,0,0,8,6,3,0,0,5},
{0,5,0,0,9,0,6,0,0},
{1,3,0,0,0,0,2,5,0},
{0,0,0,0,0,0,0,7,4},
{0,0,5,2,0,6,3,0,0}};
You can also change your print method to make it more readable:
public static void print(int mat[][]) {
for (int i = 0; i < mat.length; i++) {
List<String> stringList = Arrays.stream(mat[i])
.mapToObj(String::valueOf).collect(Collectors.toList());
System.out.println(String.join(" ", stringList));
}
}
Output:
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9

Creating a Call Simulator

The number of calls received per minute at a Help Desk has been estimated to be between 5 and 10.
Write a simulation program that simulates calls arriving at the Help Desk for a period of 12 hours and output the frequency of calls during this period.
Sample output:
(Note: The frequencies for your program will be different from the ones shown below. Each time you run your program, you should get different frequencies)
Calls/Minute Frequency
5 155
6 172
7 148
8 123
9 62
10 60
This is what I've came up with, but cannot figure out how to split/leave a gap between calls/minute and frequency. Basically splitting it into two rows.
import java.util.Random;
public class randomCalls {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rn = new Random();
int n;
for(int i=1;i<=6;i++)
{
n = rn.nextInt(6) +5;
System.out.println("Calls/Minute" +"\n" + n);
System.out.print(' ');
System.out.println(" Frequency" + "\n"+ i);
}
}
}
I'm pretty sure you are trying to print out Calls/Minute and Frequency in columns. Here is a helpful link.
In order to use that method your need to...
Combine the lines System.out.println("Calls/Minute" +"\n" + n); and System.out.println(" Frequency" + "\n"+ i);, and format the resulting single line so that it is split into two columns.
//Example
System.out.printf("%-12.30s %-30.30s%n","Column 1","Column 2");
Place it BEFORE your for loop (or else it will print every time)
Within your for loop, format your output exactly the same as you did the line in step one.
//Example
System.out.printf("%-12.30s %-30.30s%n",n,i);
Sample output in your program would look like this:
Calls/Minute Frequency
6 1
7 2
8 3
8 4
9 5
6 6
Here is how I got it to print like described:
Random rn = new Random();
int n;
for(int i=1;i<=6;i++) {
n = rn.nextInt(6) +5;
System.out.println( n + " " + i );
Hope this helps!

PrintWriter creates file but doesn't print to file

This is a college course assignment that consists of classes TotalSales and TotalSalesTest.In the main program I have created a two dimensional array to output a columnar layout with cross-totals in 4 rows and 5 columns. This program outputs sales totals by row for each sales person(1 - 4) and output by column for products(1 - 5). I have created extra elements in the array to store total for rows and columns. So far both classes compiles. The problem is that although the PrintWriter creates a notepad file, it doesn't print to it. I could use some help on this problem. Here is the code`
//write program in a two diminsional array to output a columnar layout with cross-totals in 4 rows and 5 columns
//program outputs sales totals by row for each sales person(1 - 4) and output by column for products(1 - 5)
//create extra elements to store total for rows and columns
import java.util.Scanner;
import java.io.*;
public class TotalSales
{
private int salesPerson; //declare class variable
private int productNumber;//declare class variable
private double totalSales;//declare class variable
private double allSales;
//declare input and output variables
Scanner inFile; //declare inFile variable
PrintWriter outFile;//declare outFile variable
double[][]sales = new double[6][7];//declare array sales
public void initializer()
{
try
{
inFile = new Scanner( new File( "assign06.txt" ) );
outFile = new PrintWriter( "MonthlyTotalSales.txt" );
outFile.flush();
}
catch (FileNotFoundException e)
{
System.out.println("The input file could not be found!");
System.exit(1);
}
while(inFile.hasNext()) //while there is data to process…
{
salesPerson = inFile.nextInt();//reads salesPerson
productNumber = inFile.nextInt();//reads productNumber
totalSales = inFile.nextDouble();//reads totalSales
sales[salesPerson][productNumber]+=totalSales;
sales[salesPerson][6]+=totalSales;
sales[5][productNumber]+=totalSales;
allSales += totalSales;
} //end while loop
printDetails(sales);//call method printDetails
finishUp();//call method finishUp
}//end initializer
public void printDetails(double[][] array)
{
outFile.println("\t1\t2\t3\t4\t5");
for (int salesPerson =1; salesPerson <5; salesPerson++)
{
outFile.print(salesPerson+ " ");
for(int productNumber=1; productNumber <=array.length; productNumber++)
outFile.print(array[salesPerson][productNumber]+" ");
//end inside loop
outFile.println();
}//end outside loop
outFile.print("Total: \t ");
for(int salesTotal=1; salesTotal<array.length; salesTotal++)
{
outFile.print(array[5][salesTotal] +" ");
}
outFile.print(allSales);
outFile.println();
outFile.print(" ");
outFile.println();
}//end printDetails
public void finishUp()
{
inFile.close();
outFile.close();
System.out.println("The program has finished.");
}//end finishUp
}//end class TotalSales
Here is the test program:
public class TotalSalesTest
{
public static void main(String[] args)
{
TotalSales ts = new TotalSales();
ts.initializer();
}//end method main
}
Here is the text file for the input:
1 1 37.50
1 2 77.00
1 3 68.75
1 4 61.25
1 5 175.00
2 1 45.00
2 2 66.00
2 3 27.50
2 4 49.00
2 5 250.00
3 1 67.50
3 2 33.00
3 4 73.50
3 5 200.00
4 1 15.00
4 2 99.00
4 3 123.75
4 4 85.75
4 5 125.00
1 1 60.00
1 2 88.00
1 3 41.25
1 4 49.00
1 5 225.00
2 1 67.50
2 2 33.00
2 3 27.50
2 4 122.50
2 5 25.00
3 1 60.00
3 2 44.00
3 3 96.25
3 4 36.75
3 5 50.00
4 1 75.00
4 2 11.00
4 3 41.25
4 4 98.00
4 5 125.00
1 1 45.00
1 2 33.00
1 3 27.50
1 4 61.25
1 5 200.00
2 1 52.50
2 2 22.00
2 3 13.75
2 4 36.75
2 5 50.00
3 1 37.50
3 2 88.00
3 3 96.25
3 4 36.75
4 1 37.50
4 2 77.00
4 3 82.50
4 4 73.50
4 5 25.00
1 1 30.00
1 2 88.00
1 3 41.25
1 4 12.25
1 5 175.00
2 1 45.00
2 2 22.00
2 3 68.75
2 4 98.00
3 2 88.00
3 3 41.25
3 4 24.50
4 1 30.00
4 2 88.00
4 3 82.50
4 4 122.50
4 5 175.00
You call printDetails before initializing the writer... Move the printDetails call after outFile = new PrintWriter( "MonthlyTotalSales.txt" );and it should be fine. However, you should have included your constructor since as it is right now, I would think your code throws a NullPointerException because the writer is never initialized. You also need to close the file before writing in it, or at least you need to flush.
The whole structure of your code is bad, you should never have a method such as mainProgram on a class, you should never use a file as an attribute just to use it in every method, and you should never separate in different methods creation and closing of i/o classes.
It seems you didn't call outFile.close();
Call your finishUp() method once you complete writing in the file.
I think your program crashes with a nullpointer on
inFile.hasNext()
because you never actually opened or even instantiated the input file along with the output file in the try/catch block. Whoops!
change
try
{
outFile = new PrintWriter( "MonthlyTotalSales.txt" );
}
to
try
{
inFile = new Scanner(new File("Input.txt"));
outFile = new PrintWriter( "MonthlyTotalSales.txt" );
}

String thread safety because of immutability?

Hi was reading about that a string is thread safe because it is immutable.
For example i do:
String a = "test";
One thread uses this variable.
But another thread could still also use this variable and change it:
a = a + "something";
So it would change or not?
If it would be volatile, i would get it, that it can just be used by one thread at a time. But immutabilty doesnt guarantee me this!?
You're not changing the object pointed by a, but where a points to:
String a = "test";
here a points to a string "test"
a = a + "something";
here a new string is created as the result of the concatenation of "test" and "something", which "testsomething" where a points to. It's a different instance.
So there is no problem of thread safety, as both threads will have their own a referring to the same "test" string object, but once one of those thread will modify the string to be referring the "testsomething" object, the other Thread will still be referring the original "test" object.
The String itself isn't changing, the reference is. It sounds like you need the reference to be final. Immutability guarantees that the Object does not change, not that the reference cannot change. Just mark it like this:
final String a = "test";
You can make the code thread safe trivially by having each thread copy the reference a. In fact, that’s normally what happens anyway, since you usually pass the string to the thread via a parameter.
So both threads hold a reference to the original string, here "test". If thread 1 now modifies a it only modifies this reference. Thread 2 still retains an intact reference to "test" because the string itself (rather than the reference) is immutable.
Strings objects are thread-safe. If your String a is a local variable then this code is still thread-safe. If it is a field of your class than it is your responsibility to guarantee its thread-safety. Thread-safety of String won't magically make your own code thread-safe. You should take care about it.
You can make field volatile then you get visibility among threads. So any thread will see up-to-date value of your field. But you won't get atomicity in this way. Imagine the following. Let a = "test". Thread 1 updates a and thread 2 updates a. They both see current value which is "test". They read it, make new strings by concatenation and update value of a. And what will be that value? It is unknown. It can be "testsomethingsomething" if threads perform their operations strictly one after another. But it can be just "testsomething". For instance:
thread 1 read "test" from a
thread 2 read "test" from a
thread 2 updates a with "testsomething"
thread 1 updates a (remember, it read a as "test" before) with the same "testsomething"
Voila, you've lost an update to your field. To avoid this kind of problem, you should guard all accesses and modifications to your field with synchronization on single lock object.
A lot of confusion here...
What thread safety of some class means is that concurrent use of it's instance
will not destroy it's internal structure.
In our case it is just a warranty that we finally get a "testsomething", but not a mess like
"tsomethingest" or "tesomethingst" or "tseosmtething" or "somethingtest".
Here a "quick and dirty" illustration:
public class Test2 {
private volatile String tstStr = "";
Test2(){
}
void impl(int par){
Thread wrk = new Thread(new MyRun(par));
wrk.start();
}
static public void main(String[] args) throws Exception {
Test2 tst2 = new Test2();
long startTime = System.currentTimeMillis();
Thread wrk;
for (int i = 0; i < 9; i=i+1) {
tst2.impl(i);
}
long endTime = System.currentTimeMillis();
System.out.println("The process took " + (endTime - startTime) + " milliseconds");
}
class MyRun implements Runnable {
int no;
MyRun(int var){
no = var;
}
public void run(){
tstStr = tstStr + " " + no;
for (int i = 0; i < 3; i=i+1) {
System.out.println("Message from "+no+", tested string ="+tstStr);
}
}
}
}
The output:
Message from 1, tested string = 0
Message from 1, tested string = 0 2 3
Message from 1, tested string = 0 2 3
Message from 4, tested string = 0 2 3 4
Message from 4, tested string = 0 2 3 4
Message from 0, tested string = 0 2
Message from 8, tested string = 0 2 3 4 7 8
Message from 5, tested string = 0 2 3 4 7 8 5
Message from 0, tested string = 0 2 3 4 7 8 5
Message from 0, tested string = 0 2 3 4 7 8 5
The process took 0 milliseconds
Message from 7, tested string = 0 2 3 4 7
Message from 7, tested string = 0 2 3 4 7 8 5 6
Message from 4, tested string = 0 2 3 4
Message from 3, tested string = 0 2 3
Message from 2, tested string = 0 2
Message from 3, tested string = 0 2 3 4 7 8 5 6
Message from 7, tested string = 0 2 3 4 7 8 5 6
Message from 6, tested string = 0 2 3 4 7 8 5 6
Message from 5, tested string = 0 2 3 4 7 8 5
Message from 8, tested string = 0 2 3 4 7 8 5
Message from 5, tested string = 0 2 3 4 7 8 5 6
Message from 6, tested string = 0 2 3 4 7 8 5 6
Message from 3, tested string = 0 2 3 4 7 8 5 6
Message from 2, tested string = 0 2 3 4 7 8 5 6
Message from 6, tested string = 0 2 3 4 7 8 5 6
Message from 8, tested string = 0 2 3 4 7 8 5 6
Message from 2, tested string = 0 2 3 4 7 8 5 6

I am trying to create an array using data from a file

This is what I have so far....
/**
* #param args
*/
public static void main(String[] args) {
final String DATA_FILE = "payroll_problem.txt";
Scanner scan = null;
try
{
scan = new Scanner(new File(DATA_FILE));
}
catch (FileNotFoundException e)
{
System.err.printf("Could not open file \"%s\".\n", DATA_FILE);
}
int [] arr = new int[scan.nextInt()];
for(int i = 0; i < arr.length; i++)
{
arr[i] = scan.nextInt();
System.out.print(arr[i]);
}
scan.close();
}
I keep getting error code
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at fvse.main(fvse.java:22)
The five ints stand for how many hours the person has worked from Monday-Friday. Here is the data file.
Mohnan Maria 8 8 8 9 8 10.01
Blue Shelly 8 10 8 8 6 10.00
Black 8 8 8 8 8 23.0
Fortuna Jorge 5 5 5 5 5 10.10
Jones Mitchel 10 5.5 10 10 10 15.05
Olafson Sven 10 10 10 10 10 10.00
Cruz Astrid 1 1 1 1 1 20.50.3
Adler Irene 10 12 8 8 8 22.50
The problem happen because you call scan.nextInt() but your input file actually contains string/characters.
Either add the integer indicating the number of lines on the top of your input file, or change your code read by line (eg: using BufferredReader.readLine())
If you choose the former, make sure you also read the first and last name using two invocation of scan.next()
You are reading your file for integers, but more than likely that file is filled with strings or characters.
Edit: Try scanning for lines or characters, or just using a FileInputStream, and then parsing the data once it's been loaded in.
Edit: Now that i've seen your data file, I would read in the file using standard file input practices (check out http://www.javapractices.com/topic/TopicAction.do?Id=42 if you need a tutorial on that). Then split the string based on spaces, and go through each string in your new string array and handle the data. The first 2 strings being names, and then integers until you get another name, or the end of the string.

Categories

Resources