Accept two integers separated by a delimiter and print their sum - java

import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int A = sc.nextInt().split(":");
int B = sc.nextInt();
System.out.println(A + B);
}
}
If I'm given an input like 1:2 then the output should be 3. Likewise 54:6 then 60.
But I'm getting an error. What should I do to achieve that output?

You cannot call split on an integer, it is meant for splitting a String. Try this:
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] numbers = sc.next().split(":");
int A = Integer.parseInt(numbers[0]);
int B = Integer.parseInt(numbers[1]);
System.out.println(A + B);
}
}
Of course some validation would be nice (check if the String contains a colon, if the parts are numeric, etc.), but this should point you in the right direction.

At first, read a whole input line into a String variable. Then just split it into two values and cast them to integer.
Code example:
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
String[] splittedValues = inputString.split(":");
int
A = Integer.parseInt(splittedValues[0]),
B = Integer.parseInt(splittedValues[1]);
System.out.println(A + B);

you will need to take input as string and then split your input by : and convert the string to integer and add them.
see example below
public class Hello {
public static void main(String[] args) {
String input;
Scanner sc = new Scanner(System.in);
input = sc.next();
String[] parts = input.split(":");
if(parts.length > 0) {
int sum = Integer.parseInt(parts[0])+Integer.parseInt(parts[1]);
System.out.println(sum);
} else{
System.out.println("Enter number in format example 12:2");
}
}
}```

You can try this:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
sc.next().charAt(0);
int B = sc.nextInt();
System.out.println(A + B);
}
}

I think Splitting of two integers is not possible in java(it is possible in python by using the input.split() function) ,for that reason it is better take input as string and split input by using colon(:) operator and convert those input string to an integer and add the both to print the result.
java code:
import java.util.Scanner;
Public class TwoIntegers
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in());
String[] two_numbers = s.next().split(":");
int fir_num = Int.parseInt(two_numbers[0]);
int sec_num = Int.parseInt(two_numbers[1]);
int sum=fir_num+sec_num;
System.out.println("The sum of two numbers is:"+sum);
}
}

Related

!string.equals(string) turns false result

In a part of my program, I put a while loop to repeatedly ask for inputs. There is an option to type in the letter "F" and break the loop.
This is my program:
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
while (x==0) {
System.out.println("Type your number:");
Scanner s = new Scanner(System.in);
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}
}
When I run the program, I type some numbers and then type "F". I see this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "F"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Example.main(Example.java:13)
I believe the String "F" can pass through my else if but I don't know why. How can I solve this?
You are comparing a string with a Scanner obj. Lets see how a scanner object works in java.
Scanner myObj = new Scanner(System.in);
String myInput = myObj.nextLine(); // Read user input
Then you can compare your myInput to the character 'f' or 'F'
You cannot directly compare a scanner object with a string. You will need to take some input using scanner and then you can compare that input with other types.
Try running this code.
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
Scanner sc = new Scanner(System.in);
while (x==0) {
System.out.println("Type your number:");
String s = sc.nextLine();
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}}

printout the length and words of the input

Sorry for my unclear questions, I want to input a single line text and print out the length of it, then printout the first word of it then the rest of the text.
Like if input "I am ruby", then the output would be:
9
I
am ruby
How should I make it? I have searched for the questions and got some similar but doesn't help, The following code is what I make so far
import java.util.Scanner;
public class lab {
public static void main(String [] args)
{
Scanner kbd = new Scanner(System.in);
String s = kbd.next();
String s1 = kbd.nextLine();
System.out.println(s);
System.out.println(s1);
}
}
import java.util.Scanner;
public class lab {
public static void main(String [] args)
{
Scanner kbd = new Scanner(System.in);
String s = kbd.next();
String s1 = kbd.nextLine();
System.out.println(s.length());
System.out.println(s);
System.out.println(s1);
}
}
Scanner does not have lenght(), Length() method is only for strings variables
Which IDE are you using (Eclipse, Netbeans, Intellij?) because the IDE usually shows you the error
I don't get what you want.
import java.util.Scanner;
public class lab
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.print("1st string: ");
String s = kbd.nextLine();
System.out.print("2nd string: ");
String s1 = kbd.nextLine();
System.out.println(s.length()); // this is for the length
System.out.println(s1); // this if for the input only
}
}
Still the same.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.print("Word:");
String s = kbd.nextLine();
System.out.println("Input:" +s); // print the string
System.out.println("Length:" + s.length()); // the length of the string
}
}
see the picture if its what u want to do.

Resource leak: 'sc' is never closed

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();
}
}

Loop in Java that takes 2 values in from the String

I need to write a loop that takes in two values from the user-given list and then work with those values in the loop. My issue is that I can not seem to get the loop to take in the 2 values from the String.
Here is my code:
import java.util.Scanner;
public class practice2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter numbers seperated by commas");
String numbers = input.nextLine();
Scanner s = new Scanner(numbers);
s.useDelimiter(",");
for(int i =0; i<numbers.length(); i+=2 ) {
int newnum = i/25;
System.out.println(newnum);
}
}
}
Here, to get the values - do as below
public static void main(String[] args) {
System.out.println("enter numbers seperated by commas");
Scanner input = new Scanner (System.in);
String[] numbers = input.nextLine().split(",\\s*");
//to read number
System.out.println(numbers[0] + " - " + numbers[1]);
//to use them as int
int i = Integer.parseInt(numbers[0]);
System.out.println(++i);
}

How to read input from user with unknown length?

I want to enter a string of numbers, delimited by ",". I don't know how long it will be. The input will be passed to the program and will end with the letter "x".
JAVA!
import java.util.Scanner;
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
int sumTotal=0;
while(scan.nextByte() != 'x') {
num = scan.nextInt();
sumTotal += num;
}
System.out.println(sumTotal);
scan.close();
}
}
PLEASE help! :)
//////////////
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x");
userInput = scan.next();
} while (!userInput.matches("(?:\\d+(?:,\\d+)*)x") || !userInput.matches("\\d+( \\d+)*x"));
scan.close();
String[] numberStrings;
if (userInput.contains(",")) {
numberStrings = userInput.replace("x", "").split(","); // 4x is now 4 and split by ','
} else {
numberStrings = userInput.replace("x", "").split(" ");
}
int sum = 0;
for (String i : numberStrings) {
sum += Integer.valueOf(i);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
}
Try this
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value");
String string = sc.nextLine();
string = string.replace("x", "");
String[] strArray = string.split(",");
for (String str : strArray) {
result += Integer.valueOf(str);
}
System.out.println("Result is " + result);
}
Input is 1,2,3,4x
Output is Result is 10
import java.io.Console;
import java.util.Scanner;
class MainClass{
public static void main(String args[]) {
int sum=0;
Console c=System.console();
Scanner scan = new Scanner(c.readLine());
scan.useDelimiter("[,x]");
while(scan.hasNextInt())
sum+=scan.nextInt();
scan.close();
System.out.print(sum);
}
}
This does the job as well. Additionally it tells the user what input is expected and if the entered list does not match the format.
public static void main(final String[] args) {
final Scanner userInputScanner = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x or 1 2 3 4x");
userInput = userInputScanner.nextLine();
} while (!(userInput.matches("\\d+(,\\d+)*x") || userInput.matches("\\d+( \\d+)*x")));
userInputScanner.close();
final String[] numberStrings = userInput.replace("x", "").split("[, ]");
int sum = 0;
for (final String numberString : numberStrings) {
sum += Integer.valueOf(numberString);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}

Categories

Resources