This question already has answers here:
How to read multiple inputs on same line in Java?
(5 answers)
Closed 12 months ago.
The given problem is to be able to input 2 digits in one line, instead of:
Input:
2
2
Output:
1
It should be:
Input:
2 2
Output:
1
To make more sense, here is my code:
import java.util.Scanner;
class Main
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
int sum = a % b;
System.out.print(sum);
input.close();
}
}
I want a code that only requires you to input two digits in one line instead of having to input the 2 digits separately.
you can use scanner inside another scanner like below and iterate it to get values
To sum you can you collectors.summingInt()
working sample:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class Summing {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine())
{
List<String> tokens = new ArrayList<>();
Scanner lineScanner = new Scanner(scanner.nextLine());
while (lineScanner.hasNext()) {
tokens.add(lineScanner.next());
}
lineScanner.close();
System.out.println(tokens.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.summingInt(Integer::intValue)));
}
scanner.close();
}
}
You can use one string input. Take this string and split it by whitespace then parse it by int.
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
var str = input.nextLine();
var delimeter = " ";
var subStr = str.split(delimeter);
var nums = new ArrayList<Integer>();
for(int i = 0; i < subStr.length; i++)
{
nums.add(Integer.parseInt(subStr[i]));
}
var sum = nums.get(0) % nums.get(1);
System.out.println(sum);
input.close();
}
}
Related
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) throws IOException {
//write your code here
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
// For each Iteration I am adding the total no. of
// 1's place digits, 10's place digits, 100's place digits, and so on.
for(int i=0;i<T;i++){
int Num = sc.nextInt();
int count = 0;
for(int j=1;j<=Num;j*=10){
count += Num-j+1;
}
System.out.println(count);
}
}
}
Input:
3
100
1000000000
222222222
The output I am seeing:
192
298954307
1888888896
Desired Output:
192
8888888899
1888888896
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) throws IOException {
//write your code here
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i=0;i<T;i++){
int Num = sc.nextInt();
long count = 0;
for(int j=1;j<=Num;j*=10){
count += Num-j+1;
}
System.out.println(count);
}
}
}
I just needed to change the count variable from int to long.
I want to get an Array with the reversed number when I invoke the method (Given a random non-negative number, you have to return the digits of this number within an array in reverse order.)
I initalised a scanner, but whenever I execute, I only get the address in the heap I suppose (for example: [I#66a29884).
I know this problem also occurs when we have String, which why we have the toString-Method.
Is there a way I can print the array or the reversed numbers out in the console?
public class ConvertNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Long n = Long.parseLong(scanner.nextLine());
digitize(n);
}
public static int[] digitize(long n) {
int[] digitized = new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray() ;
System.out.println(digitized);
return digitized;
}
}
You have to change Long to String because [I#66a29884) is String. using java stream you can reverse string easily.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.*;
public class Main
{
public static String digitize(String n) {
return Stream.of(n)
.map(str->new StringBuilder(str).reverse())
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String n = scanner.next();
System.out.print(digitize(n));
}
}
I am trying to solve this question. I tried many different ways, I get the correct output but the testcases are not passed(I dont know what are those testcases). I cant figure what is wrong.
Question:
Given a set of integers (separated by space), write a program to print the sum of their cubes.
Sample Input:
1 2 3 4 5
Sample Output:
225
Sample Input:
1 2
Sample Output:
9
Solution 2:
import java.io.*;
import java.util.*;
class Test{
public static void main(String []args)
{
int num,sum=0;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
num=sc2.nextInt();
sum=sum+num*num*num;
}
System.out.print(sum);
}
}
Your test cases most likely contain large integers as input. Use BigInteger to hold their cubes.
I modified my answer according to your needs. Now it gives sum of cubes of numbers in given input which are separated by spaces. Check this :-
import java.math.BigInteger;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.List;
import java.util.Scanner;
public class SumOfCubes {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String integers="";
Integer num=0;
BigInteger cube;
BigInteger sum=new BigInteger("0");
System.out.println("Enter Integers seperated by space");
integers=in.nextLine();
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s")) {
list.add(Integer.parseInt(s));
}
list.toArray();
for(int i=0;i<list.size();i++){
num=list.get(i);
cube=BigInteger.valueOf(num*num*num);
sum=sum.add(cube);
}
System.out.println("Sum of Cubes of numbers in given input = "+sum);
}
}
Hope it helps.
Update (by Andreas): Added boilerplate imports since #Ash seems unable to figure that out.
If you would like an implementation in more functional style (using Java 8+ streams), here is another suggestion:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] numbers = line.split("\\s+");
BigInteger sum = Arrays.asList(numbers)
.stream()
.map(BigInteger::new)
.map(bigInteger -> bigInteger.pow(3))
.reduce(BigInteger.ZERO, BigInteger::add);
System.out.println(sum);
}
}
Update: After #Andreas comments, the implementation can be even shorter:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
BigInteger sum = Pattern.compile("\\s+")
.splitAsStream(line)
.map(s -> new BigInteger(s).pow(3))
.reduce(BigInteger::add)
.orElse(BigInteger.ZERO);
System.out.println(sum);
}
}
I have changed your Solution 2 a little bit. Could you please confirm whether this passes the test or not.
import java.math.BigInteger;
import java.util.Scanner;
public class Test{
public static void main(String []args)
{
BigInteger sum=new BigInteger.ZERO;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
BigInteger num=new BigInteger(String.valueOf(sc2.nextInt()));
sum= sum.add(num.multiply(num).multiply(num));
}
System.out.print(sum);
}
}
import java.util.*;
class csum
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
long csum=0;
while(in.hasNextInt())
{
csum=csum+(long)Math.pow(in.nextInt(),3);
}
System.out.println(csum);
}
}
public static void main(String args[])
{
long num,count=0;
Scanner in=new Scanner(System.in);
while(in.hasNextInt())
{
num=in.nextInt();
count+=Math.pow(num,3);
}
System.out.println(count);
}
or
public Static vid main(String args[])
{
long count;
Scanner in=new Scanner(System.in);
String s=in.nextLine();
String[] t=s.split(" ");
for(i=0;i<t.length;i++)
{
count+=Math.pow(Integer.parseInt(t[i]),3);
}
System.out.println(count);
}
Used long instead of int. Thanks to Andreas and Matsev for the BigInteger idea.
import java.util.*;
class Test{
public static void main(String []args)
{
long num,sum=0;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
num=sc2.nextInt();
sum=sum+num*num*num;
}
System.out.println(sum);
}
}
I'm trying to make a simple calculator and need help with somthing
import java.util.*;
import javax.swing.*;
public class HiWorld {
public static void main(String[] args) {
System.out.println("Type 2 Numbers");
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
answer = input1 + input2;
System.out.println(answer);
}
It says that the operator + is undefined for the argument types java.util.scanner.
What you are doing there is creating two objects that read from standard input (your keyboard) and then, you are trying to add those objects together.
For start, use:
import java.util.*;
public class HiWorld {
public static void main(String[] args) {
System.out.println("Type 2 Numbers");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
System.out.println(answer);
}
}
In Java you can only use the + operator for adding two numbers or concatenating two Strings. Not for doing anything with scanners.
I'm new to java. In my program, I have the user enter the integers that are being added to an array list. I need to set up a while loop that will be something like this:
arrayList = new ArrayList<int>;
int i = scanner.nextInt();
while(there is input from user)
{
arrayList.add(i);
}
I expect the user to enter 5 values. What do I put as the condition statement of the while loop. In other words, how do I say "while there is input?" Thanks
Try something along the lines of
while(scanner.hasNextInt())
{
arrayList.add(i);
}
import java.util.Scanner;
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList arrayList = new ArrayList<Integer>();
int input;
for (int i = 0; i < 5; i++)
{
input = scan.nextInt();
arrayList.add(input);
}
}
}
I tried below code and tested its working fine. let me know if u want another requirements.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
System.out.print("enter 5 numbers");
int counter=1;
while(scan.hasNextInt()){
int i=scan.nextInt();
arr.add(i);
counter++;
if(counter==5){
scan.close();
break;
}
}
}
}
I believe, you're currently accepted answer has a very fatal (it never updates i). What you need is something more like this -
// arrayList = new ArrayList<int>; // And arrayList isn't a great name. But I have
// no idea what they actually are. So
// just use a short name.
List<Integer> al = new ArrayList<Inteeger>(); // <-- Use the interface type?
// And, you have to use the wrapper type.
// int i = scanner.nextInt();
while (scanner.hasNextInt())
{
al.add(scanner.nextInt()); // You don't need `i`.
}