Using Scanner with sequence of Integers - java

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

Related

Find biggest number in each row from a text file in 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

How to print the selected name in the array?

How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}

How to read multiple integers in multiple lines when the number of integers in each line is unknown

EDIT: This is the input:
1st number is m, followed by m numbers. Next entry is n followed by n lines, each with varying and unknown number of elements.
5
1 2 3 4 5
3
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
How can I read this input in Java using the scanner class? nextInt doesn't seem to take the next line character into account.
One way is to take the whole line as input and get the integers from it but am looking for something faster.
My code works for the following constraints:
1 ≤ M ≤ 10
1 ≤ N ≤ 100
The number of elements in the n lines ranges between 1 and 100
but times out for the following(takes more than 3s):
1 ≤ M ≤ 100
1 ≤ N ≤ 9 x 103
The number of elements in the n lines ranges between 1 and 1000
Here's what am doing:
public static void main(String[] str) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> qualities = new ArrayList<Integer>();
int m = in.nextInt();
in.nextLine();
for(int i=0;i<m;i++)
qualities.add(in.nextInt());
int n = in.nextInt();
in.nextLine();
for(int j=0;j<n;j++) {
HashSet<Integer> qua = new HashSet<Integer>();
String[] strng = in.nextLine().split(" ");
for(String x: strng)
qua.add(Integer.parseInt(x));
solve(qua);
}
System.out.print(count);
}
Just wanted to know if there is a way I can avoid using in.nextLine() while reading the line with multiple integers and just use in.nextInt() instead.
The number of integers in each line varies and is unknown.
How can I read this input in Java using the scanner class?
To detect new line with Scanner, you need to have 2 things.
1)Grasp the first line say L.
2)Feed L into a new Scannerand get your Ints.
Something like:
Scanner scan=new Scanner(new File("input.txt"));
while(scan.hasNext())
{
String s=scan.nextLine();
Scanner inscan=new Scanner(s);
while(inscan.hasNext())
System.out.print(" "+inscan.nextInt());
System.out.println("");
inscan.close();
}
scan.close();
Try this:
String contents =
"3\n" +
"1 2 3 4 5 6\n" +
"1 2 3 4 5\n" +
"1 2 3 4\n";
int[][] result = null;
try (BufferedReader reader = new BufferedReader(new StringReader(contents))) {
int i = 0;
int count = 0;
String line;
while ((line = reader.readLine()) != null)
if (result == null)
result = new int[count = Integer.parseInt(line)][];
else if (i < count)
result[i++] = Stream.of(line.split(" "))
.mapToInt(s -> Integer.parseInt(s))
.toArray();
else
break;
}
for (int[] line : result)
System.out.println(Arrays.toString(line));
// result:
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4]
If you are using Scanner you don't need to do anything other than use it. This code works for both a string input and direct input from the system input. As you can see it is a simple use of Scanner, the only change is to decide which way you want to instantiate the scanner, i.e. to select either a String or System.input source.
public static void main(String[] args)
{
System.out.println("\nInput some numbers (end by typing a non number)"); //$NON-NLS-1$
String contents =
"1 2 3 4 5\n" +
"1 3 5 7 9\n" +
"5 4 3 2 1\n" +
"100 33 -146\n";
// scanner form string
Scanner sc = new Scanner(contents);
// scanner from system input
// Scanner sc = new Scanner(System.in);
List<Integer> li = new LinkedList<>();
while (true)
{
try
{
Integer i = sc.nextInt();
li.add(new Integer(i));
}
catch(InputMismatchException e)
{
break;
}
catch(NoSuchElementException e)
{
break;
}
}
Integer sum = 0;
for (Integer i : li)
{
sum += i;
}
StringBuilder sb = new StringBuilder("sum = ").append(sum); //$NON-NLS-1$
System.out.println(sb.toString());
sc.close();
}
running with the Scanner linked to the String or the System input produces the same result
42
No special handling of \n is required due to the whitespace rules employe din java.
EDIT:
The InputMismatchException exception is thrown when the System.input source is used and you enter a non number, like an X. The NoSuchElementException exception is thrown when the source is a String and the input is exhausted.
This is just an example, you woul dhave to handle end of System.input better for production code.

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

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