I am solving this problem on ArrayList in HackerRank. I completed the code but there's no stdout showing on the console.
Question:
You are given lines. In each line, there are zero or more integers. You need to answer a few queries where you need to tell the number located in the Yth position of Xth line.
The first line has an integer (n). In each of the next (n) lines there will be an integer denoting the number (d) of integers on that line and then there will be (d) space-separated integers. In the next line, there will be an integer denoting q number of queries. Each query will consist of two integers (x)and (y).
I am getting a number format exception at (int)number.
Problem statement - if the number is present at x row and y position, print it otherwise print ERROR!
Input:
5
5 41 77 74 22 44
1 12
4 37 34 36 52
0
3 20 22 33
5
1 3
3 4
3 1
4 3
5 5
Output:
74
52
37
ERROR!
ERROR!
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n = 0;
String []problem;
int queries = 0;
int number = 0;
ArrayList<List<String>> allProblems = new ArrayList<>();
List<String> problems = new ArrayList<>();
ArrayList<List<String>> allPos = new ArrayList<>();
List<String> pos = new ArrayList<>();
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++)
{
problem = sc.nextLine().split(" ");
problems = Arrays.asList(problem);
allProblems.add(problems);
}
queries = sc.nextInt();
sc.nextLine();
for(int i=0;i<queries;i++)
{
pos = Arrays.asList(sc.nextLine().split(" "));
allPos.add(pos);
}
for(int i=0;i<queries;i++)
{
int x = Integer.parseInt((allPos.get(i)).get(0));
int y = Integer.parseInt((allPos.get(i)).get(1));
if(y >= allProblems.get(i).size()-1)
{
System.out.println("ERROR!");
}
else
{
number = Integer.parseInt((allProblems.get(x)).get(y+1));
System.out.println(number);
}
}
sc.close();
}
}
Please, try to use the code below. I added the comments in places where I changed something
package tests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n = 0;
String[] problem;
int queries = 0;
int number = 0;
ArrayList<List<String>> allProblems = new ArrayList<>();
List<String> problems; // removed an implementation from here, it wasn't used
ArrayList<List<String>> allPos = new ArrayList<>();
List<String> pos; // removed an implementation from here, it wasn't used
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++)
{
problem = sc.nextLine().split(" ");
problems = Arrays.asList(problem);
allProblems.add(problems);
}
queries = sc.nextInt();
sc.nextLine();
for (int i = 0; i < queries; i++)
{
pos = Arrays.asList(sc.nextLine().split(" "));
allPos.add(pos);
}
sc.close(); // I closed the scanner as soon as I ended read data
// defining the return values
for (int i = 0; i < queries; i++)
{
int x = Integer.parseInt((allPos.get(i)).get(0));
int y = Integer.parseInt((allPos.get(i)).get(1));
if (y > allProblems.get(x-1).size() - 1) // the equal mark was not needed
{
System.out.println("ERROR!");
} else
{
number = Integer.parseInt((allProblems.get(x-1)).get(y)); // (x-1) instead of X and Y instead of (y+1)
System.out.println(number);
}
}
}
}
Related
I'm learning Java and was wondering if it's possible to type numbers in the same line without going over the counter?
for (int i = 0; i < 5; i++) {
int a = sc.nextInt();
if (i == 4){
break;
}
}
If I press enter after every number I type in then i can have only 5 numbers and they are in a column, but if I want to type the numbers in a line, then I can have more than 5 numbers. So is there a way to do that, is there anything similar to \a in C++?
Use nextLine() method of scanner.
It will read full line and return a string.
Split string using white space and store in string array.
Iterate over string array. Pick an index and parse it with the help of Integer class parseInt method.
Store in array or use in any way you want/need.
Input pattern :- 12 13 14 15 16 16 18
You can have N number of integer in 1 line.
Note:- You should be sure that user only enter integer in input. Else you need to write if and else logic just before converting string into integer. So that your code will not throw an exception.
String a = sc.nextLine();
String arr[] = a.split("\\s+"):
int input[] = new int[arr.length];
for( int i = 0 ; i < arr.length ; i++){
input[i] = Integer.parseInt(arr[i]);
}
You can use BufferedReader also. Here is an example. The .split() method will return you an array object with the input values you entered splited by white space in this case. After that you need to parse the entries because they are String objects.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String... args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String[] input = br.readLine().split(" ");
int[] a = new int[input.length];
for (int i = 0; i < input.length; i++)
a[i] = Integer.parseInt(input[i]);
for (int i = 0; i < input.length; i++) System.out.printf("%d ", a[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm doing a task in which I am told to check for the '-'s in sample data, when a - is found in the data and there are adjacent dashes within the hashes, this only counts for 1 occurrence, e.g. in this sample data the answer would be 4.
I started by creating a 2D array to populate it then I was going to check for the dashes in the array but I am a bit puzzled as to how I would go about actually counting the occurrences, Any help would be appreciated.
Here's what I have so far;
Scanner input = new Scanner(System.in);
int a = input.nextInt(); //no. of rows
int b = input.nextInt(); //no. of columns
String arr[][] = new String[a][b]; //array of strings of 10 x 20
for(int i = 0; i<a; i++){
for(int j = 0; j<b; j++){
arr[i][j] = input.next();
}
}
//for test purposes
for(String[] s : arr){
for(String e : s){
System.out.print(e);
}
}
Here's the sample input:
10 20
#################---
##-###############--
#---################
##-#################
########---#########
#######-----########
########---#########
##################--
#################---
##################-#
Simplest way to use regex. Consider each row as string, trim string and then allow only 20 characters in string(based on your column count).
Other approaches could be to use DSL algos.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String... args) throws Exception {
Scanner input = new Scanner(System.in);
int a = input.nextInt(); // no. of rows
int b = input.nextInt(); // no. of columns
Pattern pattern = Pattern.compile("#(--+)#");
int count = 0;
for (int i = 0; i < a; i++) {
String temp = input.next().trim();
if (temp.length() > b) {
temp.substring(0, b);
}
Matcher matcher = pattern.matcher(temp);
if (matcher.find()) {
count++;
}
}
System.out.println(count);
}
}
I'm writing my solution for a problem which involves, among other things, parsing a string which contains numbers entered by the user, separated with spaces and then storing them as integers.
I'm not sure why I get a numberformat exception, when I'm using the nextLine() method to first accept the string (including spaces) and then using the split method to separate out the integers. What's still weird is that the code has worked in a different problem before, but not here apparently.
Here's the code, and the exception message:
package algorithms.Warmup;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by manishgiri on 4/8/15.
*/
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = sc.nextLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
And the exception messages:
Enter number of test cases:
2
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Enter N, C, M separated by spaces
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at algorithms.Warmup.ChocolateFeastTest.main(ChocolateFeastTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
On tracing the exception, it looks like the error occurs in the line when I use Integer.parseInt(), but even before that, why doesn't the code read in the numbers (with spaces) in the first place? ie: this line doesn't work:
String next = sc.nextLine()
I'd appreciate any help!
You're using nextInt() which only reads the integer, not the new line character \n at the end of the line.
Therefore, when you press an integer and then enter, the line:
int T = sc.nextInt();
Only reads the integer. Next when you do:
String next = sc.nextLine();
It reads the new line character waiting in the input to be read.
Simply change to:
int T = Integer.parseInt(sc.nextLine());
(But of course, doing try/catch on that would be much better)
The problem is nextInt() doesnt use full line so when you do String next = sc.nextLine(); It reads the same line resulting the error.
Problem can be solved by
int T = sc.nextInt();
nextLine(); //adding a next line after nextInt()
I just changed: int T = sc.nextInt();
To: int T = Integer.parseInt(sc.nextLine());
This seems to work.
I tried using BufferedReader and it worked.
Here is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = br.readLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
You need to call 'sc.nextLine()' twice, in order to take the input from the next line. The first call will take you to the next line and the second call will grab the input on the second line.
String next = sc.nextLine();
next = sc.nextLine();
I am currently working on a program that calculates the power of certain numbers. The number limit is 1 to 9. My code is posted below. I have the following issues:
Every time I run the program it doesn't print the correct answer.
I want to modify the code so the application calculates X to power of Y, where X and Y are allowed to be integers in the range 1 to 9 (including 9). If the user enters an invalid value the program should ask the user for input again. When a user is done with entering the values for base and exponents, the program will print the result.
Conditions of this task is that I must use loops to calculate the result by doing
several multiplications; I am not allowed to use any available method or API
that calculates the result for me. Please help me come up with the solution.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package exponent;
//import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
int t = 1;
for(int i = 1;i <= e; i++);
{
t=t*b;
}
System.out.println(t);
}
// TODO code application logic here
}
For a start, there should be no semi colon after the for loop:
for(int i=1;i<=e; i++ )
{
t=t*b;
}
A simple input test could be something along the lines of:
public boolean testInput(int e)
{
if(e>9||e<1)//where e is the inputted number
{
return false
}
else
{
return true;
}
}
Then use it like this:
boolean valid = false;
while(valid!=true)
{
e = Integer.parseInt(br.readLine());
if(testInput(e)==false)
{
System.out.println("Please enter a number between 1 and 9")
continue;
}
else
{
valid = true;
}
}
Remove semi colon from for-loop
From
for(int i=1;i<=e; i++ );
to
for(int i=1;i<=e; i++ )
For the first part, its is a easy fix. You just added a semicolon where there shouldn't be in the for loop.
for(int i = 1;i <= e; i++); {
for(int i = 1;i <= e; i++){ //There should be no semicolon here
For the second part, you can do it with two very easy do-while loops.
//Replace this
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
//with
do{
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1);
do{
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1);
So the do-while loops, will first ask for the base or the power (Depending where in the code the program is running), then it will set the int to the value. If the value is greater than 9, ie: 10 or above, the program will reask for the base or power (Like I said, depended which loo is running), and then it will set the int again. It will do this, until the value is under 10. Like you want.
Here is an example of the output:
Enter the base
56
Enter the base
-4
Enter the base
4
Enter the power
67
Enter the power
10
Enter the power
-8
Enter the power
7
4 to the 7th power is 16384
If the code snippets are confusing, here is the entire compilable, working class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StackOverflowAnswers{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
do{ //Asks for the base
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1); //If the base is not valid, it goes back to the "do" statement, which asks for the base, again.
do{ //Asks for the power
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1); //If the power is not valid, it goes back to the "do" statement, which asks for the power, again.
int t = 1;
for(int i = 1;i <= e; i++){ //No semicolon here
t=t*b;
}
System.out.println(b + " to the " + e + "th power is " + t); //Just added some words and the base and the power for easier debugging and understanding.
}
}
Hope this helps.
For the first part, it is just happening because you placed a semicolon after loop's declaration, which java just loops to that semicolon and nothing more. By removing semicolon the loop should work. However, for the second part, you can just add inputcheck method, as shown in my code below.
import java.io.*;
public class abc {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b, e;
System.out.println("Enter the base");
b = check(Integer.parseInt(br.readLine()));
System.out.println("Enter the power");
e = check(Integer.parseInt(br.readLine()));
int t = 1;
for (int i = 1; i <= e; i++); {
t = t * b;
}
System.out.println(t);
}
private static int check(int x) {
while (x < 1 || x > 10)
x = Integer.parseInt(br.readLine());
return x;
}
I want to get input from stdin in the for of
3
10 20 30
the first number is the amount of numbers in the second line. Here's what I got, but it is stuck in the while loop... so I believe. I ran in debug mode and the array is not getting assign any values...
import java.util.*;
public class Tester {
public static void main (String[] args)
{
int testNum;
int[] testCases;
Scanner in = new Scanner(System.in);
System.out.println("Enter test number");
testNum = in.nextInt();
testCases = new int[testNum];
int i = 0;
while(in.hasNextInt()) {
testCases[i] = in.nextInt();
i++;
}
for(Integer t : testCases) {
if(t != null)
System.out.println(t.toString());
}
}
}
It has to do with the condition.
in.hasNextInt()
It lets you keep looping and then after three iterations 'i' value equals to 4 and testCases[4] throws ArrayIndexOutOfBoundException.
The Solution to do this could be
for (int i = 0; i < testNum; i++) {
*//do something*
}
Update your while to read only desired numbers as below:
while(i < testNum && in.hasNextInt()) {
The additional condition && i < testNum added in while will stop reading the numbers once your have read the numbers equivalent to your array size, otherwise it will go indefininte and you will get ArrayIndexOutOfBoundException when number array testCases is full i.e. you are done reading with testNum numbers.