I'm trying to create a program where the user can create an array using scanner. In this example, if the first input is 4, an array with the length of 4 is then initialized. However, in the next part, the scanner is asking for 5 inputs instead of 4. If the next inputs are 1 2 3 4 5, the final output will be [2,3,4,5]. I'm not sure why it's asking for 5 inputs instead of 4. Can someone tell me what I did wrong?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] numbers = new int[n];
int input = s.nextInt();
for (int i = 0; i < n; i++) {
numbers[i] = s.nextInt();
}
System.out.println("---------");
for (int x : numbers) {
System.out.print(x);
}
}
}
The line int input = s.nextInt(); is consuming the first input.. that's why array is getting initialized from 2 at 0'th index.
Remove the line int input = s.nextInt(); and it'll work fine
Related
I am really confused why my java code is not working it is giving TLE on Code Monks on Hacker Earth.
Here is the link to the 1
Link to Question
the first question MONK AND ROTATION
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(t-->0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
I don't know why is it giving TLE I think there is some infinite loop going.
the question at the site is-
Monk and Rotation
Monk loves to perform different operations on arrays, and so being the principal of HackerEarth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
The next line consists of N space separated integers , denoting the elements of the array A.
Output:
Print the required array.
Constraints:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
Sample Input
1
5 2
1 2 3 4 5
Sample Output
4 5 1 2 3
Explanation
Here T is 1, which means one test case.
denoting the number of elements in the array and , denoting the number of steps of rotations.
The initial array is:
In first rotation, 5 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
In second rotation, 4 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
Time Limit: 1.0 sec(s) for each input file
Memory Limit: 256 MB
Source Limit: 1024 KB
I'm not sure about the correctness of your solution, but try to use StreamTokenizer or BufferedReader instead of Scanner. Scanner is too slow and may result in TLE when you need to read a lot of data.
Reduce the number of reads and writes from/to System.in and System.out.
Look at the following solution
Scanner scanner = new Scanner(System.in);
int noOfTestCases = scanner.nextInt();
for (int i = 0; i < noOfTestCases; i++) {
int arraySize = scanner.nextInt();
int noOfRotations = scanner.nextInt();
noOfRotations = noOfRotations % arraySize;
scanner.nextLine();
String inputString = scanner.nextLine();
String[] inputStringArray = inputString.split(" ");
StringBuffer sb = new StringBuffer();
for (int j = 0; j < arraySize; j++) {
sb.append(inputStringArray[(arraySize + j - noOfRotations) % arraySize] + " ");
}
System.out.print(sb);
System.out.println("");
}
import java.util.*;
public class temp {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int k = sc.nextInt();
int p = 0;
int ar[] = new int[n];
for(int i=0;i<n;i++){
ar[i] = sc.nextInt();
}
k %= n;
for(int i=0;i<n;i++){
p = ar[(i+(n-k))%n];
System.out.print(p+" ");
}
System.out.println();
}
}
}
Though I have not used a big sized array in the starting, this code is working fine for all test cases.
Try this one.
Think from a different perspective. Instead of splitting the string and converting it into an array and applying the iterative logic, we can apply a different logic.
The trick is you just need to find the position of the input string where we have to split only once.
By that I mean,
input=>
6 2 //4 is the length of numbers and 2 is the index of rotation
1 2 3 4 5 6 //array (take input as a string using buffered reader)
Here, we just need to split the array string at the 2nd last space i.e. 4th space. So the output can be achieved by just splitting the string once-
5 6 1 2 3 4
first split- 5 6 + space + second split- 1 2 3 4
This logic worked for me and all the test cases passed.
Also don't forget to cover the corner case scenario when array input string is just one number.
Code Snippet-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}
Problem is in the System.out.print() call that is inside the for-loop. Thats a fairly heavy call and if called too many times and creates an overhead. This solution works:
//import for Scanner and other utility classes
import java.util.*;
class TestClass {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
int noOfTests = Integer.parseInt(input);
for (int t = 0; t < noOfTests; t++) {
input = s.nextLine();
String[] str = input.split(" ");
int sizeOfArray = Integer.parseInt(str[0]);
int noOfRotations = Integer.parseInt(str[1]);
String strIntegerArray = s.nextLine();
String[] array = strIntegerArray.split(" ");
printRightRotatedArray(array, noOfRotations, strIntegerArray.length());
}
}
static void printRightRotatedArray(String[] array, int noOfRotations, int lengthOfStr) {
int len = array.length;
int noOfAcutalRotations = noOfRotations % len;
int startingIndex = len - noOfAcutalRotations;
StringBuilder sb = new StringBuilder(lengthOfStr+1);
for (int i = 0; i < len; i++) {
sb.append(array[(startingIndex + i) % len]);
sb.append(" ");
}
System.out.println(sb);
}
}
putting all into string buffer and print at the end worked for me.
class TestClass {
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();// output
for(int i=0;i<t;i++){
String [] nk=br.readLine().split(" ");
int n= Integer.parseInt(nk[0]);
int k=Integer.parseInt(nk[1]);
String [] a=br.readLine().split(" ");
int split=n-(k%n);
for (int j = split; j < a.length; j++) {
sb.append(a[j]);
sb.append(' ');
}
for (int j = 0 ; j < split; j++) {
sb.append(a[j]);
sb.append(' ');
}
sb.append("\n");
}
System.out.println(sb);
}
}
I am trying to read elements of a 2-d 3x3 matrix using a scanner.
The input would look something like this:
3
11 2 4
4 5 6
10 8 -12
I am current geting the error:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.next();
List<List<Integer>> array = new ArrayList<>();
for (int i = 0; i < a; i++) {
String number = scan.nextLine();
String[] arrRowItems1 = number.split(" ");
List<Integer> list = new ArrayList<>();
for (int j = 0; j < a; j++) {
int arrItem = Integer.parseInt(arrRowItems1[j]);
list.add(arrItem);
}
array.add(list);
}
scan.close();
How do I go about doing this problem, so that a the end a 2d 3x3 matrix array is constructed according to user input? Thank You.
Do the following:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // change to nextLine
Your program works just fine the way it was written as long as you make the above change. However, I recommend you split on "\\s+" to allow any number of spaces between the numbers.
You could read the input line-by-line as a string, check it for validity, parse it and fill it in an int[][]-Matrix.
This way, the program keeps asking for input until it got three valid lines of numbers:
Scanner scan = new Scanner(System.in);
int dim = 3; //dimensions of the matrix
int line = 1; //we start with line 1
int[][] matrix = new int[dim][dim]; //the target matrix
while(line <= dim) {
System.out.print("Enter values for line " + line + ": "); //ask for line
String in = scan.nextLine(); //prompt for line
String[] nums; //declare line numbers array variable
//check input for validity
if (!in.matches("[\\-\\d\\s]+")
| (nums = in.trim().split("\\s")).length != dim) {
System.out.println("Invalid input!");
continue;
}
//fill line data into target matrix
for (int i = 0; i < nums.length; i++) {
matrix[line - 1][i] = Integer.parseInt(nums[i]);
}
line++; //next line
}
scan.close(); //close scanner (!)
//test output
for (int i = 0; i < matrix.length; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
The last for-loop is only for printing the result, just to check if it works:
Enter values for line 1: 11 2 4
Enter values for line 2: 4 5 6
Enter values for line 3: 10 8 -12
[11, 2, 4]
[4, 5, 6]
[10, 8, -12]
BTW by changing the value for dim (dimension) you could even get a 5x5 or whatever matrix!
I hope this helped!
I am supposed to write a program that accepts 6 user inputs and display numbers less than 3. I don't know what the problem is and I can't find help anywhere.
public class Apples {
public static void main(String [] args{
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
for (int i = 0; i<6; i++){
numList[i]=scan.nextDouble(); //user input
}
Arrays.sort(numList[i]); //sort user input
for (numList < 3)
System.out.println(numList);
}
}
}
I would to something like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=0; i<6; i++) {
double number = scan.nextDouble();
if(number < 3.0) {
System.out.println(number);
}
}
}
So:
If it's just about printing, you don't need to store in an array the numbers, that you get from input.
You don't need sorting, you can just check if the number that you have currently scanned is smaller than 3 (or double 3.0).
The for(numList < 3) is not a correct Java syntax. You probably meant if(number < 3)
This may be due to copy/paste but there where quite some problems, let me show you one solution:
public static void main(String [] args){
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
// until here everything is fine
for (int i = 0; i<numList.length; i++){ // just a hint: use the array's length. Maybe you want to change the array one day and add 20 numbers to it..
numList[i]=scan.nextDouble(); // you forgot the . and it is called nextDouble() (capital D)
}
Arrays.sort(numList); // sorting is fine, just make sure you sort the whole array (not just one element)
for (int i = 0; i<numList.length; i++){ // here I assume you want to print every element smaller than 3, so you still need to iterate over the whole array (maybe the user inputs only twos
if(numList[i]<3){ // test if the number is smaller than 3
System.out.println(numList[i]); // and print it
}
}
}
if however you want to print only the 3 smallest elements of the array, then your approach was correct (though you still need to write out the whole for conditions:
for(int i=0; i<3;i++){
System.out.println(numList[i]);
}
The last for doesn't work like that. With a for you can iterate trough numbers like you did in the first one or through lists/arrays.
I didn't understood if you wanted the smallest 3 or the ones smaller than 3.
If you want the smallest 3 you can do this:
double smallList[] = new double[3]
for (int i=0;i<3;i++) {
smallList[i] = numList[i];
}
or if you want to print it one by one:
for (int i=0;i<3;i++) {
System.out.println(numList[i]);
}
if you want the ones that are smaller than 3 you'll have to do:
for (int i=0;i<numList.length;i++) {
if (numList[i]<3) {
System.out.println(numList[i]);
}
}
Two ways of printing them out.
double[] numList = new double[6];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
numList[i] = scan.nextDouble(); // user input
}
// then do
Arrays.stream(numList).filter(a -> a < 3).forEach(System.out::println);
// or
for (double n : numList) {
if (n < 3) {
System.out.println(n);
}
}
I'm trying to create a program which allows the user to addition as many pairs of numbers as they would like, by first taking user input to ask them how many sums they would like to complete (additions of 2 numbers), thereafter creating 2 arrays of whatever size the user has input, and then asking the user to input each pair of numbers on a single line that they would like to addition and storing the first value in one array and the second value in a second array from each input. This is where I am stuck, I don't know how I can take the user input as two int values on each line and store them in the respective indexes of each array to be added later. Please take a look at my code below:
import java.util.Scanner;
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
String[] input = new String[2];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
input = sc.nextLine().split(" ");
int[] intinput = Arrays.asList(input).stream().mapToInt(Integer::parseInt).toArray();
a = intinput[0];
b = intinput[1];
}
}
I think you need to change 2 lines this way:
a[i] = intinput[0];
b[i] = intinput[1];
You're using nextLine() method, which is useful for string input, but it's not the best solution for integer or other primitive data.
In addition, this line of code is wrong :
a = intinput[0];
because you're storing an integer value as integer array.
You must store that value inside a[i] in order to respect the variables type.
I'd do it this way:
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextInt();
System.out.println("Enter second number: ");
b[i] = sc.nextInt();
}
// Close scanner
sc.close();
// Prints every sum
for(int i = 0; i < a.length; i++){
System.out.println(i + "-th sum is: " + (a[i] + b[i]));
}
}
}
Here you read every pair with nextInt() which is specific for integer data.
Every time you store items in i-th position of arrays, so finally you can sum a[i] and b[i].
Result example:
Enter the amount of sums you would like to calculate:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
2
Enter second number:
1
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
3
Enter second number:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
5
Enter second number:
6
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
7
Enter second number:
8
0-th sum is: 3
1-th sum is: 7
2-th sum is: 11
3-th sum is: 15
Just read pairs with nextInt() method of scanner, it's use all space symbols like separator (not only end of line):
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
}
}
The problem is :
Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.
My code :
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-1 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
The error is :
----jGRASP exec: java Q1
Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q1.main(Q1.java:16)
----jGRASP wedge2: exit code for process is 1.
why it says that?
And the number by user printed twice!
a[i+1] = Math.pow(2,a[i]); // issue here
When i=a.length-1, i+1 is a.length. So there is no index value match in this array.
Suggestion:
Create an array witch has lenght= a.length+1
double powArray[] =new double[a.length+1];
Now
powArray[0]=a[0];
for(int i=1;i<powArray.length;i++){
powArray[i]=Math.pow(2,a[i-1]);
}
Issue is on line.16 as per compiler : a[i+1] = Math.pow(2,a[i]); The problem is indexes are not properly matched here.So it gives ArrayIndexOutOfBound Exception.Here i=a.length-1, i+1=a.length.So it is giving ArrayIndexOutOfBound Exception.
You should check that your index is not negative and not higher than the array length before accessing an array item.
Refer this : Avoiding index out of bounds exceptions
Concentrate on below portion of your code, its easy and you'll feel good if you figure out yourself:
for ( ;i<=a.length-1 ; i++) // check from where i starts and where it ends
{
a[i+1] = Math.pow(2,a[i]); // check what value of i would be here on each iteration
System.out.println((int)(a[i]) );
}
Also you could use a debugger and check every iteration
Few things to look upon here.
You have written a[0]= num ; which means the first value in the array is the same as the number entered by the user. Thus, you can see the number printed again. Thus,
a[0] = 1; // initial value has to be 1, contrary to what you've used
Next, your loop to generate the array values needs to be fixed. When you have i+1, the array index goes out of bounds in the last iteration, where your i is a.length - 1. Thus change your loop to something like this
for (int i = 1; i < a.length; i++) {
a[i] = Math.pow(2, a[i-1]);
}
Now, print the array values in a separate loop, as the previous loop won't print the value of the first index of the array.
for (int i = 0; i < a.length; i++) {
System.out.println((int)a[i]);
}
Change the upper limit to a.length-2 .Rest code remain same
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-2 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
int num ;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ; //Assign First Element To Array
double prev = a[0];
for(int i=1;i<a.length;i++){
a[i] = Math.pow(2,prev);
prev = a[i];
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Output
Enter a number :
3
3.0
8.0
256.0
Just change the loop to :
for(;i < a.length-1;i++)
since when you assign 4 as a length for a[]..
you have a[0],a[1],a[2],a[3]... 4 slots.
Now a.length gives 4.
so for your a[i+1] for i=a.length-1 (i.e 3 ) .. a[i+1] = a[4]... which is out of the array bound for you array.
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
for ( ;i<a.length ; i++) {
a[i] = Math.pow(2,i);
System.out.pri``nt((int)a[i]+ " ");
}
}
}