V
V
VorpaBlade2021-04-11 13:40:02
Java
VorpaBlade, 2021-04-11 13:40:02

Java console input. Why can't I enter a string?

package com.company;
import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  int y=in.nextInt();
  float x=in.nextFloat();
  in.next();
  String h=in.nextLine();
  System.out.printf("x = %.3f, y =%d, h=%s \n", x,y, h); 
  in.close();
  }
}


1) After entering numbers, the program closes, and h remains unspecified. Please write the correct version of the program and why the above version does not work?
2) why do you need in.close() in which cases to add in which it is not necessary?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-04-11
Hasanly @azerphoenix

After entering the numbers, the program closes, and h remains unspecified. Please write the correct version of the program and why the above version does not work?

Try like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int y=in.nextInt();
float x=in.nextFloat();
in.nextLine();
String h = in.nextLine();
System.out.printf("x = %.3f, y =%d, h=%s \n", x,y, h);
in.close();
}
}

Here is the answer to your question:
https://stackoverflow.com/questions/13102045/scann...
why do you need in.close() in which cases to add in which it is not necessary?

When the method is called, the scanner is closed. However, since Scanner implements the Closable interface, you can use Scanner with try with resouces and not explicitly call the close() method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question