java - specifiing Int as input with Scanner - java

i have a function to read user input. it takes a parameter to choose reading Ints or Strings. When i try to make sure that it reads only Ints with while(!sc.hasNextInt()) it works, but only when i step it in debug mode. whenever i try to use it while program is running it throws an exception regardless of input being a number or characters.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Databaz.ctecka(Databaz.java:14)
at Databaz.main(Databaz.java:38)
this points me to sc.next(); line in my function:
static String ctecka(int volba)
{
Scanner sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next(); //this is where exception points
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
sc.close();
return vystup;
}
function is being used from code:
int volba = Integer.parseInt(ctecka(1)); //it returns String so i parse it

That happens because you close your scanner sc.close(); which closes your inputStream then you try to access it again (have a look here), so to solve your problem, generalize your scanner variable, and then close it only when you finish all the ctecka() method calls, like the following:
Scanner sc;
private void some_method(){
int volba1 = Integer.parseInt(ctecka(1));
int volba2 = Integer.parseInt(ctecka(1));
int volba3 = Integer.parseInt(ctecka(2));
int volba4 = Integer.parseInt(ctecka(3));
sc.close();
}
String ctecka(int volba){
sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next();
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
return vystup;
}

Related

Java scanner test for empty line

I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.

Putting the while condition from system input is not working

In the main method I am reading the input from system.in and passing it to while condition. But it is not working. Each time it takes default 53 cases. Could not figure out where is the mistake.
If I manually assign int num = 15 instead of int num = br.read() just above the while loop. It works fine.
public class Parenthesis
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int num = br.read();
while(num > 0)
{
System.out.println(num-- + "Chances Left");
String str = br.readLine();
if(isParenthesis(str))
System.out.println("Cool Rudra");
else
System.out.println("Poor Rudra");
}
}
public static boolean isParenthesis(String str)
{
if(str == "Rudra")
return true;
else
return false;
}
}
Use below
int num = Integer.parseInt(br.readLine());
instead of
int num = br.read();
Another way to get intfrom user
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();

How to take space separated input in Java using BufferedReader?

How to take space separated input in Java using BufferedReader?
Please change the code accordingly, i wanted the values of a, b, n as space seperated integers and then I want to hit Enter after every test cases.
Which means first i'll input the number of test cases then i'll press the Enter key. Then i input the vale of a then i'll press Space, b then again Space then i'll input the value of n, then i'll press the Enter key for the input for the next testcase.
I know that this can be done easily through Scanner but i don't wanna use it because it throws TLE(Time Limit Extended) error on online judges.
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
int testCases = Integer.parseInt(inputString);
double a,b,n,j,t=1;
int i;
int ans [] = new int[testCases];
for(i=0;i<testCases;i++)
{
inputString = br.readLine();
a = Double.parseDouble(inputString);
inputString = br.readLine();
b = Double.parseDouble(inputString);
inputString = br.readLine();
n = Double.parseDouble(inputString);
for(j=0;j<n;j++)
{
if(t==1)
{
a*=2;
t=0;
}
else if(t==0)
{
b*=2;
t=1;
}
}
if(a>b)
ans[i]=(int)(a/b);
else
ans[i]=(int)(b/a);
t=1;
}
for(i=0;i<testCases;i++)
System.out.println(ans[i]);
}catch(Exception e)
{
return;
}
}
First read the number of input lines to be read.
Then parse each line and get the String.
Though I have not added the NumberFormatException handling, but it's a good idea to have that.
Change your for loop like this:
for(i=0;i<testCases;i++){
inputString = br.readLine();
String input[] = inputString.split("\\s+");
a = Double.parseDouble(input[0]);
inputString = br.readLine();
b = Double.parseDouble(input[1]);
inputString = br.readLine();
n = Double.parseDouble(input[2]);
for(j=0;j<n;j++){
if(t==1){
a*=2;
t=0;
}else if(t==0){
b*=2;
t=1;
}
}
if(a>b){
ans[i]=(int)(a/b);
}else{
ans[i]=(int)(b/a);
t=1;
}
}

Runtime Exception- feature not implemented yet

The following block of code showing this error "Runtime Exception- feature not implemented yet" in jelliot, when it reaches the line
char arr [] = w.toCharArray();
And in other compilers,it won't take the number of input it's supposed to take. If I set n=4, it only takes 2 inputs.
Scanner Sc = new Scanner (System.in);
int n = Sc.nextInt();
for(int count = 1;count<=n; count++){
String w = Sc.nextLine();
char arr [] = w.toCharArray();
if(arr.length > 4){
System.out.print(arr[0]);
System.out.print(arr.length-2);
System.out.print(arr[arr.length-1]);
}
else{
System.out.println(w);
}
System.out.println();
}
The exception indicates that this particular method (toCharArray()) of the String class isn't implemented for the (presumably non-standard) implementation of java that you're using. You can work around this by not using a char array, and instead using the String methods length() and charAt(). Try this:
Scanner Sc = new Scanner (System.in);
int n = Sc.nextInt();
for(int count = 1;count<=n; count++){
String w = Sc.nextLine();
if(w.length() > 4){
System.out.print(w.charAt(0));
System.out.print(w.length()-2);
System.out.print(w.chatAt(w.length()-1));
}
else{
System.out.println(w);
}
System.out.println();
}

How is my String Index Out of Bounds?

GOAL: To ask user for # of points. Then user will input "1 4", where 1 is the x and 4 is the y. I will take the sub-string to get 1 and 4 separately then make them an int so I can make them a Point.
I keep getting "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
this is taking place on line 25, but not 24. When I use 3 instead of the length it also gives me this error.
This is a fragment of code:
public String run() {
String line = "";
String first = "";
String second = "";
int j = 0; int n = 0;
System.out.println("How many inputs do you want to enter?");
Scanner sc = new Scanner(System.in);
while(j == 0){
if(sc.hasNextInt()){
n = sc.nextInt();
Point[] points = new Point[n];
sc.close();
j++;
}
else {
System.out.println("invalid input");
}
}
Scanner scan = new Scanner(System.in);
for(int i = 0; i <= n; i++){
System.out.println("Enter x and y:");
line = scan.next();
first = line.substring(0,1);
second = line.substring(2,line.length());
}
scan.close();
origin(points);
return "";
}
See if this works for you. I'm not sure what your j variable was doing, your for-loop for the points was going out of bounds on the array, you are closing System.in between two separate Scanners, and obviously something wrong is happening with your substring logic.
This code fixes all those problems and runs great for me.
public String run() {
Scanner sc = new Scanner(System.in);
int n = numberPrompt("How many inputs do you want to enter?\n", "Invalid input");
Point[] points = new Point[n];
for(int i = 0; i < n; i++){
System.out.println("Enter x and y:");
String line = sc.nextLine();
String[] data = line.split("\\s+");
if (data.length >= 2)
{
int x = Integer.parseInt(data[0]);
int y = Integer.parseInt(data[1]);
points[i] = new Point(x, y);
}
}
System.out.println(Arrays.asList(points));
origin(points);
return "";
}
private int numberPrompt(String prompt, String error) {
Integer number = null;
boolean isValid;
String input;
Scanner sc = new Scanner(System.in);
do {
isValid = true; // reset the validity
System.out.print(prompt);
input = sc.nextLine();
try {
number = Integer.parseInt(input);
} catch (NumberFormatException e) {
isValid = false;
if (!(error == null || error.isEmpty())) {
System.out.println(error);
}
}
} while (!isValid);
return number;
}

Categories

Resources