Below is the script I have at the moment
import java.util.Arrays;
import java.util.Scanner;
public class SeeWhatTo
{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in); //define scan
int a = scan.nextInt();
int sum =0;
while (a>0 )
{
sum = sum +a;
a = scan.nextInt();
}
System.out.println(sum); //print out the sum
}
}
Currently, it stores an input value in a and then adds it to sum and once a negative or zero is given as an input, it suspends itself and outputs the sum.
I was wondering if there's an integer equivalent of isEmpty so that i can do while (! a.isEmpty() ) so when there's no input but an enter, then it would stop and prints out the sum.
A natural followup from that would be, is there a way to assign an input integer to a and check if it is empty or not at the same time in the while condition as in while ( ! (a=scan.nextInt()).isEmpty() )
Scanner can do 2 things:
Read line-by-line (nextLine).
Read token-by-token (next or e.g. nextInt).
These are really two different functionalities of Scanner, and if you're reading tokens then your Scanner basically doesn't know about empty lines.
If you call nextInt, Scanner does two things:
Finds the next token (default: delimited by any whitespace).
Tries to turn it in to an int.
The tokenizing behavior is an important feature of Scanner. If you enter 1 2\n and call nextInt twice, you get 1 and 2. However, if you enter an empty line, the tokenizing Scanner just skips it as whitespace and keeps looking for another token.
So the straightforward answer is "no": you can never get an "empty" int from a call to nextInt in a simply way and still retain the token-by-token behavior. (That's beyond the fact that a primitive variable in Java can't be "empty".)
One easy way to do what you're asking is to use line-by-line reading instead and call parseInt yourself:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String line;
while (!(line = systemIn.nextLine()).isEmpty()) {
sum += Integer.parseInt(line);
}
But you lose the tokenizing behavior. Now, if you enter 1 2\n, an exception is thrown because nextLine finds 1 2.
You can still read token-by-token with nextInt, but it's more complicated, using a second Scanner:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String nextLine;
while (!(nextLine = systemIn.nextLine()).isEmpty()) {
Scanner theInts = new Scanner(nextLine);
while (theInts.hasNextInt()) {
sum += theInts.nextInt();
}
}
Here, we can enter 1 2\n, get 1 2 as our next line, then ask the second Scanner to tokenize it.
So yes, you can program the functionality you're looking for, but not in an easy way, because Scanner is more complicated.
edit
Possibly another way is to use a delimiter on the line separator:
// use System.getProperty("line.separator") in 1.6
Scanner systemIn = new Scanner(System.in).useDelimiter(System.lineSeparator());
int sum = 0;
while (systemIn.hasNextInt()) {
sum += systemIn.nextInt();
}
Now, nextInt tokenizes the same way as nextLine. This will break the loop for any input that's not an int, including empty tokens. (Empty tokens aren't possible with the default delimiter.) I'm never really sure if people actually expect Scanner's default delimiting to work the way it does or not. It's possible creating a Scanner in this way makes it behave closer to what people seem to expect for reading the console, just line-by-line.
There isn't an equivalent in the sense that you describe, since String is a variable-length collection of characters, and having zero characters is still a valid String. One integer cannot contain zero integers, since by definition, it is already an integer.
However, your problem revolves around how Scanner works, rather than how int works.
Take a look at scan.hasNextInt(), which returns true if there is an int to read, and false otherwise. This may give you what you want, using something like:
Scanner scan = new Scanner(System.in);
int sum = 0;
while(scan.hasNextInt())
{
int a = scan.nextInt();
sum = sum + a;
}
System.out.println(sum);
Related
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:
It must be a non-negative number
It must be an alphabetical letter
... etc
What's the best way to do this?
Overview of Scanner.hasNextXXX methods
java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:
hasNext() - does it have any token at all?
hasNextLine() - does it have another line of input?
For Java primitives
hasNextInt() - does it have a token that can be parsed into an int?
Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean()
As bonus, there's also hasNextBigInteger() and hasNextBigDecimal()
The integral types also has overloads to specify radix (for e.g. hexadecimal)
Regular expression-based
hasNext(String pattern)
hasNext(Pattern pattern) is the Pattern.compile overload
Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.
Example 1: Validating positive ints
Here's a simple example of using hasNextInt() to validate positive int from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.
Related questions
How to use Scanner to accept only valid int as input
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Example 2: Multiple hasNextXXX on the same token
Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!
Here's an example of performing multiple hasNextXXX tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.
Example 3 : Validating vowels
Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.
API links
hasNext(String pattern) - Returns true if the next token matches the pattern constructed from the specified string.
java.util.regex.Pattern
Related questions
Reading a single char in Java
References
Java Tutorials/Essential Classes/Regular Expressions
regular-expressions.info/Character Classes
Example 4: Using two Scanner at once
Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.
Summary
Scanner provides a rich set of features, such as hasNextXXX methods for validation.
Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
Always remember that hasNextXXX does not advance the Scanner past any input.
Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.
Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want.
Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}
One idea:
try {
int i = Integer.parseInt(myString);
if (i < 0) {
// Error, negative input
}
} catch (NumberFormatException e) {
// Error, not a number.
}
There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...
If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here:
http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Otherwise, to parse an int from a string, try
Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.
String input;
int number;
try
{
number = Integer.parseInt(input);
if(number > 0)
{
System.out.println("You positive number is " + number);
}
} catch (NumberFormatException ex)
{
System.out.println("That is not a positive number!");
}
To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).
String input
for(int i = 0; i<input.length(); i++)
{
if(!Character.isLetter(input.charAt(i)))
{
System.out.println("This string does not contain only letters!");
break;
}
}
Good luck!
what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:
It must be a non-negative number
It must be an alphabetical letter
... etc
What's the best way to do this?
Overview of Scanner.hasNextXXX methods
java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:
hasNext() - does it have any token at all?
hasNextLine() - does it have another line of input?
For Java primitives
hasNextInt() - does it have a token that can be parsed into an int?
Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean()
As bonus, there's also hasNextBigInteger() and hasNextBigDecimal()
The integral types also has overloads to specify radix (for e.g. hexadecimal)
Regular expression-based
hasNext(String pattern)
hasNext(Pattern pattern) is the Pattern.compile overload
Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.
Example 1: Validating positive ints
Here's a simple example of using hasNextInt() to validate positive int from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.
Related questions
How to use Scanner to accept only valid int as input
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Example 2: Multiple hasNextXXX on the same token
Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!
Here's an example of performing multiple hasNextXXX tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.
Example 3 : Validating vowels
Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.
API links
hasNext(String pattern) - Returns true if the next token matches the pattern constructed from the specified string.
java.util.regex.Pattern
Related questions
Reading a single char in Java
References
Java Tutorials/Essential Classes/Regular Expressions
regular-expressions.info/Character Classes
Example 4: Using two Scanner at once
Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.
Summary
Scanner provides a rich set of features, such as hasNextXXX methods for validation.
Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
Always remember that hasNextXXX does not advance the Scanner past any input.
Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.
Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want.
Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}
One idea:
try {
int i = Integer.parseInt(myString);
if (i < 0) {
// Error, negative input
}
} catch (NumberFormatException e) {
// Error, not a number.
}
There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...
If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here:
http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Otherwise, to parse an int from a string, try
Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.
String input;
int number;
try
{
number = Integer.parseInt(input);
if(number > 0)
{
System.out.println("You positive number is " + number);
}
} catch (NumberFormatException ex)
{
System.out.println("That is not a positive number!");
}
To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).
String input
for(int i = 0; i<input.length(); i++)
{
if(!Character.isLetter(input.charAt(i)))
{
System.out.println("This string does not contain only letters!");
break;
}
}
Good luck!
what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);
The user needs to enter a certain number of integers. Rather them enter an integer at a time, I want to make it so they can enter multiple integers on a single line, then I want those integers to be converted in an array. For example, if the user enters: 56 83 12 99 then I want an array to be created that is {56, 83, 12, 99}
In other languages like Python or Ruby I would use a .split(" ") method to achieve this. No such thing exist in Java to my knowledge. Any advice on how to accept user input and create an array based on that, all on a single line?
Using the Scanner.nextInt() method would do the trick:
Input:
56 83 12 99
Code:
import java.util.Scanner;
class Example
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] numbers = new int[4];
for(int i = 0; i < 4; ++i) {
numbers[i] = sc.nextInt();
}
}
}
At #user1803551's request on how Scanner.hasNext() can achieve this:
import java.util.*;
class Example2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
}
}
}
The answer by Makoto does what you want using Scanner#nextLine and String#split. The answer by mauris uses Scanner#nextInt and works if you are willing to change your input requirement such that the last entry is not an integer. I would like to show how to get Scanner#nextLine to work with the exact input condition you gave. Albeit not as practical, it does have educational value.
public static void main(String[] args) {
// Preparation
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers:");
// Get the input
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
// Convert the list to an array and print it
Integer[] input = numbers.toArray(new Integer[0]);
System.out.println(Arrays.toString(input));
}
When giving the input 10 11 12 upon first prompt, the program stores them (Scanner has a private buffer), but then keeps asking for more input. This might be confusing since we give 3 integers which loop through hasNext and expect that when the 4th call is made there will be no integer and the loop will break.
To understand it we need to look at the documentation:
Both hasNext and next methods [and their primitive-type companion methods] may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
(emphasis mine) and hasNextInt
Returns: true if and only if this scanner's next token is a valid int value
What happens is that we initialized scanner with an InputStream, which is a continuous stream of data. On the 4th call to hasNextInt, the scanner "does not know" if there is a next int or not because the stream is still open and data is expected to come. To conclude from the documentation, we can say that hasNextInt
Returns true if this scanner's next token is a valid int value, returns false if it is not a valid int, and blocks if it does not know what the next token is.
So what we need to do is close the stream after we got the input:
// Get the input
numbers.add(scanner.nextInt());
System.in.close();
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
This time we ask for the input, get all of it, close the stream to inform scanner that hasNextInt does not need to wait for more input, and store it through iteration. The only problem here is that we closed System.in, but if we don't need more input it's fine.
String#split exists, but you have to do more work, since you're only getting strings back.
Once you've got the split, convert each element into an int, and place it into the desired array.
final String intLine = input.nextLine();
final String[] splitIntLine = intLine.split(" ");
final int[] arr = new int[splitIntLine.length];
for(int i = 0; i < splitIntLine.length; i++) {
arr[i] = Integer.parseInt(splitIntLine[i]);
}
System.out.println(Arrays.toString(arr)); // prints contents of your array
Scanner scan2= new Scanner(System.in);
ArrayList l2=new ArrayList();
System.out.print("How many numbers do you want in your list: ");
int numbers=scan2.nextInt();
while(numbers!=0){
int age=scan2.nextInt();
l2.add(age);
numbers-=1;
}
System.println(l2);
package cornett1;
import java.util.Scanner;
public class CodeRat {
public static boolean makes10(int a , int b)
{
return (a + b == 10 || a == 10 || b == 10);
}
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt());
}
}
I am using a website called codingbat to do programming exercises and I solved the question
"Given 2 ints, a and b, return true if one of them is 10 or if their sum is 10." How can I apply this program and Input actual numbers.
Write a main method in the class, and pass in two numbers when invoking the program.
In the main method, Use
int a = Integer.parseInt(argument 0);
int b = Integer.parseInt(argument 1);
Now create a new instance of JOption class and invoke the method 'makes10' in the method with the arguments.
JOption opt = new JOption();
boolean answer = opt.makes10(a, b);
System.out.println(answer);
One of the easiest option you have is
java.util.Scanner
Defention: A simple text scanner which can parse primitive types and strings
using regular expressions.
A Scanner breaks its input into tokens
using a delimiter pattern, which by default matches whitespace.
The resulting tokens may then be converted into values of different types
using the various next methods.
Why using Scanner API?
1. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
2. A scanning operation may block waiting for input.
3 .A Scanner is not safe for multithreaded use without external synchronization.
For example:
Scanner input = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("the number you entered is " + i);
Explanation:
you read from console and feed scanner variable which is input and you just want to read int. at the end, you print the read number on the console
Resources
first one
second one
Another option is using BufferedReader API
Reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The
default is large enough for most purposes.
take a look at this sample for your BufferReader need
BufferReader vs Scanner
BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.
Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.
BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.
In your case:
int a = 0;
int b = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter two numbers");
a = input.nextInt();
b = input.nextInt();
JOption jp = new JOption();
jp.makes10(a, b);
}
public boolean makes10(int a, int b) {
return ((a + b) == 10 || a == 10 || b == 10);
}
Read up on this:
http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
This tells you how to take arguments form the command line and use those as variables in your program.
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.print(makes10(a,b));
}
If you want input at runtime, you can use the Scanner class or the Console class
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt()));
You can use a Scanner to get input from a user :
Scanner sc = new Scanner(System.in);
System.out.println(makes10(sc.nextInt(),sc.nextInt()));
Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}