Let's say I have a text file with this:
2 4 6 7 -999
9 9 9 9 -999
When I run the program, I should print out everything except the "-999" on each line. What I should get is:
2 4 6 7
9 9 9 9
This is what I've tried:
public class Prac {
public static void main(String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("test.txt"));
while(reader.hasNextLine() && reader.nextInt() != -999) {
int nextInt = reader.nextInt();
System.out.print(nextInt + " ");
}
}
}
I've tried using while/for loops but don't seem to get this to work and the numbers are not on different lines. I don't get why the condition does not work when I run the code and each line is not separated while printing. I've been trying to find a solution for a while and decided to ask here. It's probably an easy question but I haven't coded in a while, so let me know. Thanks in advance.
The reader.nextInt() in the while will consume the next int, so you will be always skipping an integer. So I would suggest:
public static void main(String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("test.txt"));
while (reader.hasNextLine()) {
int nextInt = reader.nextInt();
if (nextInt != -999)
System.out.print(nextInt + " ");
else
System.out.println();
}
}
Update: In case you want to calculate the average for each line, as requested in your comment, you could store each value to make the calculations (see here other ways). The code below will do that and print the average at the end of the line:
public static void main(String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("test.txt"));
List<Integer> values = new ArrayList<>();
while (reader.hasNextLine()) {
int nextInt = reader.nextInt();
if (nextInt != -999) {
System.out.print(nextInt + " ");
values.add(nextInt);
} else {
int sum = 0;
for (int value : values) {
sum += value;
}
System.out.println((float) sum / values.size());
values.clear();
}
}
}
Try this.
public static void main(String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("./input.txt"));
while (reader.hasNextInt()) {
int nextInt = reader.nextInt();
if (nextInt != -999) {
System.out.print(nextInt + " ");
} else {
if (reader.hasNextLine()) {
System.out.println("");
}
}
}
}
I'm late to the party ... but as long as somebody else replied after you accepted, I thought I'd share the response I started writing ... but was too slow to post back before you got two other (great!) responses.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Prac {
static final int EOL = -999;
public static void main(String[] args) throws FileNotFoundException {
File f = new File("test.txt");
try (Scanner reader = new Scanner(f)) {
int nextInt;
while(reader.hasNext()) {
if ((nextInt = reader.nextInt()) == EOL)
System.out.println();
else
System.out.print(nextInt + " ");
}
}
}
}
NOTES:
1. The main problem is that you didn't capture the value of "scanner.nextInt()" in your while loop. Consequently, you skipped every other value.
There's also a resource leak - you're not closing the Scanner. That doesn't matter for a small program like this (exiting the program will close the file just fine ;)).
One way is to do an explicit "close()".
Another alternative, illustrated above, is the try-with-resources statement, introduced in Java 8.
Problem is you're not saving the value from reader.nextInt() in your while Loop.
You can try this:
while (reader.hasNextLine()) {
int nextInt = reader.nextInt();
System.out.print( nextInt != -999 ? nextInt + " " : "\n");
}
Related
I'm trying to make a simple program where you can put integers in, and it will tell you if it increased or decreased from the previous integer input. But when I run the code, I have to put an integer value twice, but I only want it put once.
The input and output should look like (numbers typed by me, words output by the program):
Starting...
5
Increasing
4
Decreasing
6
Increasing
etc. etc.
But instead it looks like:
Starting...
5
5
Increasing
Input Number:
1
2
Not Increasing
etc. etc.
This is my code:
import java.util.Scanner;
public class Prob1 {
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (!(scan.nextInt() <= 0)) {
input = scan.nextInt();
if (input > previousInput) {
System.out.println("Increasing");
previousInput = input;
} else {
System.out.println("Not Increasing");
previousInput = input;
}
System.out.println("Input Number:");
}
scan.close();
}
}
Why does this problem occur, and how can I fix it?
The loop behavior you are describing is:
read a numeric input value
do something with it (print a message)
if the loop value meets a condition (input is 0 or less), exit the loop
otherwise, repeat
Here's a "do-while" loop that reads like those steps above:
Scanner scan = new Scanner(System.in);
int input;
do {
input = scan.nextInt();
System.out.println("input: " + input);
} while (input > 0);
System.out.println("done");
And here's input+output, first entering "1", then entering "0":
1
input: 1
0
input: 0
done
while (!(scan.nextInt() <= 0)) { takes an int and then input = scan.nextInt(); takes another one. You need to change the while loop to use input.
modified based on your code
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Input Number:");
input = scan.nextInt();
if (input <= 0) {
System.out.println("app shut down");
break;
}
if (input > previousInput) {
System.out.println("Increasing");
} else {
System.out.println("Not Increasing");
}
previousInput = input;
}
scan.close();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a console application with a main method and some methods that I call from main. There, I want to ask the user for some input, for which I use the Scanner class.
Here's my problem:
I find there is no way to use Scanner when reading inputs from outside main without random exceptions or unexpected behaviour. I have tried two approaches:
Having a Scanner global variable in the class containing main. Then
I use this same Scanner in all functions in that same class.
In every function I need to ask for input, I declare a new Scanner
variable, use it, and close it before exiting the function.
1. makes Scanner try to read twice. I mean, I have a sc.readLine in a function and, when I exit that function, I have another sc.readLine in main. I input once and the two readLine lines get executed, the second one reading an empty String.
2. throws Exception (base class Exception) when I call any sc.readLine for a second time during the execution of the program.
I have also noticed that any other method other than readLine is going to read various items on the same line. For example, line "10 20 30 40" would execute 4 sc.nextInt calls.
TL;DR: how do you use Scanner in a console application?
One way:
import java.util.Scanner;
public class Main {
private Scanner scanner = new Scanner(System.in);
public Scanner getScanner() {
return scanner;
}
void fun1() {
Scanner in = getScanner();
System.out.print("Enter a string: ");
System.out.println("You entered: " + in.nextLine());
}
void fun2() {
Scanner in = getScanner();
System.out.print("Enter an integer: ");
int n = 0;
try {
n = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(n + " + 10 = " + (n + 10));
}
public static void main(String[] args) {
Main m = new Main();
m.fun1();
m.fun2();
}
}
A sample run:
Enter a string: Hello world!
You entered: Hello world!
Enter an integer: 25
25 + 10 = 35
Another way:
import java.util.Scanner;
public class Main {
static void fun1(Scanner in) {
System.out.print("Enter a string: ");
System.out.println("You entered: " + in.nextLine());
}
static void fun2(Scanner in) {
System.out.print("Enter an integer: ");
int n = 0;
try {
n = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(n + " + 10 = " + (n + 10));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
fun1(in);
fun2(in);
}
}
A sample run:
Enter a string: Hello world!
You entered: Hello world!
Enter an integer: 25
25 + 10 = 35
Regarding your problem with next() or nextInt(): Given below is the recommended way for multiple inputs in one go.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = true;
System.out.print("Enter some intgers: ");
String strNum = in.nextLine();
String[] strNumArr = strNum.split("\\s+");
int[] numArr = new int[strNumArr.length];
for (int i = 0; i < strNumArr.length; i++) {
try {
numArr[i] = Integer.parseInt(strNumArr[i]);
} catch (NumberFormatException e) {
numArr[i] = Integer.MIN_VALUE;
valid = false;
}
}
System.out.println(Arrays.toString(numArr));
if (!valid) {
System.out.println("Note: invalid inputs have been reset to " + Integer.MIN_VALUE);
}
}
}
A sample run:
Enter some intgers: 10 5 20 15
[10, 5, 20, 15]
Another sample run:
Enter some intgers: 4 40 a 20 b 15
[4, 40, -2147483648, 20, -2147483648, 15]
Note: invalid inputs have been reset to -2147483648
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information about console input using Scanner.
to use a single instance of Scanner (or any other datatype or class), you can use the design pattern "Singleton" which consist to instantiate a single instance of your Object for the whole project.
The Singleton definition (a new class) :
import java.util.Scanner;
public class ScannerSingleton {
private static Scanner sc = null;
private ScannerSingleton() {
sc = new Scanner(System.in);
}
public static Scanner getInstance() {
if (sc == null) {
synchronized(ScannerSingleton.class) {
if (sc == null)
sc = new ScannerSingleton();
}
}
}
}
and each time you want to use your scanner anywhere you only have to call ScannerSingleton.getInstance() which will return your single instance of scanner
example of use:
String test = ScannerSingleton.getInstance().nextLine();
I suggest to pass your Scanner object as another parameter for your functions.
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String answer = ask(scanner, "what is your name?");
System.out.println("Oh! Hello dear " + answer + "!");
scanner.close();
}
private static String ask(Scanner scanner, String question)
{
System.out.println(question);
return scanner.nextLine();
}
This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}
This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}
When I run the program everything seems to work fine except that it counts 8 fives when there are in fact 9 fives in the txt file.
import java.io.*;
import java.util.*;
public class FileIO2
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
String filename = "Input1.txt";
Scanner myFile = null;
try
{
myFile = new Scanner(new FileInputStream(filename));
}
catch(Exception e)
{
System.out.println("File not found.");
System.exit(0); //close the program
}
int countNums = 0;
while(myFile.hasNext())
{
if(myFile.hasNextInt(5))
{
countNums++;
}
myFile.next();
}
System.out.println("There were " + countNums + " fives in " + filename);
}
}
Input1.txt file contents:
5 9 3 2 0 5 3 0 8 5 5 5
5 9
4 3 0 6
5 5 5
I suggest you to do some refactor on your code.
This solution works fine:
public class FileIO2 {
private static final String PATH_TO_FILE = "/home/user/temp/Input1.txt";
private static final int NUMBER_TO_FIND = 5;
public static void main(String[] args) throws FileNotFoundException {
int counter = 0;
try (Scanner scanner = new Scanner(new File(PATH_TO_FILE))) {
while (scanner.hasNextInt()) {
int currentInt = scanner.nextInt();
if (currentInt == NUMBER_TO_FIND) {
counter++;
}
}
}
System.out.println("There were " + counter + " fives in " + PATH_TO_FILE);
}
}
The problematic line in your code is myFile.hasNextInt(5).
Here is your problem:
myFile.hasNextInt(5)
From the documentation of the hasNextInt(int) method:
Returns true if the next token in this scanner's input can be
interpreted as an int value in the specified radix (base) using the nextInt()
method.
So that doesn't return true if the next int value is 5 as you expect. It will return true if each digit in the number (and each number in this case has just one digit) is between 0-4 (radix 5)!.
So change your while loop to:
while(myFile.hasNext())
{
if(myFile.hasNextInt() && myFile.nextInt() == 5)
{
countNums++;
}
}
This time we validate that the number is actually 5 using hasNextInt() without arguments (which uses radix 10, i.e. the decimal system) and nextInt which returns the given number.
Program to count how many times a particular character, letter or number occur in a sentence.
However I keep getting message:
Resource leak: 'sc' is never closed
I am using Java and Eclipse. What should I do?
import java.util.Scanner;
class Number-count {
public static void number - count(String args[]) {
String s;
char ch;
int count = 0;
Scanner SC = new Scanner(System. in );
System.out.println("Enter a sentence");
String str = sc.nextLine();
System.out.println("Enter a character to be searched for occurence");
s = sc.nextLine();
char c = s.charAt(0);
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Character " + c + " occur " + count + " times");
}
}
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method
SC.close();
after your scanner work completed put: sc.close();
It is working 100%
Try this code
public static void number - count(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
try{
//your code
}
finally {
sc.close();
}
}
If you want to use the scanner globally in a class(which is the case sometimes)
try this:
static Scanner sc = new Scanner(System.in);
/* Making it easy for beginners, when we use Scanner sc it is required to be close once we have taken all inputs from user, to close use sc.close(); */
package basicjava;
import java.util.*;
public class sumbyuser {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers for summation : ");
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a+b;
System.out.println("Summation is : "+sum);
}
}
Try sc.close();
After the using the scanner inputs :
import java.util.*;
public class Func1 {
public static void CalculateSum() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a + b;
System.out.println("The sum is " + sum);
}
public static void main(String[] args) {
CalculateSum();
}
}