All menu options work besides menu option 1 when i select 1 it just repeats the menu instead of asking me to type the name and repeat it 20 time, if anyone can help me debug I would appreciate it.
Get the user’s first name and echo it back out 20 times.
Get the Store user’s age and double it and display the age and the doubled age.
Using the age from #2 output one of the following statements.Since you are 99 years old, you are a teenagerb. Since you are 99 years old, you are NOT a teenager
Get a single integer between 3 and 50 from the user. Create a triangle of X’s with the integer inputted rows. The triangle needs to be displayed on the screen and in a text document named triangle.txt.
The code :
//Menu.java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n::MENU::");
System.out.println("1.Echo Name");
System.out.println("2.Double Your Age");
System.out.println("3.Check Teenager or not");
System.out.println("4.Display Triangle");
System.out.println("5.Exit");
System.out.print("Enter Choice:");
choice = sc.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter your name");
String name = sc.nextLine();
for (int i = 1; i <= 20; i++) {
System.out.println(name);
}
break;
}
case 2: {
int age;
System.out.print("Enter age :");
age = sc.nextInt();
System.out.println("Your age :" + age);
System.out.println("Doubled age :" + (2 * age));
break;
}
case 3: {
int age;
System.out.print("Enter age :");
age = sc.nextInt();
if (age >= 13 && age <= 19) {
System.out.println("Since you are " + age + " years old.Your are a Teenager");
} else {
System.out.println("Since you are " + age + " years old.Your are not a Teenager");
}
break;
}
case 4: {
int rows;
do {
System.out.print("Enter a number (between 3 and 50):");
rows = sc.nextInt();
if (rows < 3 || rows > 50) {
System.out.println("** Invalid.Must be between 3 and 50 **");
}
} while (rows < 3 || rows > 50);
printTriangle(rows);
break;
}
case 5: {
break;
}
default: {
System.out.println("** Invalid Choice **");
break;
}
}
} while (choice != 5);
}
private static void printTriangle(int size) {
char ch = '*';
for (int a = 0; a < 2 * size - 1; a++) {
if (a % 2 == 0) {
for (int b = 0; b < (2 * size - 1) - a; b++) {
System.out.print(" ");
}
for (int c = 0; c <= a; c++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
}
After taking input for choice you have to write sc.nextLine() like
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
because nextInt() only reads in until it's found the int and then stops.
You have to do nextLine() because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine() reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.
To read both strings and integer value, a solution is to use two Scanners:
//Menu.java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner intScanner = new Scanner(System.in);
//added new separate scanner for string
Scanner stringScanner = new Scanner(System.in);
int choice;
do {
int age;
System.out.println("\n::MENU::");
System.out.println("1.Echo Name");
System.out.println("2.Double Your Age");
System.out.println("3.Check Teenager or not");
System.out.println("4.Display Triangle");
System.out.println("5.Exit");
System.out.print("Enter Choice: ");
choice = intScanner.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter your name: ");
String name = stringScanner.nextLine();
for (int i = 1; i <= 20; i++) {
System.out.println(name);
}
break;
}
case 2: {
System.out.print("Enter age :");
age = intScanner.nextInt();
System.out.println("Your age :" + age);
System.out.println("Doubled age :" + (2 * age));
break;
}
case 3: {
System.out.print("Enter age :");
age = intScanner.nextInt();
if (age >= 13 && age <= 19) {
System.out.println("Since you are " + age + " years old.Your are a Teenager");
} else {
System.out.println("Since you are " + age + " years old.Your are not a Teenager");
}
break;
}
case 4: {
int rows;
do {
System.out.print("Enter a number (between 3 and 50):");
rows = intScanner.nextInt();
if (rows < 3 || rows > 50) {
System.out.println("** Invalid.Must be between 3 and 50 **");
}
} while (rows < 3 || rows > 50);
printTriangle(rows);
break;
}
case 5: {
System.out.println("You pressed Exit");
break;
}
default: {
System.out.println("** Invalid Choice **");
break;
}
}
} while (choice != 5);
}
private static void printTriangle(int size) {
char ch = '*';
for (int a = 0; a < 2 * size - 1; a++) {
if (a % 2 == 0) {
for (int b = 0; b < (2 * size - 1) - a; b++) {
System.out.print(" ");
}
for (int c = 0; c <= a; c++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
}
Related
I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}
I have an application that acts as a gradebook. However, in the console log when I type in a grade there seems to be an error. I was hoping someone could fix this to where I am able to put in a grade percentage and the error does not pop up.enter code here
Below is what the error says:java.lang.NumberFormatException: For input string: "70%"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Gradebook.getScores(Gradebook.java:45)
at Gradebook.main(Gradebook.java:154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is my code:
import java.util.Scanner;
public class Gradebook {
//getNumStudents takes a Scanner object as parameter
//the reader object lets us take user input
public static int getNumStudents(Scanner reader){
int numStudents = 0;
//we get the number of students
do{
System.out.print("Enter number of students: ");
numStudents = Integer.parseInt(reader.nextLine());
//we determine if the user input is valid
//it should be greater than 0
//because we don't want the number o students to be negative
//if it is not valid then we keep taking inputs
if(numStudents > 0){
break;
}else{
System.out.println("Please enter atleast 1 student.");
}
}while(true);
System.out.println("================================================================================================================================================");
//we return numStudents
return numStudents;
}
//getScores takes our Scanner object again and the number student as parameter this time
public static String[] getScores(Scanner reader, int numStudents){
//we create an array of string studInfo
//that will be returned containing the name, and scores of our students
String[] studInfo = new String[numStudents];
String name = "";
int quiz = 0;
int assign = 0;
int test1 = 0;
int test2 = 0;
//we use a for loop to keep taking student scores
for(int i = 0; i < numStudents; i++){
//enter name
System.out.print("Enter student "+(i+1)+" name: ");
name = reader.nextLine();
//enter quiz, assignment, test1 and test2 scores
//we also validate scores to not be negative
//and not out of bounds
do{
System.out.print("Enter Quiz Score (over 40): ");
quiz = Integer.parseInt(reader.nextLine());
if(quiz >= 0 && quiz <= 40){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Assignment Score (over 30): ");
assign = Integer.parseInt(reader.nextLine());
if(assign >= 0 && assign <= 30){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Midterm Test Score (over 55): ");
test1 = Integer.parseInt(reader.nextLine());
if(test1 >= 0 && test1 <= 55){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Final Test Score (over 65): ");
test2 = Integer.parseInt(reader.nextLine());
if(test2 >= 0 && test2 <= 65){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
//after we get the name and student's score
//we put it in a string
studInfo[i] = name+ " " +quiz+ " " +assign+ " " +test1+ " " +test2;
System.out.println();
}
//return the studInfo
return studInfo;
}
//our displayGrade takes String array as parameter
public static void displayGrade(String[] studInfo){
//this is our header for our formatted table
System.out.println("================================================================================================================================================");
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10s%-15s%s", "Name", "Quiz", "Assignment", "Midterm Test", "Final Test", "Average", "Letter Grade", "Status"));
System.out.println("================================================================================================================================================");
//we go through our array of string
for(int i = 0; i < studInfo.length; i++){
//the split method returns an array of strings
//that are split by a delimeter
String[] data = studInfo[i].split(" ");
//we sum up the scores
//but we have to parse it to double first
//to get the closest sum
double sum = ((Double.parseDouble(data[1]) / 40.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[2]) / 30.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[3]) / 55.0) * 100.0) * 0.3;
sum += ((Double.parseDouble(data[4]) / 65.0) * 100.0) * 0.4;
//after that we round the sum and convert it to int and put it in average
int average = (int) Math.round(sum);
char letterGrade = ' ';
//we get the letter grade using a nested if else
if(average>=0 && average<=59){
letterGrade = 'F';
}else if(average>=60 && average<=69){
letterGrade = 'D';
}else if(average>=70 && average<=79){
letterGrade = 'C';
}else if(average>=80 && average<=89){
letterGrade = 'B';
}else if(average>=90 && average<=100){
letterGrade = 'A';
}
String status = "";
//we determine the status of our student here
//using switch case
//if the leter grade is f then he fails
//if the case is D then he needs to go to remedial class
//otherwise they pass
switch(letterGrade){
case 'F':
status = "Fail";
break;
case 'D':
status = "Remedial";
break;
case 'A': case 'B': case 'C':
status = "Pass";
break;
}
//we displat student information
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10d%-15c%s", data[0], data[1], data[2], data[3], data[4], average, letterGrade, status));
}
System.out.println("================================================================================================================================================");
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
displayGrade(getScores(reader, getNumStudents(reader)));
}
}
Instead of nextLine() you can use next("[0-9]+%?") and then remove the optional % character:
public static int getNumStudents(Scanner reader) {
int numStudents = 0;
//we get the number of students
do {
System.out.print("Enter number of students: ");
// Read the number either with or without the % sign
String input = reader.next("[0-9]+%?");
if (input.endsWith("%")) {
// Remove the % sign if present
input = input.substring(0, input.length() - 1);
}
numStudents = Integer.parseInt(input);
// we determine if the user input is valid
// it should be greater than 0
// because we don't want the number o students to be negative
// if it is not valid then we keep taking inputs
if (numStudents > 0) {
break;
}
System.out.println("Please enter at least 1 student.");
} while (true);
System.out.println("================================================================================================================================================");
// we return numStudents
return numStudents;
}
I am having trouble on a program and I can't seem to fix the problem. I have a team roster program that gives the option of replacing a player's number and rating, but when that option is used the loop keeps going and it won't end and go back to the menu for the other options. If anyone could help point me in the right direction it would be appreciated.
import java.util.Scanner;
class PlayerRoster {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int[] playerJerseyNumber = new int[5];
int[] playerRating = new int[5];
for (int i = 0; i < 5; i++) {
//Taking jersey number till it is in the range of 0-99
while (true) {
System.out.println("Enter player " + (i + 1)
+ "'s jersey number:");
playerJerseyNumber[i] = scanner.nextInt();
if (0 <= playerJerseyNumber[i] && playerJerseyNumber[i] <= 99) {
break;
} else {
System.out.println("Jersey number must be 0-99");
}
}
//Taking playerRating till it is in the range of 1-9
while (true) {
System.out.println("Enter player " + (i + 1) + "'s rating:");
playerRating[i] = scanner.nextInt();
if (1 <= playerRating[i] && playerRating[i] <= 9) {
break;
} else {
System.out.println("Player's ratings must be 1-9");
}
}
System.out.println("");
}
System.out.println("ROSTER");
//Displaying the rosters
for (int i = 0; i < 5; i++) {
System.out.println("Player " + (i + 1) + " -- Jersey number: "
+ playerJerseyNumber[i] + ", Rating: "
+ playerRating[i]);
}
System.out.println("");
//Printing the menu
do {
System.out.println("MENU " + "u - Update player rating");
System.out.println("a - Output players above a rating");
System.out.println("r - Replace player");
System.out.println("o - Output roster");
System.out.println("q - Quit");
System.out.println("");
System.out.println("Choose an option:");
char choice = scanner.next().charAt(0);
switch (choice) {
case 'u': {
System.out.println("Enter a jersey number:");
int playerJersey = scanner.nextInt();
System.out.println("Enter a new rating for player:");
int newRating = scanner.nextInt();
for (int i = 0; i < 5; i++) {
if (playerJerseyNumber[i] == playerJersey) {
playerRating[i] = newRating;
break;
}
}
}
break;
case 'a': {
System.out.println("Enter a rating:");
int aboveRating = scanner.nextInt();
System.out.println("ABOVE " + aboveRating);
for (int i = 0; i < 5; i++) {
if (playerRating[i] > aboveRating) {
System.out.println("Player " + (i + 1)
+ " -- Jersey number: "
+ playerJerseyNumber[i] + ", Rating: "
+ playerRating[i]);
}
}
}
break;
case 'r': {
boolean flag = true;
do {
System.out.println("Enter a jersey number:");
int newRating, playerNewJersey;
int playerJersey = scanner.nextInt();
for (int i = 0; i < 5; i++) {
if ((playerJerseyNumber[i] == playerJersey)) {
//Taking jersey number till it is in the range of 0-99
while (true) {
System.out.println("Enter a new jersey number:");
playerNewJersey = scanner.nextInt();
if (0 <= playerNewJersey && playerNewJersey <= 99) {
break;
} else {
System.out.println("Jersey number must be 0-99");
}
}
//Taking playerRating till it is in the range of 1-9
while (true) {
System.out.println("Enter a new rating for player:");
newRating = scanner.nextInt();
if (1 <= newRating && newRating <= 9) {
break;
} else {
System.out.println("Player's ratings must be 1-9");
}
}
playerJerseyNumber[i] = playerNewJersey;
playerJerseyNumber[i] = playerJersey;
playerRating[i] = newRating;
flag = false;
break;
}
}
if (!flag) {
System.out.println("Error: Invalid Jersey Number... Try Again...");
}
} while (flag);
}
break;
case 'o': {
System.out.println("ROSTER");
for (int i = 0; i < 5; i++) {
System.out.println("Player " + (i + 1)
+ " -- Jersey number: " + playerJerseyNumber[i]
+ ", Rating: " + playerRating[i]);
}
}
break;
case 'q':
break;
default:
break;
}
if (choice == 'q') break;
} while (true);
} catch (Exception e) {
}
return;
}
}
if (flag) {
System.out.println("Error: Invalid Jersey Number... Try Again...");
} }
Removing the ! solves the problem. Also, a few lines above it there is
playerJerseyNumber[i] = playerNewJersey;
playerJerseyNumber[i] = playerJersey;
I don't understand why you need to reassign it to playerJersey. This would cause the jersey number to not get updated.
The Java program for my school work gives me an error:
Welcome to Surinam Airlines - We may get you there!
We have 6 seats available for flight JAVA123.
How many seats do you want to book? 3
Enter passenger #1's name: Taylor Swift
Enter passenger #1's food option
(V = vegetarian, N = no preference, H = Halal): V
Enter passenger #1's class (1 = first, 2 = business, 3 = economy): 1
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown source)
at Passenger.enterPassenger(Passenger.java:64)
at RunAirLine.main(RunAirLine.java:23)
It seems to have something to do with the object not being instantiated though I can't quite figure out why. Does anyone know what's wrong?
import java.util.*;
public class RunAirLine {
private static Passenger seatArray[][] = new Passenger[2][3]; // declares new
// array of
// Passengers
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Surinam Airlines – We may get you there!");
System.out.println();
int seats = 6; // available seats
while (seats > 0) {
System.out.println("We have " + seats
+ " seats available for flight JAVA123.");
System.out.println();
System.out.print("How many seats do you want to book? ");
int n = kb.nextInt();
System.out.println();
for (int i = 0; i < n; i++) {
int x = emptySeat()[0];
int y = emptySeat()[1];
// retrieves info from emptySeat() function
seatArray[x][y] = new Passenger();
seatArray[x][y].enterPassenger(7 - seats); // gives the method the nth
// passenger number
seats--; // takes away 1 from the available seats
}
System.out.println();
}
System.out.println("No seats available.");
System.out.println();
System.out.println("Flight manifest:");
System.out.println();
for (int y = 0; y < 3; y++) { // prints out the list of flyers
for (int x = 0; x < 2; x++) {
System.out.println(seatArray[x][y].getSeat() + " "
+ seatArray[x][y].printPassengerCode());
}
}
kb.close();
}
public static int[] emptySeat() {
for (int y = 0; y < 3; y++) {// finds the next empty seat
for (int x = 0; x < 2; x++) {
if (seatArray[x][y] == null || seatArray[x][y].getSeat().equals("")) {
// if the spot hasn't been declared yet or is empty
return new int[] { x, y };
}
}
}
return null; // if none found then return null
}
}
Passenger.java
import java.util.*;
public class Passenger {
private String name;
private String seat;
private char foodOption;
private int seatClass;
// reduces some redundancy
private String classStr;
private String prefStr;
public Passenger() { // constructors
name = "";
seat = "";
foodOption = ' ';
seatClass = -1;
}
public Passenger(String n, String s, char f, int sc) { // assigns values
// according to input
name = n;
seat = s;
foodOption = f;
seatClass = sc;
}
// get and set methods
public void setName(String n) {
name = n;
}
public void setSeat(String s) {
seat = s;
}
public void setFoodOption(char f) {
foodOption = f;
}
public void setSeatClass(int sc) {
seatClass = sc;
}
public String getName() {
return name;
}
public String getSeat() {
return seat;
}
public char getFoodOption() {
return foodOption;
}
public int getSeatClass() {
return seatClass;
}
// end of get and set methods
public void enterPassenger(int i) {
Scanner kb = new Scanner(System.in);
// asks the important questions
System.out.print("Enter passenger #" + i + "’s name: ");
name = kb.nextLine();
System.out.println("Enter passenger #" + i + "’s food option ");
System.out.print("(V = vegetarian, N = no preference, H = Halal): ");
foodOption = kb.nextLine().toUpperCase().charAt(0);
System.out.print("Enter passenger #" + i
+ "’s class (1 = first, 2 = business, 3 = economy): ");
seatClass = kb.nextInt();
System.out.println();
char seatChar = 'A'; // calculates the seat number
if (i % 2 == 0)
seatChar = 'B';
seat = Integer.toString(i / 2 + i % 2) + seatChar;
classStr = "Economy Class"; // transfers the class choice int into string
switch (seatClass) {
case 1:
classStr = "First Class";
break;
case 2:
classStr = "Business Class";
break;
}
prefStr = "No preference"; // transfers the preference char into string
switch (foodOption) {
case 'V':
prefStr = "Vegetarian";
break;
case 'H':
prefStr = "Halal";
break;
}
System.out.println("Done – Seat " + seat + " booked");
System.out
.println("-------------------------------------------------------------------");
System.out.println(name + "(" + classStr + " - Seat " + seat + ") - "
+ prefStr);
System.out
.println("-------------------------------------------------------------------");
kb.close();
}
public void printTicketStub() {
char initial = name.split(" ")[0].toUpperCase().charAt(0); // splits name
// into first
// name and
// second name
System.out.println(initial + ". " + name.split(" ")[1] + "(" + classStr
+ " - Seat " + seat + ") - " + prefStr);
}
public String printPassengerCode() { // forms the code as required
return seatClass + name.toUpperCase().substring(name.length() - 4)
+ foodOption;
}
}
You have two problems:
You create a Scanner for System.in twice. You should only do this once. I have commented out the one you create in Passenger.java, and changed the reference to the one in RunAirLine.java:
public void enterPassenger(int i) {
// Scanner kb = new Scanner(System.in);
// asks the important questions
System.out.print("Enter passenger #" + i + "’s name: ");
name = RunAirLine.kb.nextLine();
System.out.println("Enter passenger #" + i + "’s food option ");
System.out.print("(V = vegetarian, N = no preference, H = Halal): ");
foodOption = RunAirLine.kb.nextLine().toUpperCase().charAt(0);
System.out.print("Enter passenger #" + i
+ "’s class (1 = first, 2 = business, 3 = economy): ");
seatClass = RunAirLine.kb.nextInt();
RunAirLine.kb.nextLine();
Every time you do nextInt(), it doesn't take the new line off the Scanner's reading, which messes stuff up. If you want nextInt() to be on it's own line, you should throw a dummy RunAirLine.kb.nextLine(); after the nextInt() call. This needs to be done twice, once in the code I've fixed above, and once in your RunAirLine.class:
System.out.print("How many seats do you want to book? ");
int n = kb.nextInt();
kb.nextLine();
System.out.println();
Further reading on Why you shouldn't have multiple Scanners. the tl;dr of is that closing System.in closes the stream forever.
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.