0

whats wrong?

my goal is to prevent the user from writing an Integer, i want the input to be a String. how can i make it work? i used a method called "hasNextInt" that i found online and it doesnt do the work, or i just messed up somewhere... https://code.sololearn.com/cb83Fx9EvB2k

6th Jun 2020, 11:12 AM
Yahel
Yahel - avatar
4 Antworten
+ 1
yahel hasNextInt() and hasNextLine() are a method of Scanner class. You can't apply on String. So here x.hasNextInt() and x.hasNextLine() are Wrong. Here should be scan.hasNextInt() and scan.hasNextLine()
6th Jun 2020, 11:54 AM
A͢J
A͢J - avatar
+ 1
yahel Yes you will have to use 2 scanner, 1st for input and 2nd for to do operation on that input value. So you can do like this. Scanner scan = new Scanner (System.in); String name = scan.nextLine(); Scanner sc = new Scanner(name); if (sc.hasNextInt()) { System.out.println("error - write a String, not an integer"); } but here if statement will work on only input like 123456. It will not work on dgdgg233 because hasNextInt check on each iteration so here while loop will work.
6th Jun 2020, 12:23 PM
A͢J
A͢J - avatar
0
AJ Anant , i did that and now i have 2 Scanners. meaning that the program forces me to write 2 inputs... how can i fix that? code: import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.println("Whats your name ?"); Scanner scan = new Scanner (System.in); String x = scan.nextLine(); x = x.substring (0 , 1).toUpperCase() + x.substring (1); if (scan.hasNextInt()){ System.out.println("error - write a String, not an integer"); }else if (scan.hasNextLine() && x.equals ("Yahel") || x.equals ("John")){ System.out.println("You are welcome , " + x); }else if (scan.hasNextLine() && x != ("Yahel") || x != ("John")){ System.out.println("Go away , " + x); }else{ System.out.println("Error"); } } }
6th Jun 2020, 12:05 PM
Yahel
Yahel - avatar
0
so is there a simpler way to prevent user from writing numbers?
6th Jun 2020, 4:17 PM
Yahel
Yahel - avatar