Read integers and strings from a single line of a console - java

The problem is like this:
I have two programs which takes input from a console but in different manner:
1)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
2)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
// input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
In 1st case 1 take inputs in 2 different lines like
1
2
so it gives correct answer but in 2nd case I removed the input.nextLine() statement to take inputs in a single line like:
1 2
it gives me number format exception why?? and also suggest me how I can read integers and strings from a single line of a console.

The problem is that str has the value " 2", and the leading space is not legal syntax for parseInt(). You need to either skip the white space between the two numbers in the input or trim the white space off of str before parsing as an int. To skip white space, do this:
input.skip("\\s*");
String str = input.nextLine();
To trim the space off of str before parsing, do this:
int temp2 = Integer.parseInt(str.trim());
You can also get fancy and read the two pieces of the line in one go:
if (input.findInLine("(\\d+)\\s+(\\d+)") == null) {
// expected pattern was not found
System.out.println("Incorrect input!");
} else {
// expected pattern was found - retrieve and parse the pieces
MatchResult result = input.match();
int temp1 = Integer.parseInt(result.group(1));
int temp2 = Integer.parseInt(result.group(2));
int total = temp1+temp2;
System.out.println(total);
}

Assuming the input is 1 2, after this line
String str = input.nextLine();
str is equal to " 2", so it can't be parsed as int.
You can do simply:
int temp1 = input.nextInt();
int temp2 = input.nextInt();
int total = temp1+temp2;
System.out.println(total);

in your next line there is no integer ... its trying to create and integer from null ... hence you get number formate exception. If you use split string on temp1 then you get 2 string with values 1 and 2.

Related

If condition is met -> scan input into one variable. If not -> scan input into another variable

Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}

How to solve the error and how to do better way using oops concept?

I am learning java program. I have a question to solve . the question is
enter the no . of people:
enter the product_name, price, stock_available:
total amount is price * no. of people
if the stock available is less than the no of people the print value 0
Example:
**input:**
no . of people : 3
product_name, price, stock_available: book, 100, 3
**output:** 300
public class Product {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people=sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
int quantity=Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
if(people<=quantity) {
System.out.println("Total amout is:"+(price*people));
}
else
{
System.out.println("value is "+0);
}
}
}
console error:
Enter the no . of people:
3
Enter the product_name, price, quantity_available:
book
30
Exception in thread "main" java.lang.NumberFormatException: For input string: "book"
How to solve this error and how to do better way using oops concept ?
For Loop I always prefer to read input using next() .
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
As you were using sc.nextLine() this may one reason you were getting java.lang.NumberFormatException.
Try as sc.next(); to read your input
Your problem is you are using :
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
this sc.nextLine() while taking input. Now the problem is sc.nextLine() reads a line until '\n' or enter is encountered. Now, for the first cycle in for loop it it putting a '\n' in the buffer. Because nextLine() stop taking input while '\n' encountered. So, In the next cycle the value of string[1] = '\n'. And when you try to parse this to an Integer then an error occurs. Because this is not an Integer.
Try this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people = sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.next();
}
int price = Integer.parseInt(string[1]);
int quantity = Integer.parseInt(string[2]);
if(people <= quantity) {
System.out.println("Total amount is: "+ (price*people));
}
else
{
System.out.println("value is: "+0);
}
}
You can use an extra sc.nextLine() just before the loop...
sc.nextLine() ----> add this line
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
when you press enter after getting the value of people... your string[] array takes a value in its 0 index position. So the nextLine scans only 2 values from the console and then throws an exception.
On that time your string[] values are = {"", "NAME", "PRICE"}
And you are trying to parse a string value (NAME) to int
According to your input style, your code does not serve your purpose.
Problem:
Case 1: You tried to input something like:
product_name, price, stock_available: book, 100, 3
But in your code, using for loop you tried to get 3 string values.
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
So, after first input, when you press enter without any input, it throws java.lang.NumberFormatException: For input string: ""
Case 2: nextLine() scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present. And this is the reason, you may get this exception.
when the loop executes, string[0]'s value will be ""/blank string, which it gets from the buffered line separator. string[1]'s value will be your first string input(product_name).
so, when you tried to parse it as int, it threw number format exception.
Solution:
Case 1. If you want to take input in one line then, do not use for loop. Get input as a string and parse it to get your values.
String[] string = new String[3];
String inputString = null;System.out.println("Enter the product_name, price, quantity_available:");
inputString=sc.next();
string=inputString.split(",");
String product = string[0];
int quantity = Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
Case 2. If you do not solve the buffered line separator issue, then you should use next() method to take input.
This is very simple application. So, oop concept is not necessary for the current context.

How to read characters and integers separately

I have to read the following symbols with Scanner and process them separately.
The input is:
###xx#*
1 -1 -1 4
The first line is the life and food of a game animal, the second row are her moves the - to the left, + to the right
I start with something, but not enough:
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
System.out.print("[" + ch + "] "); // to check what is happening
}
How to read the second row of integers with - and + and then operate with them?
You can use Scanner 's built-in methods like nextInt() and next() also look for something like hasNextInt() it can be usefull.
You can use various scanner class functions to do that. Input is:
1 -1 -1 4
Create two arrays to store characters '-' and '+' and one to store integers
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
if(sc.hasNextInt()){
intArray = sc.nextInt();
}
else charArray = sc.next();
}
You can parse the input character to integer if it parses then you can continue your code if it throws number format exception then you should know input character is not a number.
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
try {
int a = Integer.parseInt(String.valueOf(ch));
switch (a){
case 1:
// your condition
case -1:
// your condition
case -4:
//condition
default:
// your condition
}
}catch (NumberFormatException ex){
System.out.printf("input character is not number");
}
System.out.print("[" + ch + "] ");// to chack what is happening
}
The Java Scanner class has a whole bunch of methods for grabbing and parsing the next part of a string, e.g. next(), nextInt(), nextDouble(), etc.
The code looks like this:
String input = "1 -1 -1 4";
Scanner s = new Scanner(input);
int i1 = s.nextInt();
int i2 = s.nextInt();
int i3 = s.nextInt();
int i4 = s.nextInt();
Will read all four values
as most of the people is saying you can use scanner.nextInt() and about watching if you have to go the left or to the right you have the method Math.signum() which tells you were to go and then you can take the Math.abs() to get the value as an absolute number.
You could read whole line instead read by characters. Then split line into String array which will be contains chars of lines and operate with array. Here the solution of your case line.replaceAll("(-*[\\W\\d\\w])(\\s*)", "$1 ")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("z")) {
String line = sc.nextLine();
String[] split = line.replaceAll("(-*[\\W\\d\\w])(\\s*)", "$1 ").trim().split(" ");
Arrays.asList(split).forEach(ch -> System.out.print(ch + " "));
}
}
Output:
###xx#*
# # # x x # *
1 -1 -1 4
1 -1 -1 4

Parse int, double, and String from a String in Java

I have to do an assignment in my Java class using the Scanner method to input an integer (number of items), a string (name of the item), and a double (cost of the item). We have to use Scanner.nextLine() and then parse from there.
Example:
System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();
The user would input something like: 3 Captain Crunch 3.5
Output would be: Captain Crunch #3 for $10.5
The trouble I am having is parsing the int and double from the string, but also keeping the string value.
First of all, split the string and get an array.
Loop through the array.
Then you can try to parse those strings in array to their respective type.
For example:
In each iteration, see if it is integer. Following example checks the first element to be an integer.
string[0].matches("\\d+")
Or you can use try-catch as follow (not recommended though)
try{
int anInteger = Integer.parseInt(string[0]);
}catch(NumberFormatException e){
}
If I understand your question you could use String.indexOf(int) and String.lastIndexOf(int) like
String input = "3 Captain Crunch 3.5";
int fi = input.indexOf(' ');
int li = input.lastIndexOf(' ');
int itemNumber = Integer.parseInt(input.substring(0, fi));
double price = Double.parseDouble(input.substring(li + 1));
System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
itemNumber, itemNumber * price);
Output is
Captain Crunch #3 for $10.50
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();//take the message from the command line
String temp [] = message.split(" ");// assign to a temp array value
int number = Integer.parseInt(temp[0]);// take the first value from the message
String name = temp[1]; // second one is name.
Double price = Double.parseDouble(temp[2]); // third one is price
System.out.println(name + " #" + number + " for $ " + number*price ) ;

How to read multiple Integer values from a single line of input in Java?

I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`

Categories