Java: issue calculating average from txt file - java

Hello everybody first post on here!
i'm currently having some issues with my readfromfile() to calculate an average my issue is that its printing the ten numbers "stuck together"
like 12345678910 i dont understand how i can calculate an average like this i tried token/10 and it returns 0000000000
any suggestions getting an average from this mess?
i tried returning token with %n%s which looks better but still when i divide by 10 it doesnt give me a correct number what am i doing wrong
package average;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Formatter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class average {
private static Formatter output;
private static Scanner input;
public static void main(String[] args) {
openFileWrite();
writeToFile();
closeFile();
openFileRead();
readFromFile();
closeFileRead();
}
public static void openFileRead() { // gets file for "read"
try {
input = new Scanner(Paths.get("Numbers.txt"));
} catch (IOException e) {
System.out.println("Unable to read file");
}
}
public static void openFileWrite() { // gets file for "write"
try {
output = new Formatter("Numbers.txt");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file");
}
}
public static void readFromFile() {
while (input.hasNextInt()) {
int token = input.nextInt();
System.out.print(token);
}
}
public static void writeToFile() {
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 numbers");
try {
for (int i = 0; i < 10; i++) {
System.out.println("Another Number Please");
int total = input.nextInt();
output.format("%s%n", total);
}
} catch (InputMismatchException e) {
System.out.println("Please do not enter any letters");
writeToFile();
}
}
//required to close file for write
public static void closeFile() {
output.close();
}
//required to close file for read
public static void closeFileRead() {
input.close();
}
}

Just change your readFromFile method as:-
public static void readFromFile() {
double average = 0;
while (input.hasNextInt()) {
int token = input.nextInt();
average+=token;
}
System.out.println("Average ="+average/10);
}

Related

How to end a infinite while loop with user input

I am trying to create a loading sequence of 3 dots that repeats itself until input from the user breaks the loading sequence specifically the enter key. i connot for the life of me get the infinite while loop to end with input
public class loop {
public static void AnyKey() {
try {
System.in.read();
loading(false);
} catch (Exception e){}
}
public static void pause(long duration) {
try{
Thread.sleep(duration);
} catch (InterruptedException e){}
}
public static void loading(boolean status){
if (status == true) {
while (status) {
pause(500);
int i;
for (i = 0; i <3; i++){
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
}
public static void main(String[] args) {
loading(true);
AnyKey();
}
}
In your current code, the main method calls loading and never leaves the function. If you go through loading(true) step by step, you find that since while(status) is always true you are stuck there and AnyKey() is never called.
Also, System.in.read(); is a blocking call. This means that you will wait for user input but will be unable to print the '...'. Instead I recommend your read the documentation for input stream, there you will find the .read() function but also the .available() function which will let you know if any characters have been entered in the input buffer.
Those should be all the tools you need to figure this one out (I think).
Hope this helps!
I figured it out i needed to learn about and use Threads and global variables check out my code below im fairly pleased with myself i was working on this for 3 days now lol
import java.util.Scanner;
class AnyKey extends Thread {
public void run() {
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
loadingDots.loadingStatus = false;
}
}
public class loadingDots {
public static boolean loadingStatus;
public static void pause(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {}
}
public static void loading(){
loadingStatus = true;
while (loadingStatus) {
pause(500);
int i;
for (i = 0; i < 3; i++) {
if (!loadingStatus){
break;
}
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
public static void main(String[] args) {
AnyKey anykey = new AnyKey();
anykey.start();
loading();
}
}

The constructor Scanner(InputStream) is undefined

I have imported java.util.* but the IDE can't recognize Scanner. If I change it to import java.util.Scanner; it's fine. But I need it on java.util.* because the catch exception is part of java.util. This code is from a textbook by the way.
EDIT: I'm using Eclipse.
import java.util.*;
public class GetInteger {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
int i = GetAnInteger();
System.out.println("You entered " + i);
}
public static int GetAnInteger() {
while(true) {
try {
return sc.nextInt();
}
catch (InputMismatchException e) {
sc.next();
System.out.println("That's not an integer. Try again: ");
}
}
}
}

How to stop NoSuchElementException error from this part of the code? [duplicate]

This question already has answers here:
NoSuchElementException after closing system.in
(1 answer)
Scanner throwing NoSuchElementException
(2 answers)
NoSuchElementException Issue
(1 answer)
Closed 5 years ago.
This is a section of my code from a project that is giving an error. I am practicing encapsulation, but, cannot figure out why I am getting this error when I am setting values inside the Array-list.
There are two classes
1) Create_accountant
2) Adminstoreroom
Both of them are under same package: com.admin
package com.admin;
import java.util.InputMismatchException;
import java.util.Scanner;
class Create_accountant {
Adminstoreroom admin = new Adminstoreroom();
void Creating() {
System.out.println();
System.out.println("\t\t\t\t Create New Accoutant");
System.out.println();
name();
pass();
}
void name() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her name: \t");
String name = null;
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the name again.");
name();
}
catch(Exception e) {
System.out.println("Here is the main problem " + e);
}
admin.setAccName(name);
input.close();
}
private void pass() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her password: \t");
try {
admin.setAccPassword(input.nextLine());
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the password again.");
pass();
}
catch(Exception e) {
System.out.println("Here is the main problem");
}
input.close();
}
The problem is inside the 2 try blocks.
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
Both of the name() and pass() go for the catch(exception e) block. When I run this code, the output from the above try is
Here is the main problem java.util.NoSuchElementException: No line found
The second class
package com.admin;
import java.util.ArrayList;
class Adminstoreroom {
//These arrays are used for Storing accountant info in the admin sections
private static ArrayList<String> accName = new ArrayList<String>(30);
private static ArrayList<String> accPassword = new ArrayList<String>(30);
//Accountant Names
public void setAccName(String an) {
accName.add(an);
}
public String getAccName(int i) {
return accName.get(i);
}
//Accountant Password
public void setAccPassword(String ap) {
accPassword.add(ap);
}
public String getAccPassword(int i) {
return accPassword.get(i);
}

Counting Inversion hangs in the terminal

The code runs for a small file size.But it hangs when i use a file of huge size say 100000.The code used is:
import java.util.Scanner;
import java.util.Formatter;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;
import java.io.FileNotFoundException;
import java.io.*;
import java.lang.*;
public class mergesort1
{
private int arr[];
private int length;
private Scanner sc;
private Formatter f;
public static int inversion=0;
public mergesort1()
{
try
{
sc=new Scanner(new File("IntegerArray.txt"));
}
catch(FileNotFoundException fe)
{
System.err.println("File not found");
}
arr=new int[100000];
length=arr.length;
int i=0;
try
{
while(sc.hasNext())
arr[i++]=sc.nextInt();
}
catch (NoSuchElementException ne)
{
System.err.println("File formed wrong");
sc.close();
System.exit(1);
}
catch(IllegalStateException stateException)
{
System.err.println("Error reading from the file.");
System.exit(1);
}
split(0,length-1);
writeback();
}
private void split(int low,int high)
{
int mid;
if ((high-low)>=1)
{
mid=(low+high)/2;
split(low,mid);
split(mid+1,high);
merge(low,mid+1,high);
}
}
private void merge(int low,int mid,int high)
{
int count=low;
int lcount=low;
int rcount=mid;
int[] merged=new int[length];
while (lcount<=mid-1 && rcount<=high)
{
if (arr[lcount]<arr[rcount])
merged[count++]=arr[lcount++];
else
{
merged[count++]=arr[rcount++];
inversion=inversion+(mid-1-low);
}
}
if (lcount!=mid)
{
while (lcount<=mid-1)
{
if (arr[count]!=count)
merged[count++]=arr[lcount++];
}
}
else
{
while (rcount<=high)
{
if (arr[count]!=count)
merged[count++]=arr[rcount++];
}
}
System.out.println("The inversions counted till now is "+inversion);
for(int i=low;i<=high;i++)
arr[i]=merged[i];
}
private void writeback()
{
try
{
f=new Formatter("output.txt");
}
catch(FileNotFoundException fe)
{
System.err.println("File Not found");
}
for(int i=0;i<arr.length;i++)
f.format("%d\n",arr[i]);
System.out.println("The number of inversions is:"+inversion);
sc.close();
f.close();
}
}
Now the code runs fine for a input of 2 4 1 3 5 and the number of inversions is 3.But for a code of counting inversions of a input of size:100000 it hangs after counting till 103782637.
Try running with high memory
java -Xms512m -Xmx1024m yourclass

Syntax error on token(s), misplaced construct(s) Code Help Needed

I use eclipse to help me code & I have been having issues with the error message "Syntax error on token(s), misplaced construct(s)" coming up, I'm not entirely sure what is wrong with my code.
The goal of this code is to write a program where a user enters their name and age and the program checks to see the age is between 0 and 125. If not, the program shows an error code (use Exception Class)
Here is my current code: Errors are showing up in lines 1 and 4
public class ThreadsUnitProject1 {
import java.lang.String;
import java.io.*;
public static void main(String args[]);
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
try {
name = br.readLine();
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
catch(InvalidAgeException e) {
System.out.println("Error: " + e);
System.exit(1);
}
finally {
System.out.println("No errors found.");
}
}
}
}
Thank you thank you thank you for all of your help, I have been coding for awhile, but I'm new to Java.
Thanks again!
-Kristen
public static void main(String args[]) is a method it needs to create a block with curly braces. It doesn't contain the block in the ThreadsUnitProject1 class.
public static void main(String args[]){}
Also the import statements should be outside the class declaration.
Full Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ThreadsUnitProject1 {
public static void main(String args[]) {
}
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String name = "";
try {
name = br.readLine();
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
} finally {
System.out.println("No errors found.");
}
}
}
}
Use {} after public static void main(String args[]), not ;.

Categories

Resources