I was trying a problem yesterday(well that's not the problem),but it repeatedly gave me error.
What I had to do was to take a substring,convert it itno int and just print it
but it gave error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Here is my implementation
import java.util.Scanner;
import java.io.*;
class gerald{
public static void main(String [] s)
{
long t2,t3,t,a,b,c;
Scanner sc=new Scanner(System.in);
t=sc.nextInt();
for(int i=1;i<=t;i++)
{
String time1=new String(sc.nextLine());
long t1=Integer.parseInt(time1.substring(0,2));
System.out.println(t1);
}
}
}
If I don't use loop,code works fine. Any thoughts?
You should check the length of time1 first before you execute time1.substring(0,2)
The best thing you can do is debug it. Another thing you can do is to handle anormal behaviour you can do it asking first with if-else like if(timer1.length() < 2) or using try-catch.
Let see with try-catch.
public static void main(String [] args){
int t,t1;
Scanner sc=new Scanner(System.in);
t=sc.nextInt();
String time1=null;
for(int i=1;i<=t;i++){
time1=sc.nextLine();
try{
t1=Integer.parseInt(time1.substring(0,2));
System.out.println(t1);
}catch(NumberFormatException e){
System.err.println("input string is not a number ---> "+time1);
}catch(StringIndexOutOfBoundsException e){
System.err.println("input string is shorter than required ---> "+time1);
}
}
}
Related
I realized the issue was due to me creating a new scanner/reader object(the new scanner has a blank input), the issue still persists - how do I use the same input stream for both methods (or) how do I use the same scanner reader for both methods
Original question: how to pass on the main method input stream to called method
So I'm taking in formatted input which is like this from geek for geeks (this is important to my error)
1
4
1 2 3 4
And I am using scanner class to read the numbers into variables. This is my code
// code to print reverse of input string after reading the length of the string and no. of testcases
class Main {
public static void main (String[] args) {
int i,t,n;
String x,y;
Scanner scan = new Scanner(System.in);
try {
t=scan.nextInt();
scan.nextLine();
REV rv=new REV();
for (i=0;i<t;i++){
rv.reverse();
}
}catch (Exception e){
return;
}
}
}
class REV{
public void reverse(){
int i,a[],n;
Scanner scan = new Scanner(System.in);
try {
n=scan.nextInt();
scan.nextLine()
a= new int[n];
for (i=n-1;i>=0;i--){
a[i]=scan.nextInt();
}
System.out.println(a[i]);
}catch(Exception E){
return;
}
}
}
I get no output for this (java.util.NoSuchElementException if I don't use try and catch)
I am able to read the variables in the main method but my input stream becomes empty for the new method
I verified this by using nextLine() both in the main() method and reverse() method as shown
public static void main (String[] args) {
int t,n;
String x,y,z;
t=scan.nextInt();
x=scan.nextLine();
n=scan.nextInt(); //to eat up the n input
y=scan.nextLine();
z=scan.nextLine();
System.out.println(x+y);
....
}
output-
141 2 3 4
and
public void reverse(int n){
....
String k,j;
k = scan.nextLine(); //replacing n- to check what n=scanInt() reads
j= scan.nextLine();
System.out.println(x +y);
....
}
Output is blank again (java.util.NoSuchElementException)
I think this means the input stream is empty for the reverse() method.
So how do I pass on the main() input to reverse()
Note: 1. if I don't use try{} and catch{} it gives me java.util.NoSuchElementException
I'm aware I have made the code needlessly a little complicated, this is due to me trying to solve this problem
I got the try{} and catch{} solution from here, but it doesn't solve my empty input problem
4.This made me understand the empty input exception
Create a method instead of making an Object of a class and then calling the method. (Unless you want it that way).
Create a single static Scanner and use it everywhere.
private static Scanner scanner = new Scanner(System.in)
To print an array use System.out.println(Arrays.toString(a));.
Reductant use of scanner.nextLine() after Scanner.nextInt.
import java.util.Arrays;
import java.util.Scanner;
class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int i, t, n;
String x, y;
t = scanner.nextInt();
for (i = 0; i < t; i++) {
reverse();
}
}
private static void reverse() {
int i;
int[] a;
int n;
n = scanner.nextInt();
a = new int[n];
for (i = n - 1; i >= 0; i--) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(a));
}
}
Is this your desired output?
This code is working for the first scanner to accept ints but the second scanner throws a mismatch error. I cannot seem to find why it is doing this. Can anyone help me out?
I have tried everything and it is not working. I can get the first scanner to accept strings multiple times. The second scanner will accept ints but if i try to input a string even one time then the program crashes. How can this be resolved?
For more details of full program click here:
pastebin.com/iMgNncMH
Password: ENdu4mWLNm
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter two integers:");
while (!scanner.hasNextInt()) {
scanner.next();
}
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
System.out.println();
I looked through the code, and it is working fine on BlueJ Here is the console image. Could you explain a little more about what error you are getting while compilation? Also here's the full code
import java.util.*;
public class prime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter two integers:");
while (!scanner.hasNextInt()) {
scanner.next();
}
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
System.out.println();
}
}
}
The error being thrown is InputMismatchException. Its happening on the n2 why this is happening... idk I'm about as surprised as you are. Weird how it doesn't throw on n1 its the same issue. Perhaps it has something to do with the next int your looking for. Here's what I would suggest. Basic error handling using a Boolean while loop. If the catch is thrown it will never hit that true so two integers must be entered.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = 0;
int n2 = 0;
System.out.println("Enter two integers:");
boolean validEntry = false;
while(!validEntry) {
try {
n1 = scanner.nextInt();
n2 = scanner.nextInt();
validEntry = true;
}
catch(InputMismatchException ex){
System.out.println("Please refrain from entering words. only numbers aloud");
scanner.nextLine();
}
}
}
Ps that other while loop you had is never hit. I can see what you were going for though.
I am trying to write a code where you sort a given list of numbers, and I'm trying to do so using ArrayList. I am using a while loop to allow for repeated inputs. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class sortinggg {
public static Scanner keyboard = new Scanner(System.in);
public static ArrayList<Integer> number = new ArrayList<Integer>();
public static void main (String [] args) {
int count= 0;
System.out.println("Enter your numbers.");
while (keyboard.hasNextInt()); {
number.add(keyboard.nextInt());
}
The integer count is irrelevant right now, as I only use it when I am sorting the list.
The problem is that after I input my numbers, even if I type in a string (for example), the program doesn't move on to the next line of code. Am i missing anything here?
P.S. I tired looking up questions that have been asked previously on this topic, but none of the solutions suggested worked for me.Thank you for your help in advance!
Try this:
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
System.out.println("Enter your numbers:");
while (keyboard.hasNextInt()) {
number.add(keyboard.nextInt());
}
}
}
Modifications:
In while (keyboard.hasNextInt()); remove semicolon(;) at the end.
Here while loop will keep adding values to the arraylist until you provide int values.
In the first place the ; just after the while is wrong. It does not let you to execute the body. Then how are you going to skip the loop. You may ask the end user to enter some special value and use it to break the loop. The corrected version is given below.
public static void main(String[] args) {
int count = 0;
System.out.println("Enter your numbers or -1 to skip.");
while (keyboard.hasNextInt()) {
int num = keyboard.nextInt();
if (num == -1) {
break;
}
number.add(num);
}
System.out.println(number);
}
Can I get this problem of Terminated due to time out solved?
I mean how to reduce the complexity or unwanted code in order to solve the issue?
Here is my code:
public class Solution {
public static void main(String[] args) {
int i,n,hit,count=0,p=0,t,tmp,j;
int h[]=new int[100000];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
hit=sc.nextInt();
t=sc.nextInt();
for(i=0;i<n;i++){
h[i]=sc.nextInt();
}
for(i=0;i<n;i++){
for(j=i;j<n;j++){
if(h[i]>h[j]){
tmp=h[i];
h[i]=h[j];
h[j]=tmp;
}
}
}
for(i=1;i<=t;i++){
h[p]-=hit;
if(h[p]<=0){
count++;
p++;
}
}
System.out.println(count);
}
}
Since I don't know the problem statement, the only thing which I can suggest is to always avoid Bubble Sort. It's complexity is O(n^2), and probably that's what hindering you're time requirement.
Use Arrays.sort like Arrays.sort(h)
The only problem I can see is you need to import the scanner before you can use it. When I ran the code you provided it gave me a timeout because it couldn't locate the scanner, but when I imported the scanner it ran just fine, so I'm assuming that's the same timeout error you're getting. Put this statement at the beginning of your code:
import java.util.Scanner;
The finished code should look like this:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int i,n,hit,count=0,p=0,t,tmp,j;
int h[]=new int[100000];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
hit=sc.nextInt();
t=sc.nextInt();
for(i=0;i<n;i++){
h[i]=sc.nextInt();
}
for(i=0;i<n;i++){
for(j=i;j<n;j++){
if(h[i]>h[j]){
tmp=h[i];
h[i]=h[j];
h[j]=tmp;
}
}
}
for(i=1;i<=t;i++){
h[p]-=hit;
if(h[p]<=0){
count++;
p++;
}
}
System.out.println(count);
}
}
I have used the following code for the question but it keeps giving me NZEC error when I submit it on SPOJ. My code runs perfectly on Eclipse or through cmd.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int line,num,numb,rev = 0,r,i,flag;
ArrayList <Integer> nums=new ArrayList <Integer>();
Scanner b=new Scanner(System.in);
Scanner a=new Scanner(System.in);
line=b.nextInt();
for(i=0;i<line;i++)
{flag=0;
num=a.nextInt();
num=num+1;
numb=num;
do {
while(numb>0)
{r=numb%10;
rev=(rev*10)+r;
numb=numb/10;
}
if (rev==num)
{nums.add(num);
rev=0;
flag=1;
break;
}
else
{num=num+1;
numb=num;
rev=0;}
}while(flag==0);
}
for (int newnum : nums)
{System.out.println(newnum);}
}
}
the mistake that you are doing is that you are storing num in an integer datatype..the constraint says that
K of not more than 1000000 digits(it is digits and not up to that number)
It is impossible for an integer to store such a huge number..so you have to use string to solve this particular problem..try this input in your eclipse
454646546546546546546546464646464646
you will realize where you are wrong