+ 1

i h've this code in java is for print name, i want to print name and age when is > 17 and < 46 using if else but dont work.

import java.util.Scanner ; public class Program { public static void main(String[] args) { System.out.println("Write your name:"); Scanner name = new Scanner(System.in); // System.out.println(name.nextLine()); System.out.println("Write your age:"); Scanner age = new Scanner(System.in); // System.out.println(age.nextInt()); System.out.println("Write your civil_state"); Scanner civil_state = new Scanner(System.in); // System.out.println(civil_state.nextLine()); if(age > 17 && age<46){ System.out.println(name.nextLine()); System.out.println(age.nextInt()); System.out.println(civil_state.nextLine()); } else { System.out.println("Your age is not accepted"); } } }

27th Jun 2019, 7:31 PM
Edwin Boada
Edwin Boada - avatar
6 Réponses
+ 2
It's because you are trying to compare an integer to a scanner. your "age" variable shouldn't be a scanner, but the scanners nextInt
27th Jun 2019, 7:40 PM
Airree
Airree - avatar
+ 2
No, not like that. firstly, I don't think you need 2 scanners. You could do it like this: Scanner sc = new Scanner(System.in); String name = sc.nextLine(); //Alternatively, if it's only one word, you can use the next() method int age = sc.nextInt();
27th Jun 2019, 8:04 PM
Airree
Airree - avatar
+ 2
But you can get different datatypes with one scanner
27th Jun 2019, 8:12 PM
Airree
Airree - avatar
+ 2
based off what Airree says, you’re just not quite using the Scanner class correctly, this is how you would go about it: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name; int age; String civilState; //get name System.out.println("Write your name:"); name = input.next(); //get age System.out.println("Write your age:"); age = input.nextInt(); //get civil state System.out.println("Write your civil state:"); civilState = input.next(); if(age > 17 && age<46) { System.out.println(name+"\n"+age+"\n"+civilState); } else { System.out.println("Your age is not accepted"); } } }
27th Jun 2019, 8:26 PM
Jake
Jake - avatar
+ 1
how i fix that? any sugesstion? like that for example: Scanner age = newScanner.nextInt(System.in); and thanks Airre
27th Jun 2019, 8:02 PM
Edwin Boada
Edwin Boada - avatar
+ 1
ohhhhhh guauuu, it is not necessary because i have three scanner one for type of data.
27th Jun 2019, 8:11 PM
Edwin Boada
Edwin Boada - avatar