What is the best way to take input as per testcases? - java

I want to take input as per this way. The input begins with number of testcases x and in each of the next x lines there are two numbers m and n.
For eg:-
2
1 10
3 5
But i want to call a function after taking the input. I want to pass the input values to the function to print my output . I tried this way but it is calling the function first.
Basically i want to take all inputs first then call the function for each test case for getting the output.
Below is the code what i tried.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
for(int i=0 ; i<x ; i++) {
int n = in.nextInt();
int m = in.nextInt();
PrimeFactors(n , m);
System.out.println();
}
}

You should call function after loop.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int[][] array = new int[x][2];
for(int i=0 ; i<x ; i++) {
array[i][0] = in.nextInt();
array[i][1] = in.nextInt();
}
for (int[] ints : array) {
PrimeFactors(ints[0], ints[1]);
}
}

I suggest you to split the input and the algorithm.
You can just extract PrimeFactors(n , m); to a separate class and test in via regular unit tests.

Related

determining a substring that is repeated in all of n strings and showing that substring in the output in java

i want to write a program that first takes the amount of n and then gets n strings (example: if n = 4 it gets 4 strings ) and then checks all the strings and finds the longest substring that contains in all the strings and prints that substring in the output. and also if we have four strings and such substring exists in 3 of them but does not exist in one of them nothing must be printed but if it exists in all 4 of them it must be printed
example1:
input:
3
asdfg
pysdfgjk
sdfgrty
output:
sdfg
example 2:
3
qwesdj
rioqwe
cbnvmnbml
output:
in example 2 qwe is the longest substring that exists in the first and the second word but it does not exist in the third word so nothing must be printed
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
byte n = input.nextByte();
String[] words = new String[n];
for ( int i = 0 ; i < n ; i++){
words[i]=input.next();
}
}
}
here i get n as input and also get n strings and store them in an array of strings but i do not know how to determine that substring and how to find out if it exists in the strings or not
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
byte n = input.nextByte();
String[] words = new String[n];
for ( int i = 0 ; i < n ; i++){
words[i]=input.next();
}
System.out.println(printCommonSubstring(words));
}
public static String printCommonSubstring(String[] words){
int count =0;
String max ="";
for(int i=0;i<words[0].length();i++){
for(int l=i+1;l<=words[0].length();l++){
String sub = words[0].substring(i,l);
count =0;
for(int j=1; j<words.length;j++){
for(int k=0;k<words[j].length()-sub.length()-1;k++){
if(sub.equals(words[j].substring(k,k+sub.length()))){
count++;
break;
}
}
}
if(count== words.length-1 && max.length()<sub.length()){
max = sub;
}
}
}
return max;
}
}
this should work
Any queries -Please comment

loop based on user input java

I want to write a program that queries the user for a "number n" and then output the word repetition n times.
For example the word is "Hello".
So far I've got this:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Zahl 1:");
int number = scanner.nextInt();
}
Which should end in this ->
Number: 3
Hello
Hello
Hell
.
I don't know how to move forward.
I thank you for your time in advance!
You can use functional programming.
IntStream.range(0, n)
.forEach(System.out.println(variable));
Here n is the number of times that string is to be printed and a variable is a string.
This code out print "Hallo" n times (n = numbers)
String s = "Hello";
for (int i = 0; i < number; i++){
System.out.println(s);
}

modifying arrays in java

So I'm trying to figure out how to take user input thru the Scanner object, place it in each slot of an array, then read those numbers back to the user plus one. Problem is I have to use a a loop for the read back statement.Heres what I have so far. I figured out the first loop fine with the scanner, but I don't know how to modify each element in the array using a loop.
import java.util.Scanner;
public class Lab7
{
public static void main(String [] Args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter your 5 integers: ");
int index =0;
final int SIZE = 5;
int[] arrayOfSize = new int[SIZE];
while(index<arrayOfSize.length )
{
arrayOfSize[index]=console.nextInt();
index++;
}
System.out.println("Processing each array element...");
You can do the below, Here i am first taking the user input integers and increasing it by 1 and then storing it in the a[] array of integers code for it is int j = scanner.nextInt();
// store it in array as incremented by 1.
a[i]=j+1;,
which i am iterating later to get the user input value+1 for example if user input was 1, then in array it would be stored as 2 :-
Complete runnable code is below with the comments and sample input and output :-
public class SOTest {
public static void main(String[] args) {
// create scanner object
Scanner scanner = new Scanner(System.in);
// create an array of 10 integers
int a[] = new int[10];
for(int i=0;i<10;i++){
int j = scanner.nextInt();
// store it in array as incremented by 1.
a[i]=j+1;
}
// Now array of integers have the user input value+1.
for(int i=0;i<10;i++) {
System.out.println(" "+ a[i]);
}
}
}
My program input and output is below, which will make it easy to understand :-
1 2 3 4 5 6 7 8 9 11 printing user input value by adding 1 to it 2 3
4 5 6 7 8 9 10 12
I Think this code will easily understand by you
import java.util.Scanner;
public class Demo
{
public static void main(String [] Args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter your 5 integers: ");
int index =0;
final int SIZE = 5;
int[] arrayOfSize = new int[SIZE];
while(index<arrayOfSize.length )
{
arrayOfSize[index]=console.nextInt();
index++;
}
System.out.println("Processing each array element...");
for(int i=0;i<arrayOfSize.length;i++){
System.out.print((arrayOfSize[i]+1)+" ");//(arrayOfSize[i]+1)this will take current value stored in array and add 1 to it
}
}
}

I need to create an array with numbers given by the user, it works but keeps giving me 0

System.out.println("Please enter a coefficients of a polynomial’s terms:");
String coefficents = keyboard.nextLine();
String[] three = coefficents.split(" ");
int[] intArray1 = new int[three.length];
for (int i = 0; i < intArray1.length; i++) {
System.out.print(intArray1[i]);
}
//Does anyone know how i can make this work because right not it builds but when i run it, it gives me 0
//if someone could show me or explain to me what's wrong that would help
The problem was that you created the array intArray1 and you printed it without adding any elements to it. That's why it gives 0 as the result.
Instead of creating intArray1, print out the array three in the following way:
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the coefficients of a polynomial’s terms:");
String coefficents = user_input.nextLine();
String[] three = coefficents.split(" ");
for (String i: three) {
System.out.print(i);
}
}
}

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