My Issue is that this code does not return and values when I call it.
I need to to read a set of values from another txt file and print out the answers.
Then I need to be able to have it print to another empty text file.
The values in the txt file is (without space in-between lines):
1 2 3 4 5 6
4 5 6
7.5 8.5 9
8.1 9.2 10.3
The source code as follows:
public class Lab5d {
public static void main(String args[]) {
// Scan the input
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
// Process each line separately
// If the next token is a double, assume there is an input line
while (scan.hasNextDouble()) {
processLine(line);
}
}
public static void processLine(String line) {
Scanner scan = new Scanner(System.in);
Scanner lineScan = new Scanner(line);
double a = lineScan.nextDouble();
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
product = 1;
while (lineScan.hasNext()) {
sum = sum + a;
product = product * a;
++count;
}
double ave = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, ave, count);
}
}
Can anyone help?
You're not reading the file in. Use the file path as a parameter for the Scanner object.
It can be two cases, you can either read values from a file or values from a command line.
First a main method look:
public static void main(String args[]) {
// Scan the input
processSystemIn();
// San the file
processFile("resource/values.txt");
}
The values.txt is following the format you presented in your question.
And read a value line by line using a hasNextLine method of a Scanner class then, use an another scanner instance for the each number from the line input.
case 1: A processSystemIn method with System.in
private static void processSystemIn() {
Scanner scanner = new Scanner(System.in);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
}
case 2: A processFile method with file.
private static void processFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The processLine method is a little bit different with yours.
With a hasNextDouble method, you can get a value.
See the method as follows:
public static void processLine(String line) {
Scanner lineScan = new Scanner(line);
double a;;
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
while(lineScan.hasNextDouble())
{
a = lineScan.nextDouble();
product = 1;
sum += a;
product *= a;
++count;
average = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, average, count);
}
lineScan.close();
}
The result is here:
Does this result meet your expectation?
I hope this helps.
Related
So this is my code, and i want to print out a new line saying what the average number of letters used. And i also want to print the longest name written in.. but i cant make it work.. Any suggestions??
import java.util.*;
import java.util.stream.Collectors;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Write some names. When you are finished write <Avslutt>! :)");
ArrayList<String> names = new ArrayList<String>();
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if ("avslutt".equalsIgnoreCase(input)) {
Collections.sort(names);
System.out.println("Here is the result (Alphabetical): " + names);
break;
} else {
names.add(input);
}
}
}
}
You can loop over the input while not empty line, then add to the list and sum the amount to calculate the average.
For sorting the list using Comparater.comparing by string length
public static void main(String[] a) {
Scanner scanner = new Scanner(System.in);
System.out.print("Write some names. When you are finished write <Avslutt>! :)");
List<String> names = new ArrayList<String>();
int amount = 0;
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if ("".equals(input)) {
break;
} else {
names.add(input);
amount += input.length();
}
}
double avg = amount / names.size();
Collections.sort(names, Comparator.comparing(n -> n.length()));
System.out.println("Longest name: " + names.get(names.size() - 1));
System.out.println("Average letter used: + avg);
scanner.close();
}
so i just fixed an error then following that i got the exception error and not sure what to change to fix it.
i've looked at similar issues but none of them seemed to pertain to my specific problem.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class AAAAAA {
public static void main (String[] args)throws IOException {
final String fileName = "classQuizzes.txt";
//1)
Scanner sc = new Scanner(new File(fileName));
//declarations
String input;
double total = 0;
double num = 0;
double count = 0;
double average = 0;
String lastname;
String firstname;
double minimum;
double max;
//2) process rows
while (sc.hasNextLine()) {
input = sc.nextLine();
System.out.println(input);
//find total
total += Double.parseDouble(input); //compile error on using input
count++;
System.out.println(count); //test delete later
//find average (decimal 2 points)
System.out.println("hi"); //test
average = (double)total / count;
System.out.println("Average = " + average);
//3) class statistics
}
}
}
It's actually a runtime exception not a compile error.
The reason is because your Scanner is reading through the whole file, line by line, and is hitting something that cannot be parsed as a double.
// for each line in the file
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
// split the line into pieces of data separated by the spaces
String[] data = line.split();
String firstName = null;
String lastName = null;
// get the name from data[]
// if the array length is greater than or equal to 1
// then it's safe to try to get something from the 1st index (0)
if(data.length >= 1)
firstName = data[0];
if(data.length >= 2)
lastName = data[1];
// what is the meaning of the numbers?
// get numbers
Double d1 = null;
if(data.length >= 3){
try {
d1 = Double.valueOf(data[2]);
} catch (NumberFormatException e){
// couldn't parse the 3rd piece of data into a double
}
}
Double d2 = null;
// do the same...
// do something with 'firstName', 'lastName', and your numbers ...
}
I want to be able to separate a String of two numbers and then add them together, but I keep getting the int value of each character. If I enter "55" as a string I want the answer to be 10. How can I do that?
package org.eclipse.wb.swt;
import java.util.*;
public class ISBN13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("enter a string");
String numbers = input.nextLine(); //String would be 55
int num1=numbers.charAt(0); //5
int num2=numbers.charAt(1); //5
System.out.println(num1+num2); //the answer should be 10
}
}
You are getting the ascii value of the characters; you can use Character.digit(char, int) to get the numeric value. Something like,
String numbers = "55";
int num1 = Character.digit(numbers.charAt(0), 10);
int num2 = Character.digit(numbers.charAt(1), 10);
System.out.println(num1 + num2);
Output is (as requested)
10
int x = Character.getNumericValue(element.charAt(0));
You can use string.toCharArray() method and then add them in a for loop
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scan = null;
try {
scan = new Scanner(System.in);
String line = scan.nextLine();
char[] charArray = line.toCharArray();
int sum = 0;
for (char character : charArray) {
sum += Integer.parseInt(String.valueOf(character));
}
System.out.println(sum);
} finally {
scan.close();
}
}
}
I am stuck when writing a Java program. I have to calculate the grade of 121 students and store them in an array for later use. But the array I created does not have the values from the for loop.
public class GradeCalculator{
public static void main(String[] args){
File grade = fileName();
int lines = getNumEntries(grade);
print(grade, lines);
}
public static File fileName(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name of the grade file");
String fileName = scan.nextLine();
File file = new File(fileName);
while(!file.exists()){
System.out.println("your input file does not exist");
fileName = scan.nextLine();
file = new File(fileName);
}return file;
}
public static int getNumEntries(File fln){
File file = fln;
int count = 0;
try{
Scanner input = new Scanner (fln);
while(input.hasNextLine()){
count++;
input.nextLine();
}
}catch(FileNotFoundException e) {
System.out.println("File not found");
System.exit(0);
}return count;
}
public static void print(File fln, int values)throws NoSuchElementException{
File file = fln;
int []a = new int [values];
try{
Scanner input = new Scanner(file);
for(int i=0; i<=a.length; i++){
while(input.hasNextDouble()){
double Lab = input.nextDouble();
double A1 = input.nextDouble()/10*4;
double A2 = input.nextDouble()/10*4;
double A3 = input.nextDouble()/10*4;
double A4 = input.nextDouble()/10*4;
double A5 = input.nextDouble()/10*4;
double A6 = input.nextDouble()/10*4;
double A7 = input.nextDouble()/10*4;
double Midterm1 = input.nextDouble()/20*15;
double Midterm2 = input.nextDouble()/35*15;
double Final = input.nextDouble()/110*37;
a[i]= (int)(Lab+A1+A2+A3+A4+A5+A6+A7+Midterm1+Midterm2+Final);
System.out.println(a[i]); //If I put the println here the values are correct
}
}
}catch(FileNotFoundException e){
System.out.println("File not found");
}System.out.println(a[i]); //If I put the println here the values are different
}
}
You consume all of your input in the inner while loop on the first iteration of the outer for loop. Also, you are repeatedly setting a[0] to the grade instead of each and every index possible within the array. Then your for loop finishes and you have an array like:
{lastGrade, 0, 0, 0, ..., 0}
Basically, you need to get rid of the while loop. There may be other problems as well.
I wrote a method that adds 1 to an int called total each time it sees a new word:
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
if(s.hasNext()){
total++;
}
}
return total;
}
Is that the right way to write it?
It looks fine. But the inner IF is unnecessary, also the next() method is required. Below should be fine.
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
s.next();
total++;
}
return total;
}
The Scanner implements Iterator.You should at least make the iterator step forward, like this:
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
s.next();
total++;
}
return total;
}
or the loop will run infinitely.
Use a regular expression to match all non-whitespace. :-)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScanWords {
public ScanWords() throws FileNotFoundException {
Scanner scan = new Scanner(new File("path/to/file.txt"));
int wordCount = 0;
while (scan.hasNext("\\S+")) {
scan.next();
wordCount++;
}
System.out.printf("Word Count: %d", wordCount);
}
public static void main(String[] args) throws Exception {
new ScanWords();
}
}
As others have said you have an infinite loop. Also there is a much simpler way to use Scanner.
int total = 0;
Scanner s = new Scanner(new File("/usr/share/dict/words"));
while(s.hasNext()){
s.next();
total++;
}
return total;