Even and odd numbers with scanner Java - java

I try to add only even numbers to ArrayList. I work with file using scanner as the most proper tool in my opinion. Path to the file should be written in console. Also I use 2 the most popular ways to define even numbers.
The problem is - not only even numbers are adding to my ArrayList.
There is my code:
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = null;
List<Integer> myInts = new ArrayList<Integer>();
String filePath = null;
try {
filePath = bfReader.readLine();
inputStream = new FileInputStream(filePath);
} catch (IOException e) { }
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext()) {
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
myInts.add(scanner.nextInt());
// if ((scanner.nextInt() & 1) == 0)
// myInts.add(scanner.nextInt());
}
for (Integer x : myInts) {
System.out.println(x);
}
I suppose I misunderstand something about Scanner.
Would be glad to receive any answers!

The reason is that every new call of nextInt() read new integer from input.
Here is a modified code snippet that illustrates what you might want to try:
Scanner scanner = new Scanner(inputStream);
int myInt;
while (scanner.hasNext()) {
myInt = scanner.nextInt();
if ((myInt % 2) == 0 && myInt != 1)
myInts.add(myInt);
}
For more information look at the docs.

Every time you call nextInt, it takes an item out of the scanner. That means that one pass through your loop removes as many as three items, and the items being added are not the same as the ones you're doing your checks on.
Imagine your input is 4 3 1
Your code will do this:
if ((scanner.nextInt() /* 4 */ % 2) == 0 && scanner.nextInt() /* 3 */ != 1)
myInts.add(scanner.nextInt() /* 1 */);
And add 1 to your list.
You should change your code to this:
while (scanner.hasNext())
{
int value = scanner.nextInt();
if ((value % 2) == 0)
myInts.add(value);
}
This will only read a single value, and use it in all comparisons.

The problem here lies in
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
Every time you call scanner.nextInt(), you consume the next input. Because of this, you end up discarding most of the input. To fix this, you would need to have something like
while (scanner.hasNext())
{
int i = scanner.nextInt;
if ((i % 2) == 0 && i != 1)
myInts.add(i);
}
This will properly consume the input and should work properly.
The scanner javadoc, which contains this information, is found here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Yes I think you have understood it wrong. Whenever you use nextInt() method of the scanner class pointer which scanning file will move to the nextInt(). So it is better to save that integer values in temporary variable. Below is the modification of your code,
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = null;
List<Integer> myInts = new ArrayList<Integer>();
String filePath = null;
try
{
filePath = bfReader.readLine();
inputStream = new FileInputStream(filePath);
}
catch (IOException e)
{
}
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext())
{
int firstNumber = scanner.nextInt();
if ((firstNumber % 2) == 0 && firstNumber != 1)
myInts.add(firstNumber);
//if ((scanner.nextInt() & 1) == 0)
// myInts.add(scanner.nextInt());
}
for (Integer x : myInts)
{
System.out.println(x);
}

Every time you call scanner.nextInt() you get another number. If you want to refer to the same number multiple times, assign to a variable.
Also, having checked that a number is even, you don't also have to check that it isn't the number 1.
while (scanner.hasNext()) {
int n = scanner.nextInt();
if (n%2 == 0) {
myInts.add(n);
}
}

In the line
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
You are reading two integers from the input, instead of checking the same one twice:
int nextInt = scanner.nextInt();
if ((nextInt % 2) == 0 && nextInt != 1)

Related

Java: How to use a Scanner to check that input is an integer and is within a specified range

I'm having trouble with my code.
What it should do:
Check if Scanner "myScanner" is an Integer
If it is an Integer, if it is between 1 and 200 (both included)
Problem:
I need to input an Integer with the correct value twice after the the first guess wasn't correct.
Here is a screenshot of exactly what I mean: Screenshot of the problem
private static int inputGuess () {
Scanner myScanner = new Scanner(System.in);
int guess = 0;
if (myScanner.hasNextInt()) {
guess = myScanner.nextInt();
}
if (1 > guess || guess > 200) {
while (!(myScanner.hasNextInt()) || !(1 <= guess && guess <= 200)) {
while (!myScanner.hasNextInt()) {
myScanner.nextLine();
}
guess = myScanner.nextInt();
if (!(guess >= 1 && guess <= 200)) {
myScanner.nextLine();
}
}
}
return guess;
}
I have tried to apply #Hulk's (top answer) logic (at least I think I did) into a single method (is sadly a requirement for my project) and got this:
private static int inputGuess () {
Scanner myScanner = new Scanner(System.in);
int guess = 0;
while (!myScanner.hasNextInt() || guess < 1 || guess > 200) {
while (!myScanner.hasNextInt()) {
myScanner.nextLine();
}
guess = myScanner.nextInt();
if (guess >= 1 && guess <= 200) {
break;
}
}
return guess;
}
After a bit of testing still no error!
If you still find a mistake I would be happy if you shared it with me!
This gets a lot simpler if you split your problem into smaller parts. First, solve the "read until we got an integer" part and put it into a method so we can reuse it:
private static int readNumber(Scanner sc) {
while (!sc.hasNextInt()) {
sc.nextLine(); // if its not a number, consume the line and wait for new input
}
return sc.nextInt(); // always an integer
}
Now, we only need to add the range check:
private static int inputGuess () {
Scanner myScanner = new Scanner(System.in);
int n = 0;
while (n < 1 || n > 200) { // range check, only in one place
n = readNumber(myScanner); // always returns a number
}
return n;
}
You basically complicated things too much, by repeating the range check in 3 places in different ways, and it's easy to get lost with all these negations. Keep your methods simple, and only do one thing at a time!
To adress your updated question: If you absolutely need to inline these into one method, this is the result:
private static int inputGuess () {
Scanner myScanner = new Scanner(System.in);
int n = 0;
while (n < 1 || n > 200) { // loop until in valid range
while (!myScanner.hasNextInt()) {
myScanner.nextLine(); // if its not a number, consume the line and wait for new input
}
n = myScanner.nextInt(); // always an integer
}
return n; // always in valid range
}
Note that there is still only one place where there is a check for numeric input, and only one place where the range is validated. In programming, there is rarely a reason to write exactly the same thing twice - don't repeat yourself! - a 'principle'/guideline sometimes abbreviated as DRY.

Entering (input/scanner) two same numbers consecutively to break a loop "while" Java

I am a new-bee in java, I have a problem that i cant figure out to compare previous entered number(int) with next one continuously and I need to write a program that repeatedly reads numbers from the user’s keyboard. The program stops looping when the user types the same number twice in a row.
Thanks in advance for your kind guidance.
Here’s a sample run of the program:
5
13
21
5
4
5
5
Done!
Following was my unsuccessful effort :)
Scanner input = new Scanner(System.in);
System.out.println("Enter Numbers");
int x = 0;
int y = 0;
x = input.nextInt();
y = input.nextInt();
while (x != y) {
x = input.nextInt();
y = input.nextInt();
}
System.out.println("Done!!!!!!!");
input.close();
You can use loop to read number from console and stop if previous nubmer equals to current one. As marker of first number you can use e.g. null value of Integer prv (as alternative, you can use boolean isFirstLine flag for first line or res.isEmpty()).
public static List<Integer> receiveNumbers() {
List<Integer> res = new LinkedList<>();
Integer prv = null;
try (Scanner scan = new Scanner(System.in)) {
while (true) {
int num = scan.nextInt();
if (prv != null && prv == num)
break;
res.add(num);
prv = num;
}
}
return res;
}
import java.util.Scanner;
public class OngoingPractice {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int previous, current;
previous = keyboard.nextInt();
current = keyboard.nextInt();
while (current != previous) {
previous = current;
current = keyboard.nextInt();
}
System.out.println("Done!");
Just use an infinite while loop and break if the new int is equal to previous one. As a suggestion you should show how you tried.
Scanner sc = new Scanner(System.in);
int i;
Integer j = null;
boolean flag = false;
while(true) {
i = sc.nextInt();
if(j==null) {j=i; flag = true;}
if(j==i&&!flag) {
System.out.println("Done");
break;}
j=i;
flag = false;
}
Edited : if first one is -1, it won't work as in the comment. so I modified some.
Remember the last entered data in one variable and check it with the current data. If both matches, break the loop.
Scanner scanner = new Scanner(System.in);
String previousNumber="";
while (scan.hasNextInt()) {
int number = scan.nextInt();
if(!previousNumber.equals("") && number==Integer.parseInt(previousNumber)) {
break;
}else {
System.out.println(number);
}
previousNumber=number+"";
}

Java input random numbers and keep a counter for each number

So I am trying to create a loop that accepts number "0 - 10". If it is less than "0" than the loop exits and the program prints out all the numbers and the number of times each was entered. So Lets say you enter values like 1 2 3 4 5 1 It will print out something like Number:1 Times Entered:2 then next line will print out Number:2 Times Entered:1. If it goes higher than 10 I will just give them an input error. If someone can just help me out creating the correct variables and format I think I can take it from there. Here is what I have thus far... I know it's not correct but this is the idea I am trying to do.
import java.io.*;
public class test {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
Integer[] numbers = new Integer[1000]
int count = 0;
str = input.readLine();
while(str != null){
numbers[count] = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(numbers < 0)
break;
else if(numbers >= 0 || numbers <= 50)
numbers[count]++;
else
System.out.print("You must enter a value less than 51");
} // Close while loop here
System.out.println("Number:" + number + " Times Entered:" + count);
}
}
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
int i,number;
Integer[] numbers = new Integer[10];
int count = 0;
for(i=0;i<10;i++)
numbers[i]=0;
str = input.readLine();
while(str != null){
number = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(number == 0)
break;
else if(number >= 0 && number <= 10)
numbers[number-1]++;
else
System.out.print("You must enter a value less than 11");
str = input.readLine();
} // Close while loop here
for(i=0;i<10;i++)
System.out.println("Number:" + (i+1) + " Times Entered:" + numbers[i]);
}
}
This should work.And put some efforts form your side so that you can learn

Java Iterate array with a fixed length and take values with Scanner class

How can i get the value of a java array using Scanner class with a fixed length of 2, and which will iterate until its value is equal to a given value?
For example; for the following inputs,
A G
N H
D F
I wrote a for loop to take the values of fixed array road, in which the length is 2 using Scanner class.
for(int i = 0; i<block.length; i++){
System.out.println("enter number");
block[i]=input2.next().charAt(0);
}
I want to iterate this loop while the user input is {'C','C'}. THat means the array loop shpuld stop if the inputs are as follow;
A G
N H
D F
C C
How can i write the code to take user input values using Scanner class and to iterate the array? And the user input values should be copied without replacing them with newly entered values.
Thank you!
Try this way:
Scanner input2 = new Scanner(System.in);
char[] block = new char[2];
ArrayList<String> arrayList = new ArrayList<String>();
int i = 0;
o:
while (block[0] != 'C' && block[1] != 'C') {
System.out.println("enter character");
block[i % 2] = input2.next().charAt(0);
i++;
arrayList.add(input2.next());
if(arrayList.size()>=2){
if(arrayList.get(arrayList.size()-1).equals("C") && arrayList.get(arrayList.size()-2).equals("C"))
{
break o;
}
}
}
System.out.println(arrayList);
assuming that your block and input2 variables are already set up and your loop as shown is working, put that loop inside a controller loop
do {
for(int i = 0; i<block.length; i++){
System.out.println("enter number");
block[i]=input2.next().charAt(0);
}
} while (block[0] != 'C" && block[1] != 'C' )
All you need is this
char[] block = new char[2];
while (block[0] != 'C' && block[1] != 'C') {
System.out.println("enter number");
block[0]=input2.next().charAt(0);
System.out.println("enter number");
block[1]=input2.next().charAt(0);
}
I assume the following from your question
You have an array of fixed length into which you would like to read
values using a Scanner
Once you read values into the array,you would like to compare this
array with values from another array and do something if the input
array matches your array.
This is a simple program that does this:
String[] scannedValues=new String[2];
String[] matchValue={"X","Y"};
boolean isMatched=false;
Scanner s=new Scanner(System.in);
while(!isMatched)
{
for(int i=0;i<scannedValues.length;i++)
{
scannedValues[i]=s.nextLine();
}
for(int i=0;i<scannedValues.length;i++)
{
if(matchValue[i].equals(scannedValues[i]))
isMatched=true;
else
isMatched=false;
}
if(isMatched)
s.close();
}
You can use some of the Scanner methods such as nextInt() etc for finding various types of values.You can also pass regular expressions to the Scanner such as next("[A-Z]{1}")
However,in case you use a regular expression be aware that a mismatch between the input provided by the user and your expression will cause an InputMismatchException.

Cannot print out read integers: java

I am creating a program that will print out digits of pi up to a number specified by the user. I can read the input from the user, I can read the text file, but when I print the number of digits, it prints out the wrong number.
"Pi.txt" contains "3.14159".
Here is my code:
package pireturner;
import java.io.*;
import java.util.Scanner;
class PiReturner {
static File file = new File("Pi.txt");
static int count = 0;
public PiReturner() {
}
public static void readFile() {
try {
System.out.print("Enter number of digits you wish to print: ");
Scanner scanner = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new FileReader(file));
int numdigits = Integer.parseInt(scanner.nextLine());
int i;
while((i = reader.read()) != -1) {
while(count != numdigits) {
System.out.print(i);
count++;
}
}
} catch (FileNotFoundException f) {
System.err.print(f);
} catch (IOException e) {
System.err.print(e);
}
}
public static void main(String[] args ) {
PiReturner.readFile();
}
}
This will print out "515151" if the user inputs 3 as the number of digits they wish to print. I do not know why it does this, and I am not sure what I am doing wrong, as there are no errors and I have tested the reading method and it works fine. Any help would be gladly appreciated. Thanks in advance.
By the way, casting integer 'i' to a char will print out 333 (assuming input is 3).
The value 51 is the Unicode code point (and the ASCII value) for the character '3'.
To display 3 instead of the 51 you need to cast the int to char before printing it:
System.out.print((char)i);
You also have an error in your loops. You should have a single loop where you stop if either you reach the end of the file, or if you reach the required number of digits:
while(((i = reader.read()) != -1) && (count < numdigits)) {
Your code also counts the character . as a digit, but it is not a digit.
Your inner loop is not left before outputting numdigit times 3
while (count != numdigits) {
System.out.print(i);
count++;
}
instead ...
int numdigits = Integer.parseInt (scanner.nextLine ());
// for the dot
if (numdigits > 1)
++numdigits;
int i;
while ((i = reader.read ()) != -1 && count != numdigits) {
System.out.print ((char) i);
count++;
}
You only read one character from the file - '3' (character code 51, as Mark Byers points out) and then you print it 3 times.
int i;
while((count < numdigits) && ((i = reader.read()) != -1)) {
System.out.print((char)i);
count++;
}
If the user says they want 4 digits of pi, are you intending to print 3.14 or 3.141?
The above code would print 3.14 for 4 - because it's 4 characters.

Categories