I'm want to read in from a file and then split it into separate parts and then access it and print it out. I know i can't do it the way it looks now. Please reply asap. The object of the program is to read in from a file points where i split it into x and y values, then sort these values according to there polar_order(this i have figured out) i just want to print out the values for testing.
Thanks
public static void main(String[] args){
int count = 0;
Scanner read = new Scanner(System.in);
int N = read.nextInt();
while(read.hasNext()){
String nN = read.nextLine();
String[]cord = nN.split(" ");
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
count++;
}
read.close();
for(int i = 0; i<N;i++){
System.out.print(x[i]);
}
Hope you are trying to print the contents of the string array 'cord'.
Try this code:
string dataToPrint = string.Join(" ", cord);
Not sure how you've structured your file but if you want to read in a file, here's an indication of how you might do that. Replace the while method with the method you need to extract the x, y values... you should probably apply Nist's answer to do so (use an ArrayList).
try {
Scanner s = new Scanner(new File("your file path"));
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
s.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
I've found the easiest way to print the contents of an array (assuming it's not null) is this:
System.out.println(Arrays.toString(array));
For some odd reason, most of the list classes give nice output:
[1, 2, 3]
whereas arrays gives you a type/address indicator:
[Ljava.lang.String;#10b62c9
I've never quite understood why they didn't do something so that arrays had nicer output without having to call some utility function.
Related
Hi everyone this is my first question here so I apologize in advance if it is not in the correct format for this forum. I'm a comp sci student and I am really a novice programmer. For an assignment, I need to read in a file of polynomials and then sort them from highest degree to lowest. On each line of the file I have a coefficient and an exponent separated by a space.
This is what my .txt file looks like:
"5.6 3
4 1
8.3 0" which represents the polynomial 5.6x^3 + 4x + 8.3
I have to scan the file from a JFileChooser and then add the tokens to an ArrayList of type Polynomial. My question/problem is how can I run the file contents through a for loop and separate the first token(coefficients) from the second token(exponents) and then add them to the ArrayList? I'm going to need the exponents to be of type int and the coefficients should be double.
This is what I have so far:
ArrayList aList = new ArrayList();
// scanner used to read each line
try {
scan = new Scanner(file);
if (file.isFile()) {
while (scan.hasNext()) {
for (int i = 0; i < something.size(); i++) {
//this is where I'm lost, not sure what I need to do here
}
}
}
....
Thank you guys I appreciate the assistance.
-Linden
EDIT:
Alright I figured it out, it was a lot more complicated than I thought. Here's what I did:
Scanner scan = new Scanner(file);
if (file.isFile()) {
for (int i = 0; i <=2; i ++) {
term(scan);
}
}
static void term(Scanner scan) {
String s = scan.nextLine();
String [] splitter = s.split(" ");
String coefficient = splitter[0];
String exponent = splitter[1];
//populating
try {
arrayList.add(new Polynomial(coefficient, exponent));
} catch (InvalidPolynomialSyntax e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks to the two guys that tried to help me out and the 24 viewers who didn't lol
First, you need to look at the scanner class. What methods does it have that you should use to get the data you need?
I don't want to give you the answer to your homework out of respect but broadly what you need is a way to get each line of that file from the scanner so you can compare the contents of each line to each other.
So look at the scanner class documentation and see what it has that you can use.
Start by simply trying to print out each line. Once you do that you can think about how you want to compare them.
you can read file as one sentence. First get all the text such as 5.6 3 4 1 8.3 0 as string. Then you can just use String [] arrayOfNumbers = yourString.split(" ");
This will split the string according to " " character so you get numbers directly.
i have a text file and i want to read the integers and doubles. I dont know how many values i have to read. The first value in the line is always the integer and the second is always the double. I want to save the value of the first line seperately.
200
11010 0.004
500 0.02
637 0.018
How to create 2 arrays and save the values, so i can use them later? I am not allowed to create a new class. I tried to use Point but cant store doubles.
Scanner scanner = new Scanner(new File(args[0]));
int cores= scanner.nextInt();
System.out.print(cores);
while (scanner.hasNext()) {
int x = scanner.nextInt();
double y = scanner.nextDouble();
System.out.printf("x");}
I' ve tried the code above but throws out Exception
You can use simple file handling approach to read the file line by line, For the first line you can use a flag to mark the line and sent the file to remote location you want to save the data. Then for all later lines you can split the string on the basis of " " (space). Post which once you have stripped the elements of the resulting array you can typecast and append the element at first index to integer array. And the second element (typecast before append) to the double array. This shall work absolutely fine with any length of file.
A demo code for the same is as following:
public class ReadLineByLine
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis);
String tempLineData = "";
int flag = 0;
String[] elements;
List<Integer> ints = new ArrayList<Integer>(
List<Float> floats = new ArrayList<Float>(
while(sc.hasNextLine())
{
if(flag == 0){
// Place the operation with the first line here
flag++;
}
tempLineData=sc.nextLine();
elements = tempLineData.split(" ");
ints.add((int)elements[0].trim());
floats.add((float)elements[1].trim());
}
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.
I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.
The code I have writen is as follows
public static void main(String[] args) throws IOException{
Scanner Input = new Scanner(new File("newestcode.txt"));
Integer[] digits = new Integer[100];
int h = 0;
while(true){
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}
}
in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day
try {
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}catch (NoSuchElementException e){
break;
}
First of all, if you're not sure about amount of ints in your file, don't try to store them into fixed-size array. Use ArrayList instead.
Also don't use endless loop while(true) but consider using Input.hasNext() to check if there still is something to read from file.
And one more. You're trying to print value after increment. This means that you're adding element on 0 position but trying to read it from 1 position. Make increment on the end of the loop.
Scanner Input = new Scanner(new File("newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while(Input.hasNetxt()){
digits.add(h, Input.nextInt());
System.out.println(digits.get(h));
h++;
}
You should use the input.hasNext() method to check whether the input has any more 'int' before using it.
In order to support any length of int elements, you cannot set the array to a fixed length of 100, you need to use an ArrayList to add elements dynamically.
Scanner input = new Scanner(new File("./newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while (input.hasNext()) {
digits.add(h, input.nextInt());
System.out.println(digits.get(h));
h++;
}
Note: You need to print digits[h] before increasing the h.
I am working on a class assignment where we can only use arrays and no Collection classes to read a text file and fill an array with information from the text file. the file ArrayData.txt is the information bellow.
The file is formatted in this way:
3 //First line states how many sets are in the file
2 //Next line:there are x numbers in the set
10.22 567.98 //Next Line states the doubles that are in the set
//The pattern continues from there
1 // x numbers in the next set
20.55 // Double in the set
3
20.55 2.34 100.97
My issue is filling the initial array with an array, then filling the second array with the doubles.
Essentially, I want it to look like this:
initArray[0]=> smallArray[2]={10.22,5.67.98}
initArray[1]=> smallArray[1]={20.55}
initArray[2]=> smallArray[3]={20.55,2.34,100.97}
Here is what I have so far:
public static double[] largeArray;
public static double[] insideArray;
public static void main(String[] args) {
String fileInputName = "ArrayData.txt";
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
while (sc.hasNextLine()) {
int i = sc.nextInt();
largeArray= new double[i];
for(int x=0; x<i;x++)
{
int z = sc.nextInt();
insideArray= new double[z];
for(int y=0; y<z; y++)
{
insideArray[z]=sc.nextDouble();
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (sc != null)
sc.close();
}
}
First off, does this logic even make sense? Secondly, I keep getting an array out of bounds error, so I know something is right, I'm just not sure where.
Remove the while. You want the body to execute only once. Line breaks at the end of the file may cause it to run again and then there will be no nextInt(). If you want to support empty files, make it an if.
Secondly, insideArray[z] = ... should be insideArray[y] = ...
Finally, largeArray should be an array of arrays double[][] (a so called jagged array) and you want to assign insideArray to the according place after filling it.
In my class we're using methods to calculate data from a text file. If I had a file that looked exactly like this:
Bob
25
Molly
30
Dylan
10
Mike
65
Is there anyway to pull this data from a file and then send it to a method to calculate, and then return that calculation to display on main? I'm confused as to how Java would be able to skip each line and calculate the numbers instead of the persons name. I was thinking about using inputFile.nextDouble(); and inputFile.nextLine();. But how would I be able to set a String read the lines in the text file if I'm supposed to readthose text file lines variables as doubles? Sorry for all of the questions, I've been stuck on this for a long time and it's driving me crazy >.
You should just alternately use nextLine() and nextInt()
Scanner sc=new Scanner(new File(/* Path to the file*/));
int i=0;
while(sc.hasNext())
{
if(i==0)
{
name=sc.nextLine();
}
else
{
number=sc.nextInt();
}
i=1-i;
}
I recommend you to use an ArrayList to read the full file:
Scanner s = new Scanner(new File(//Here the path of your file));
int number;
String name;
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now you have all the lines of your file (as a String) so now you can operate with the full data that it's inside.
Further, the numbers are in the even lines so you can use a loop to through all the lines and check if the line that you are using now it's even or not.
for(int i = 0; i < list.size(); i++)
{
if(i%2 == 0)
{
number = Integer.parseInt(list.get(i));
//You can use the references to your methods with this number
}
else
{
name = list.get(i);
}
}
With the % you will get the rest of the division (I'm using a property of pairs numbers). With Integer.parseInt you will parse your String to int.
So now you will be able to use this numbers to operate or whatever you want.
EDIT: Here you have an example without using ArrayList. In this case I'm going to use nextLine() and nextInt() functions:
Scanner s = new Scanner(new File(//Here the path of your file));
int count = 0;
int number;
int name;
while(s.hasNext())
{
if(i%2 == 0)
{
number = s.nextInt();
s.nextLine();
//You can use the references to your methods with this number
}
else
{
name = s.nextLine();
}
count = count + 1;
}
If you have doubts about why I'm using s.nextLine() after number without storing any value you can look my answer to this question: Why isn't the scanner input working?
I expect it will be helpful for you!