0

Name and age

PLEASE help me ill soon rip my hair of. I made this work then i broke it and now i cant pick up what I did (gaaaaah). HOW do i make this work????????? —————————— String name; System.out.println(“Enter name:”); name = scanner.nextLine(); —————————— ISSUE: FALSE: System.out.println(“not a valid name, try again: ”) Loop until valid input^ Valid option (only string nothing else) it shall print: TRUE: System.out.println(“welcome ” + name); result of valid input^ then continue: —————————— Int age; System.out.println(“Enter age:”); age = scanner.nextInt(); TRUE: System.out.println(“Your age is ” + age); —————————— ONLY VALID AGE INPUT: 0-120 (int)otherwise loop until valid input.

14th Oct 2020, 8:13 PM
Felicia Olsson
2 RĂ©ponses
+ 4
Did you import the Scanner? import java.util.Scanner; Scanner scan = new Scanner(System.in); System.out.println("Enter name:"); String name = scan.nextLine(); System.out.println("Enter age:"); int age = scan.nextInt(); System.out.println("Your name is " + name); System.out.println("Your age is " + age); Here on sololearn you need to enter all the input at the beginning: name [enter] age Then it should work.
14th Oct 2020, 8:24 PM
Denise Roßberg
Denise Roßberg - avatar
0
Hejsan sĂ„g att du ocksĂ„ Ă€r svensk :) om jag förstog dig rĂ€tt sĂ„ Ă€r de nĂ„got i denna stil du e ute efter System.out.println("Enter name:"); String name = scanner.nextLine(); // GĂ„r in i en loop dĂ€r de bara tillĂ„ts stora och smĂ„ bokstĂ€ver frĂ„n // a till z. Skriver anvĂ€ndaren nĂ„got annat kommer den fortsĂ€tta loopa. while( !name.matches("[a-z A-Z]+") ) { System.out.println("Not a valid name, try again: "); name = scanner.nextLine(); } System.out.println("Welcome " + name); while(true) { try { System.out.println("Enter age:"); int age = scanner.nextInt(); // Vi kollar att anvĂ€ndaren Ă€r yngre eller prick 120 // Är han de sĂ„ skriver vi ut Ă„ldern och bryter oss ut frĂ„n loopen if(age <= 120) { System.out.println("Your age is: " + age); break; } else { System.out.println("Not a valid age, try again: "); } } catch(InputMismatchException e) { System.out.println("Something went wrong.. Try again:"); scanner.next(); } } Ovanför anvĂ€nder vi en try-catch block om anvĂ€ndaren skulle skriva in bokstĂ€ver eller allt för stort nummer. Du behöver inte ha try-catch block men skulle anvĂ€ndaren skriva in nĂ„got som typ allt för stort nummer sĂ„ kommer programmet att krascha, sĂ„ de Ă€r bĂ€ttre att fĂ„nga felet och skriva ut va som hĂ€nde för att sedan kunna hoppa tillbaka till loopens början. Och glöm inte att importera Scanner klassen som ligger i util paketet: import java.util.Scanner; Bara frĂ„ga om du behöver hjĂ€lp.
15th Oct 2020, 9:51 PM
JavaBobbo
JavaBobbo - avatar