Find max value in java from file input - java

I'm new to Java and I am trying to write a program that asks the user to input the name of a txt file containing only numbers, and the program will output the sum, average, max, and min of the numbers in the file. I have written most of the program, however I am stuck trying to find the max and min of the values. Any information you can give would be helpful, and if I was not clear enough I can try to elaborate. My code so far is:
public class NumberFile{
public static void main(String[] args){
boolean goodName = false;
int currentNumber, sum = 0, numberCount=0;
Scanner numberFile = null;
FileReader infile;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the name of the file you wish to import: ");
String fileName = input.nextLine();
while (!goodName){
try{
infile = new FileReader(fileName);
numberFile = new Scanner(infile);
goodName = true;
}
catch (IOException e){
System.out.println("invalid file name, please enter another name");
fileName = input.nextLine();
}
}
while (numberFile.hasNextInt()){
currentNumber = numberFile.nextInt();
sum+=currentNumber;
numberCount++;
}
System.out.println("The sum of the numbers is " +sum);
System.out.println("The average of the numbers is " + ((double) sum)/numberCount);
} // end main
} // end class

Have two variables min and max (of course min and max should initially be int.max)
Hint:
if(currentNumber < min)
{
min= currentNumber;
}
if(currentNumber > max)
{
max = currentNumber
}
The above would be in your file read loop.

Declare two int variables - one "min" and one "max".
Initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE.
Then within your while loop check every number against those variables - ie. if number is smaller than "min" then assign it as a new "min" value.
If its larger than "max" then assign it as new "max" value.
Hope this clarifies, its very simple so I didnt put any code so you can implement it yourself.

int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
while (numberFile.hasNextInt()){
currentNumber = numberFile.nextInt();
sum+=currentNumber;
numberCount++;
if(min>currentNumber){
min=currentNumber;
}
if(max<currentNumber){
max=currentNumber;
}
}
Declare the minimum value to the maximum int value and reassign the minimum value every time you read new value that is smaller than current minimum value.
Same thing goes for maximum value.

I had an instance where I needed to find the largest Id from an .sql file containing large set of insert statements. These statements also inserted the Id along with all other fields. I thought this will make a good example as the file not only has integers but large chunk of mixed data types. Below is my program,
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* #author Hamzeen. H.
* #date 15/10/2015
*/
public class Driver {
public Driver() {
}
private void readData() {
try {
Scanner inputFile = new Scanner(new DataInputStream(
new FileInputStream("all_inserts.sql")));
long highest = 0L;
while (inputFile.hasNext()) {
String strNum = buildNumber(inputFile.next());
if (!strNum.equals("")) {
Long temp = Long.parseLong(strNum);
if (temp > highest) {
highest = temp;
}
}
}
System.out.println("Highest:: " + highest);
inputFile.close();
} catch (IOException e) {
System.out.println("Problem finding file");
}
}
private String buildNumber(String str) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
strBuilder.append(ch);
} else if ('.' == ch || !Character.isDigit(ch) || ',' == ch) {
return strBuilder.toString().trim();
}
}
return strBuilder.toString().trim();
}
public static void main(String args[]) {
new Driver().readData();
}
}

Related

java parseInt using output

The code below takes user input of 10 integers, uses String.split(" ") on the space, parses them as integers and prints them out.
public class variableGrowth
{
public main variableGrowth()
{
System.out.print('\u000c');
//scanner and variables
Scanner scan = new Scanner(System.in);
String inputInt = scan.nextLine();
System.out.println("These are the integers you entered: "+inputInt);
String[] items = inputInt.split(" ");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
System.out.println(stuff);
}
catch (NumberFormatException nfe) {
System.out.println(results);
System.out.println(errorMessage);
}
}
}
}
}
For each iteration of the loop, can the output be accessed so I could complete a sum in the loop and print it out? For example:
System.out.print(stuff(firstInt)); -- the first integer entered,
result= current + (current * (firstInt/ 100)); // or anything like this
System.out.print("something meaningful: "+result);
Your code won't compile unless you declare the variable errorMessage.
You just initialize an array to store your results but you never use it. In your loop, you should store each parsed value.
results[i] = stuff;
Then outside your loop you can access all your integers to do some stuff.
But for a simple sum operation, you can define a variable then sum each new int inside the loop.
int sum;
for ...
// get your stuff here
sum += stuff;
Also I did not notice your method signature at first. But the signature of a main method is
public static void main(String args[])
In Java, your method signature should follow :
[accessor] [static] 'returnType' yourMethodName('yourParams')
All you need to do is create an additional variable which will contain your running total.
int total = 0;
for (...) {
System.out.println(value);
total += value;
System.out.println("Running Total: " + total)
}
Go with streams (Java 8):
import java.util.*;
import java.lang.*;
class Main
{
public static void main(String[] args) {
System.out.print('\u000c');
//scanner and variables
Scanner scan = new Scanner(System.in);
String inputInt = scan.nextLine();
System.out.println("These are the integers you entered: "+inputInt);
String[] items = inputInt.split(" ");
int sum = Arrays.stream(items)
.mapToInt(x -> Integer.parseInt(x))
.sum();
System.out.println(String.format("Sum is: %s", sum));
}
}
There are a few ways you can do this. If you are looking for a direct sum of all the numbers, just keep a sum variable outside of the loop and keep a working sum through all iterations.
int sum = 0;
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
sum += stuff;
...
}
Another way is to store all of the numbers (especially if you need to perform other operations with them) in a list or an array and perform your operations after the fact.
int[] numbers = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
numbers[i] = stuff;
...
}
// Perform operations here

How do I find the smallest number in a list of floats without using any arrays?

I would like to find the smallest number in a list of floats from the file that the user types in without using any arrays, but I can't seem to figure out how to do it. This is what I have currently but it doesn't work at all. Any help would be appreciated and please feel free to edit for phrasing.
import java.io.File;
import java.util.Scanner;
public class Excercise3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");
String filename = sc.next();
File myFile = new File(filename);
String myString;
float incumbant = 0;
float secondPlace = 0;
float counter = 0;
try {
Scanner myScanner = new Scanner(myFile);
myScanner.nextLine();
//while(myScanner.hasNextFloat())
//{
counter = myScanner.nextFloat();
if (counter == 47.83) {
System.out.println("The top qualifier is: " + counter);
} else {
counter++;
}
//System.out.println(myString);
// }
myScanner.close();
sc.close();
} catch (Exception e) {
System.out.println("File not found.");
}
}
}
Just keep track of the lowest number. If the next number is lower, then it's the new lowest. You shouldn't need any storage except the one float variable.
You need to initialize your counter in Float.MAX_VALUE and replace it every time a number is smaller than the current counter.
float newNumber = myScanner.nextFloat();
if(newNumber < counter) {
counter = newNumber;
}
At the end the smallest number will be -> counter.
The trick is to keep track of the lowest number while you scan the file (using a List or other data-structure as a commenter suggest may only hide the array - depending on the implementation). Your code should use the while loop you've commented out. If your min value starts at positive infinity you don't need a separate step for the first float. The heart your code would something like this (though I confess I'm making some assumptions about what counter is suppose to do and eliminating the mysterious 47.83):
float min = Float.POSITIVE_INFINITY;
float temp;
int counter = 0;
try {
Scanner myScanner = new Scanner(myFile);
myScanner.nextLine(); //Are you sure you want to skip the first line?
while(myScanner.hasNextFloat()) {
temp = myScanner.nextFloat(); //get next float
if(temp<min) min=temp; //keep smallest float so far
counter++; //count floats checked
}
myScanner.close();
sc.close();
} catch (Exception e) {
System.out.println("File not found.");
}
In the end, counter is the number of floats you've checked and min is the smallest float. If you had no floats, min would be positive infinity.
You could write:
float min;
if (myScanner.hasNextFloat()){
min=myScanner.nextFloat();;
}
while(myScanner.hasNextFloat())
{
counter = myScanner.nextFloat();
if (counter<min) {min = counter};
if (counter == 47.83) {
System.out.println("The top qualifier is: " + counter);
} else {
counter++;
}
//System.out.println(myString);
}

Why this program repeats answers according to how many digits user inputs?

The output is supposed to be the conversion of binary to decimal. When I run this program and input (for example) 101, it will print the answers 3 times because 101 is 3 digits. How do I fix this? I only need one answer. please help
import java.util.Scanner;
public class Bin2Dec {
public static void main (String[] args){
//Convert the input string to their decimal equivalent.
//Open scanner for input.
Scanner input = new Scanner(System.in);
//Declare variable s.
String s;
//Prompt user to enter binary string of 0s and 1s.
System.out.print("Enter a binary string of 0's and 1's: ");
//Save input to s variable.
s = input.nextLine();
//Create a loop using the length of user input as the maximum number.
for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (BinaryFormatException e) {
System.out.println("There is an error in the entered binary string:"+e.getMessage());
}
}
}
public static int error(String parameter) throws BinaryFormatException {
int tot = 0;
for (int i = parameter.length(); i > 0; i--) {
char c = parameter.charAt(i - 1);
if (c == '1') tot += Math.pow(2, parameter.length() - i);
else if (c != '0') throw new BinaryFormatException("'"+c+"' is not a binary digit");
}
return tot;
}
}
You are invoking the method in a for loop:
for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (BinaryFormatException e) {
System.out.println("There is an error in the entered binary string:"+e.getMessage());
}
}
so of course it will execute as many times as the number of characters in the input. Move the call to error(s) out of the for loop.
You shouldn't try and reinvent something that has already been done. Simply using Integer#parseInt(String s, int radix) should be enough:
public class Bin2Dec {
public static void main (String[] args){
System.out.print("Enter a binary string of 0's and 1's: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int decoded = Integer.parseInt(input, 2);
System.out.println(decoded);
}
}
Just remove the 'for' loop as shown:
//Create a loop using the length of user input as the maximum number.
//for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (Exception e) {
System.out.println("There is an error in the entered binary
string:"+e.getMessage());
}
}
//}

Let user input integers until "X" is pressed Java

Basically what I have to do is read user input in (CUI) until the user presses x. Then display the min,max and average of the numbers the user has entered. I keep getting a InputMismatchException when I press x. I have tried a lot of different ways and that is why I may have some unnecessary code in there.
import java.io.*;
import java.util.Scanner;
import java.lang.Number;
public class taskTwo{
public static void main(String [] args) throws IOException {
int min = 0;
int max = 0;
boolean isX =false;
Scanner input = new Scanner (System.in);
BufferedReader input2 = new BufferedReader (new InputStreamReader (System.in));
String s = "x";
s = input2.readLine();
while(isX == false){
if(s.equals ("x") || s.equals ("X")){
isX = true;
}
int val = input.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
if(isX == true){
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
}
in the while loop you are using nextInt(), obviously it will expect an integer as input. So when you are giving input x which is an string then it will fail.
So in the loop take string as input and if it is not X and is a number then convert it to int values and calculate
s = input2.readLine(); is called outside while loop means only for first line it will check for X and loop can never be ended if fist line is not X or you entered 0.
1.) You don't need two objects reading input. Just input is sufficient.
2.) You can use
input.hasNextInt();
and
input.hasNext();
to check if the input is an int or a string. Something like:
while(true){
if(input.hasNextInt()){
//do something with the integer
}else if(input.hasNext()){
if(input.next().toLowerCase() == "x"){
break;
}
}
}

storing multiple user inputs into an integer array

So here's what i'm trying to do. Have user input numbers, store them in an array, then print all those numbers out on one line. I must use a method/function as well. I think i have done quite well so far, it shows no errors in eclipse. What im stuck on is storing their input into an array. i want them to keep inputting numbers one at a time until they're satisifed and type 'quit'. i just havent read about how to store things in an array despite looking around, particularly storing more than one thing, progressively. here is my code so far, and thank you in advance for any help!
import java.util.Scanner;
public class intarray {
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
String x;
Scanner input = new Scanner(System.in);
while (true) {
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
isNum(x);
int goingintoarray = Integer.parseInt(x);
int array[];
}
}
public static String isNum(String t) {
int user=Integer.parseInt(t);
String convertback = Integer.toString(user);
return convertback;
}
}
Since you don't know how many elements there will be an array is a bad idea since you will have to resize it quite often as new elements appear (copying arrays is expensive!) or instantiate a large enough array at the beginning (which is a waste and still doesn't protect you in 100% from having to resize it eventually).
Instead using Java's List (preferably LinkedList) sounds like a good idea since you can add elements dynamically without resizing the data structure.
List<Integer> numbers = new LinkedList<>();
while(true) {
// something
numbers.add(goingintoarray);
// something
}
Be careful of other implementations - for instance ArrayList uses an array (d'uh ;-) ) to store the elements so you would have the same problem but the resizing part would be taken care of for you by the implementation.
#Edit: by convention classes in Java are written using CamelCase starting with an uppercase letter.
ArrayList<Integer> inputs = new ArrayList<Integer>();
while (true) {
Scanner input = new Scanner(System.in);
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
inputs.add(Integer.parseInt(x));
}
You don't want the isNum method since it gives same exception here if it gets wrong input for x.
import java.util.Scanner;
public class intarray {
public static int initSize = 5;
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
int array[] = new int[initSize];
int pos = 0;
int maxSize = initSize;
String x = null;
Scanner input = new Scanner(System.in);
while (true) {
x = input.next();
if (x.equalsIgnoreCase("quit")) {
break;
}
//input empty string, java io can filter. So , x impossible "null" or null.
//if (x.equals(null))
// throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0)
throw new Error("Seems you only entered spaces. Try again.");
Integer numX = isNum(x);
// if the array is full, extend it
if(pos == maxSize){
int[] newArray = new int[2 * maxSize];
System.arraycopy(array, 0, newArray, 0, maxSize);
array = newArray;
maxSize = array.length;
}
if(null == numX)
System.out.println(x + " isn't a number."); //choose notify or throw error
else
array[pos++] = numX;
}
printArray(array, pos);
}
public static Integer isNum(String t) {
try {
return Integer.parseInt(t);
} catch (NumberFormatException e) {
return null;
}
}
public static void printArray(int[] array, int pos) {
if(null == array || array.length == 0 || pos <= 0)
return ;
for(int i = 0 ; i < pos; i++)
System.out.print(array[i] + " ");
}
}

Categories