Find biggest number in each row from a text file in java - java

I have to find the biggest number in each row in text file but for some reason my code only finds the biggest number in the first row.
File file = new File("input.txt");
Scanner sc = new Scanner(file);
int highScore = sc.nextInt();
while(sc.hasNextInt()){
int grade = sc.nextInt();
if(grade > highScore){
highScore = grade;
}
}
System.out.println(highScore);
sc.close();
I've tried many things but it only finds the biggest number in the first row. The numbers in the text file are in a 4x4 style so, first row: 4 10 2, second row: 11 5 20 and third row: 6 3 5

Given the following lines of text.
String text = """
1 2 3 4 5 6
30 20 1 30 40
9 100, 4, 5 12 1
""";
Use Pattern.splitAsStream(String) to stream only the numeric values. The regex \\D+ will split on any grouping of non digits. (Thanks to Alexander Ivanchenko for this alternative to Arrays.stream(String.split,regex)
filter out any empty strings and convert to an int.
then return the maximum. Note: Since max returns an OptionalInt you need to use getAsInt() to get the value.
Scanner sc = new Scanner(text);
while(sc.hasNextLine()) {
int highScore = Pattern.compile("\\D+")
.splitAsStream(sc.nextLine())
.filter(s->!s.isBlank())
.mapToInt(Integer::parseInt)
.max().getAsInt();
System.out.println(highScore);
}
Prints
6
40
100
For demo purposes, a text string is used. The while loop should also work when you open a file and read with the scanner.

Use hasNextLine() to know when a new line is being read to reset the highest score.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ScanLine {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
String line = sc.nextLine();
String[] nums = line.split(" ");
int highScore = 0;
for(int i = 0; i < nums.length; ++i) {
int grade = Integer.parseInt(nums[i]);
if(grade > highScore){
highScore = grade;
}
}
System.out.println(highScore);
}
sc.close();
}
}

As written in the documentation, method hasNextInt() returns true if the next token in this scanner's input can be interpreted as an int value.
If you have input like this:
4 10 2,
11 5 20
6 3 5
Token 2, cant be interpreted as int value, and for this token method hasNextInt() will return false, and you will exist while loop.
Until that moment, the biggest number you will find is the number 10 and that is what you see printed on the console

File aaa = new File("input.txt");
Scanner sc = new Scanner(aaa);
int highScore = sc.nextInt();
int counter=1;
while(sc.hasNextInt()){
int grade = sc.nextInt();
if(counter%3==0){
highScore = grade;
}
if(grade > highScore){
highScore = grade;
}
++counter;
if(counter%3==0){
System.out.println("highScore= "+highScore+" in line number "+counter/3);
}
}
sc.close();
Note:this code work if you have 3 values in each row and you can change it by changing this condition counter%3==0 change 3 to any number

Related

Java Program to output the contents of a file within a range of numbers

So basically, my problem is, I have a text file with 5000 values in it. I am supposed to figure out how to display only the values within the range (there's no set range, but I've chosen between 1000 and 1500. So, all numbers between those values should be found and output to a text file named "User Name".txt.
The main dilemma is, I'm not able to have the text file in the code. I need it to be handled as a command line arg, and I've never really dealt with this type of problem before.
This is my code so far:
import java.util.*;
import java.io.*;
public class TestProg {
public static void main(String[] args) {
int LowerBound = 0;
int UpperBound = 0;
String Name1 = null;
String Name2 = null;
//instantiates the array to read in the numbers from the file
double[] FileNums = new double[5000];
//instantiates the array to output the upper and lower bounded values.
double[] OutputNums = new double[5000];
Scanner scanner1 = new Scanner(System.in);
System.out.println("This program will output the upper or lower
bounds of the text file.
Please input which lower bound you would like.");
LowerBound = scanner1.nextInt();
System.out.println("Now input the upper bound.");
UpperBound = scanner1.nextInt();
Names(Name1, Name2);
}
public static String Names(String Name1, String Name2) {
Scanner scanner2 = new Scanner(System.in);
System.out.println("Please input your first name.");
Name1 = scanner2.nextLine();
System.out.println("Now input your last name.");
Name2 = scanner2.nextLine();
}
}
I'm basically stuck with how to start. I believe it would involve a while loop in order to tell the program to only find the values in the range, but I'm not entirely sure.
I also have another minor problem where Name1 and Name2 keep reverting back to null since I have the names being input in a separate method.
Any help would be wonderfully appreciated.
Use following code to print number within given range(min, max inclusive).
File output = new File("output.txt");
File file = new File("input.txt");
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
file));
byte[] buffer = new byte[(int) file.length()];
bin.read(buffer);
String fileStr = new String(buffer);
String[] numbers = fileStr.split("\\s");
Scanner s = new Scanner(System.in);
System.out.println("Enter min number in range");
int rangeMin = s.nextInt();
System.out.println("Enter max number in range");
int rangeMax = s.nextInt();
for (String number : numbers) {
if (Integer.parseInt(number) >= rangeMin
&& Integer.parseInt(number) <= rangeMax) {
System.out.println(Integer.parseInt(number));
}
}
bin.close();
Input given in input.txt using space as delimeter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...

Scanner not assigning values to array

FileReader myReader = new FileReader(myReaderRef);
Scanner input = new Scanner(myReader);
int arraySize = 0;
while(input.hasNextLine()){
arraySize++;
input.nextLine();
}
int[] numbers;
numbers = new int[arraySize];
while(input.hasNextLine()){
for(int i=0; i < numbers.length; i++){
numbers[i] = input.nextInt();
}
}
input.close();
System.out.print(numbers[1]);
}
}
and the text file it is reading from reads as follows:
10
2
5
1
7
4
9
3
6
8
whenever i use system.out.print to output one of the array slots, it only gives me 0 no matter which array position i call. where am I going wrong?
edit: I had to close and restart both the filereader and scanner. Thanks for the help!
You try and read through the file twice without going back to the beginning. The first time is to count the lines, the second time is to read the data. Because you do not go back to the beginning of the file, no data is loaded / stored anywhere. So you should re-start your Scanner, eg. close and re-open.
Or you might want to consider using an ArrayList so you only need to read the file once.
List<Integer> numbers = new ArrayList<Integer>();
Scanner input = new Scanner(myReader);
while (input.hasNextLine()) {
numbers.add(input.nextInt());
input.nextLine(); // You might need this to get to the next line as nextInt() just reads the int token.
}
input.close()
You need to restart your Scanner after you count the lines (because it's at the end of the File).
Scanner input = new Scanner(myReader);
int arraySize = 0;
while(input.hasNextLine()){
arraySize++;
input.nextLine();
}
input.close(); // <-- close it.
myReader = new FileReader(myReaderRef); // Create a new FileReader
input = new Scanner(myReader); // <-- create another scanner instance
In your first while loop cursor already went to the last line of the file. So its not able to find anything after that in the next loop. So you have to create 2 Scanner object.
Scanner input = new Scanner(new File("D:\\numbers.txt"));
int arraySize =0;
while(input.hasNextLine()){
arraySize++;
input.nextLine();
}
int[] numbers;
numbers = new int[arraySize];
input.close();
Scanner input2 = new Scanner(new File("D:\\numbers.txt"));
while(input2.hasNextLine()){
for(int i=0; i < numbers.length; i++){
numbers[i] = input2.nextInt();
}
}
input2.close();
System.out.print(numbers[1]);
I tried to simplify the problem as much as possible.
The easiest way to add/remove elements to an Array for your case would be to use an ArrayList object. Read through the comments and run the project.
The first list of integers below are the original input's of the file.
The second list contains the array's printed statements. These answers might not be where you expect them to be indexed but I'm sure this will get you on the right path :)
10
2
5
1
7
4
9
3
6
8
[10, 2, 5, 1, 7, 4, 9, 3, 6, 8]
3
1
7
5
2
8
package cs1410;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class ArrayReader {
public static void main(String[] args) throws FileNotFoundException {
// Creates an array list
ArrayList<Integer> answer = new ArrayList<Integer>();
// Reads in information
JFileChooser chooser = new JFileChooser();
if (JFileChooser.APPROVE_OPTION != chooser.showOpenDialog(null)) {
return;
}
File file = chooser.getSelectedFile();
// Scan chosen document
Scanner s = new Scanner(file);
int count = 0;
// Scans each line and places the value into the array list
while (s.hasNextLine()) {
int input = s.nextInt();
answer.add(input);
}
// Kaboom
System.out.println(answer);
System.out.println(answer.indexOf(1));
System.out.println(answer.indexOf(2));
System.out.println(answer.indexOf(3));
System.out.println(answer.indexOf(4));
System.out.println(answer.indexOf(5));
System.out.println(answer.indexOf(6));
}
}

Splitting string of integers and then put the numbers onto a int array Java

Ok so i take as an input a list of numbers as a string and i want to take these numbers and create an int array with them.
import java.util.Scanner;
public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;
String s;
Scanner input = new Scanner(System.in);
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = input.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = input.nextInt();
}
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter: ");
s = input.next();
String[] parts = s.split(" ");
System.out.println(parts[1]);
for(int n = 0; n < parts.length; n++) {
System.out.println(parts[n]);
}
input.close();
}
}
Everything would be great if i could get the whole array created printed but for some reason i get this:
Input:
0 0 1 1 2 2
Output:
0
Thats it. Only the 1st element of the array is printed.Should i try to manually print and element such as parts[1](as i do and i get this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at QueueSimulation.main(QueueSimulation.java:32)
Why is this happening? And more importanly how do i fix it?
If you want to read a line, use:
s = input.nextLine();
next() returns the value till the first space.
Read more here

Using Scanner with sequence of Integers

I'm writing a program to take a sequence of integers from console, e.g.
1 5 3 4 5 5 5 4 3 2 5 5 5 3
then compute the number of occurrences and print the following output:
0 - 0
1 - 1
2 - 1
3 - 3
4 - 2
5 - 7
6 - 0
7 - 0
8 - 0
9 - 0
where the second number is the number of occurrences of the first number.
Code:
public static void main (String args[])
{
Scanner chopper = new Scanner(System.in);
System.out.println("Enter a list of number: ");
int[] numCount = new int[10];
int number;
while (chopper.hasNextInt()) {
number = chopper.nextInt();
numCount[number]++;
}
for (int i = 0; i < 10; i++) {
System.out.println(i + " - " + numCount[i]);
}
}
But after inputing the sequence, we must type a non-integer character and press "Enter" to terminate the Scanner and execute the "for" loop. Is there any way that we don't have to type a non-integer character to terminate the Scanner?
You could get out by pressing Enter followed by Control-D.
If you don't want to do that, then there's no other way with a Scanner.
You will have to read the input by some other way, for example with a BufferedReader:
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
Scanner chopper = new Scanner(line);
Even better (inspired by #user3512478's approach), with two Scanners, without BufferedReader:
Scanner chopper = new Scanner(new Scanner(System.in).nextLine());
Best way IMO:
String str;
Scanner readIn = new Scanner(System.in);
str = readIn.nextLine();
String[] nums = str.split(" ");
int[] finalArray = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
finalArray[i] = Integer.parseInt(nums[i]);
return finalArray;
Hope this helps!
Best way: Not just for this pattern, for any kind of sequence input recognition, modify delimiter of Scanner object to get required sequence recognized.
Here, in this case, change chopper delimiter to whitespace character (Spaces). i.e "\\s". You can also use "\\s*" for specifying zero or more occurrence of whitespace characters
This makes Scanner to check for spaces rather than waiting for Enter key stroke.
public static void main (String args[])
{
Scanner chopper = new Scanner(System.in).useDelimiter("\\s"); \\ Delimiter changed to whitespace.
System.out.println("Enter a list of number: ");
int[] numCount = new int[10];
int number;
while (chopper.hasNextInt()) {
number = chopper.nextInt();
numCount[number]++;
}
for (int i = 0; i < 10; i++) {
System.out.println(i + " - " + numCount[i]);
}
}
Try using a for loop.
for (int i:1; i<10;i++) {
chopper.hasNextInt()
number = chopper.nextInt();
numCount[number]++;
}
From Oracle Doc it says:
A scanning operation may block waiting for input.
Both hasNext and next methods may block waiting for further input

How to make the scanner read multiply numbers and print them without going down a row

I am new to java and I am trying to write the code as followed:
user inputs numbers one by one and the code needs to print right away each number and continue to receive the next number on the same row
this is my code so far:
Scanner user = new Scanner(System.in);
String value = user.nextLine();
String matrix = "";
int point = 0;
int pos = 0;
while(pos <= 5)
{
if(isInteger(value))
{
System.out.print(matrix.substring(point) + "\t");
matrix = matrix + value+",";
point+=2;
pos++;
}
else
{
System.out.print("Not a number");
}
value = user.next();
}
but every time I input another number to the scanner when the program is running, it goes down to the next row. so after I type 1 , 2 , 3 , 4 , 5 the output is:
1
2
3
4
5
I want to make it like this:
1 2 3 4 5
is there a way to make the scanner read another number and still remain on the same line?
You have to use nextInt() instead of nextLine() as specified here.
Try it this way:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type in all your numbers and hit return");
while (scanner.hasNext()) System.out.println(scanner.next());
}
The user inserts all numbers in one line. Afterwards you scan the input, integer per integer and print them. As separator I used space.
Here you can input all the numbers at one line separated by space & hit enter,the output will be at one line.Check it out..
int num;
int pos = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Type all the integers and hit return :");
while (pos < 5) {
if(scanner.hasNextInt()) {
num = scanner.nextInt();
System.out.print(num + "\t");
pos++;
} else {
scanner.next();
System.out.print("Not an integer number! ");
}
}
Example :
input : 1 2 3 4 5
output : 1 2 3 4 5
input : 1 2 3 M 5
output : 1 2 3 Not an integer number! 5

Categories

Resources