empty output + errors if i move the .println line anywhere else - java

i have to do a student averages program and i can't get the output to print out. if i move the .println line outside of the while loop, i get "cannot find symbol" errors.
i think it might not be printing because i already read the file once, and i'm trying to read it again to figure out the averages. how can i make this work?
contents of my file:
Agnes 56 82 95 100 68 52
Bufford 87 92 97 100 96 85 93 77 98 86
Julie 99 100 100 89 96 100 92 99 68
Alice 40 36 85 16 0 22 72
Bobby 100 98 92 86 88
import java.util.*;
import java.io.*;
public class EZD_studentAvgs
{
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_gradebook.txt"));
int max = -1;
String fr[] = new String[100];
System.out.println("The input file:\n");
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
System.out.println(fr[max]);
}
//System.out.println("max: " + max);
System.out.println("");
System.out.println("\nThe output:\n");
while(sf.hasNextLine())
{
Scanner ga = new Scanner(sf.nextLine());
String student = ga.next();
double sum = 0;
int count = 0;
while(ga.hasNextInt())
{
sum = sum + sf.nextInt();
count++;
}
System.out.println(student + ", average: " + (sum/count));
}
sf.close();
}
}

You read the lines into fr until sf.hasNext() returns false. You never reset sf, so it would be logical to think that, when you reach sf.hasNextLine(), it will be false also.
Instead of reading the lines again, just run scans on the strings you've already read in; in other words, it looks like you can loop through the strings in fr from 0 to max in place of the loop currently based on sf.hasNextLine().

Related

How do I count the frequency of an item in a given range?

I've been given a lab where I'm supposed to create a program that reads a file with 1000 random integers between 10 to 59 inclusive and generate a frequency table like this:
The ranges are 10 to 19, 20 to 29, 30 to 39, 40 to 49, and 50 to 59.
Here is a sample from the RandomInt.txt:
50
11
55
12
20
13
53
34
19
39
58
58
24
59
28
10
52
18
55
59
28
29
54
I've been successful at reading all the integers in a file, but for some reason my result for the frequency part is just 1 for every category. How do I put each integer in a range and count them all together within that range?
So far, here is my updated code that counts the frequency of each integer:
import java.io.*;
import java.util.*;
public class Demo3
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("RandomInt.txt");
Scanner sc = new Scanner(file);
SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>();
int dataSet = 0;
while(sc.hasNext())
{
String key = sc.next();
dataSet++;
if(st.contains(key))
{
st.put(key, st.get(key) + 1);
}
else
{
st.put(key, 1);
}
}
for (String s : st.keys())
{
System.out.println("Integer: " + s + " Frequency: " + st.get(s));
}
System.out.println("Data Set Size: " + dataSet);
}
}
As #user16320675 says, you should probably do something numeric with arrays. See the following as a fairly kludgy fix as the use of strings for something essentially numeric is not really appropriate. Instead of just st.contains(key) you could call st.contains(keyInRange(key)) - the following:
public static String keyInRange(String key) {
final String[] RANGES = {
"",
"10 to 19",
"20 to 29",
"30 to 39",
"40 to 49",
"50 to 59"
};
return RANGES[Integer.parseInt(key) / 10];
}
but beware, because you're currently putting in all ranges irrespective of key for some reason.

How to make an input ( 84 23 75 24) into an array?

I won't have any code to put here since this is the start of it. But I would be asking for the input of numbers that will be inputted like this "75 69 35 95 90 45 66"
What do I do with the input to turn it into an array, I know how to scan it and turn it into string but that's about it.
If the input is a proper integer.
Scanner in = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while(in.hasNextInt()) {
arrayList.add(in.nextInt());
}
System.out.println(arrayList);
If the input is a string
String str[] = "75 69 35 95 90 45 66".split(" ");
int len = str.length;
int numbers[] = new int[len];
int index = 0;
while(len > 0) {
try {
numbers[index] = Integer.parseInt(str[index]);
} catch (NumberFormatException e) {
// something to do
}
System.out.println(numbers[index]);
index++;
len--;
}
Here is sample code that makes "explode" the string. Each item is then converted to integer.
List<Integer> l = new ArrayList<Integer>();
String[] ss = "75 69 35 95 90 45 66".split(" ");
for (String s: ss) {
l.add(Integer.valueOf(s));
}
System.out.println(l);

java.lang.NumberFormatException: For Input string "" - When using scanner to read txt file

I have a problem where I need to implement Dijkstra's algorithm for Single Source Shortest Path Problem with Binary Heaps. The running time should be O(ElogV).
Here is the code for reading in from a scanner:
try {
Scanner sc = new Scanner(new File("../SOME_TEXT_FILE.txt"));
String line = sc.nextLine();
String[] ne = line.split(" ");
nodes = Integer.parseInt(ne[0].split("=")[1]);
edges = Integer.parseInt(ne[1].split("=")[1]);
constructGraph(sc);
The issue happens when the constructGraph(sc) method is called.
Here's that method:
static void constructGraph(Scanner sc) {
adjList = new ArrayList[nodes];
for (int i = 0; i < nodes; i++)
adjList[i] = new ArrayList<>();
for (int i = 0; i < nodes && sc.hasNext(); i++) {
String edge;
String n = sc.nextLine();
while (sc.hasNext() && !(edge = sc.nextLine()).isEmpty()) {
String[] e = edge.trim().split(" ");
int from, to, weight;
to = Integer.parseInt(e[0]);
weight = Integer.parseInt(e[1].trim());
adjList[Integer.parseInt(n)].add(new Edge(to, weight));
adjList[to].add(new Edge(Integer.parseInt(n), weight));
}
}
}
The error tells me that the issue is in the line that says
weight = Integer.parseInt(e[1].trim());
Here is a sample of the input coming from the text file:
n=1000 m=8544
0
25 244
108 275
140 273
159 313
1
24 187
43 182
65 331
155 369
182 222
2
31 504
35 403
176 249
229 68
Because there are multiple spaces between the two numbers you have to split using a different regex
String[] e = edge.trim().split("\\s+");
Splitting "1 2" using split(" ") will produce an array of size 3 with values ["1", "", "2"] where the middle element is the empty string delimited by the left and right space character. Using \\s+ you are saying that you want to split sequences separated by a sequence of whitespace characters.

Receive file name from user and assign each number in the file to a separate array

I'm simply just trying to receive the file name from user input then go through the file and assign each number in the file to their assigned array then print it out. I am also suppose to read the first line to know how many students/lines there are to read then.
import java.util.*;
import java.io.*;
import java.text.*;
public class A7LakshmanaSilva {
public static void main(String[] args)throws IOException {
DecimalFormat df = new DecimalFormat ("#.#");
Scanner scan = new Scanner(System.in);
final String chartSize = "%-11s%-12s%-11s%-12s%-13s";
int sum1=0;
int sum2=0;
int i=0;
int[] students;
double [] mterm, finale, grades;
System.out.print("Input file name: ");
String inFile=scan.nextLine().trim();
File myfile = new File(inFile);
Scanner input= new Scanner(myfile);
int n= input.nextInt(); //total students in class
students = new int[n+1]; //student code
mterm= new double[n+1]; //midterm grade
finale= new double[n+1]; //final grade
grades = new double[5]; //letter grade counter(irrelevant in this question though)
System.out.println(String.format(chartSize,"Student","Midterm","Grade","Final","Grade"));
System.out.println("-----------------------------------------------------------------");
if (input.hasNextLine()) {
//String line= input.next(); //been testing with this
//Scanner linescan= new Scanner(line);
students[i]=input.nextInt();
mterm[i]=input.nextDouble();
finale[i]=input.nextDouble();
++i;
}
for(int j=0;j<n;j++) {
System.out.println(String.format(chartSize,students[i],mterm[i]," ",finale[i],"Grade"));
}
}
I should be getting the values from the file but instead I'm just getting 0 every line.
The file(grades.txt) :
25
000001 82 80
000002 76 71
000003 90 86
000004 68 71
000005 70 81
000006 68 59
000007 92 94
000008 85 79
000009 72 71
000010 79 91
000011 69 61
000012 55 58
000013 59 62
000014 87 81
000015 90 82
000016 77 74
000017 81 73
000018 95 89
000019 75 75
000020 72 81
000021 89 88
000022 94 94
000023 78 72
000024 65 67
000025 78 69
I believe that you're errors are twofold.
Firstly, you did not properly load the arrays:
if (input.hasNextLine()) //If statement does not iterate
{ //Unfilled arrays are likely filled with the default '0' value.
students[i]=input.nextInt();
mterm[i]=input.nextDouble();
finale[i]=input.nextDouble();
++i;
}
Should Be:
while(input.hasNextLine()) //While Loop iterate through the file.
{
students[i]=input.nextInt();
mterm[i]=input.nextDouble();
finale[i]=input.nextDouble();
++i;
}
Secondly, you're using i instead of j in your print loop
for(int j=0;j<n;j++) {
System.out.println(String.format(chartSize,students[i],mterm[i]," ",finale[i],"Grade"));
}
Should Be:
for(int j=0;j<n;j++) {
System.out.println(String.format(chartSize,students[j],mterm[j]," ",finale[j],"Grade"));
}

Scanning in contents of a file

I have a file that has the following content:
5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47
With the a blank line between each of the names and numbers. However when I scan the file using the the nextLine(); method I get the following:
NAME:
NAME:
NAME: Derrick Rose
NAME:
NAME: 1 15 19 26 33 46
NAME:
NAME: Kobe Bryant
NAME:
NAME: 17 19 33 34 46 47
NAME:
Can someone tell me where in my code the problem is occurring and why it is scanning in blank lines.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++)
{
String name = scan.nextLine();
System.out.println("NAME: " + name);
}
It seems you want to ignore the empty lines, you could just check the length of the line you're about to write to the console. It's not possible to not scan empty lines, you need to at least skip them to dive further into your stream.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++) {
String name = scan.nextLine();
if (name.trim().length() > 0)
System.out.println("NAME: " + name);
}
If you have a newline in your input, then that will consume one call to scan.NextLine(), since that function delimits on newlines. If you want it to ignore blank lines then you should explicitly check for them and then explicitly increment your counter if the lines are not blank.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); )
{
String name = scan.nextLine();
if (!name.trim().equals("")) i++;
System.out.println("NAME: " + name);
}
You could check for blank lines and ignore them. The code below should do this.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++)
{
String name = scan.nextLine();
if (!name.equals("")){
System.out.println("NAME: " + name);
}
}
The below class ExcludeEmptyLines.java worked
package com.stackoverflow.java.scannertest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Created by fixworld.net on 03-September-2015.
*/
public class ExcludeEmptyLines {
public static void main(final String[] args)
throws FileNotFoundException {
String dataFileFullPath = "<replace with full path to input file>";
File inputFile = new File(dataFileFullPath);
Scanner scan = new Scanner(inputFile);
int numEntries = scan.nextInt();
System.out.println("NumEntries = " + numEntries);
for(int i = 0; i <= (numEntries * 4); i++)
{
String inputLine = scan.nextLine();
if(!inputLine.trim().equalsIgnoreCase("")) {
System.out.println("inputLine = " + inputLine);
}
}
}
}
Output from running it is
NumEntries = 5
inputLine = Derrick Rose
inputLine = 1 15 19 26 33 46
inputLine = Kobe Bryant
inputLine = 17 19 33 34 46 47
inputLine = Pau Gasol
inputLine = 1 4 9 16 25 36
inputLine = Kevin Durant
inputLine = 17 19 34 46 47 48
inputLine = LeBron James
inputLine = 5 10 17 19 34 47

Categories