Array list scanner loop quit functionality - java

import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if (answer.equals("quit")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
}
}
}
The problem with this is that the program is not quitting upon typing Quit but it is continuing and placing two questions on one line, shown below. how can I solve this problem?
Please enter your username: abc123
Please enter the game:
GTA V
Please Enter Achievement Score:
1200
Please Enter Playtime:
120
Any letter to continue alternatively type quit to Quit.Quit
Please enter your username: Please enter the game:

The issue is that you are comparing upper and lower case values of quit. You need to set them to the same case type for them to be equal and quit the program.
change your check to
while (!answer.toLowerCase().equals("quit"));
if (answer.toLowerCase().equals("quit"));
and that will change your input to lowercase which is what your are comparing it to.

I don't see any problem except that you have not closed the scanner. You can run this and you can see that the scanner is closed and go to normal execution after word quit.
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if(answer.equals("quit")){
System.out.println("you have just quit");
scanner.close();
} //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
System.out.print("You are done with scanner");
}
}
}

I just tried your program and it does quit if you type "quit" (all lowercase) like your command line instruction suggest:
System.out.print("Any letter to continue alternatively type quit to Quit.");
If you want your quit instruction to be case-insensitive you should replace this line:
} while (!answer.equals("quit"));
with this:
} while (!answer.equalsIgnoreCase("quit"));
I hope that helped!

Your quit information System.out.print("Any letter to continue alternatively type quit to Quit."); says that you need to put quit all lowercase word to end.
Also change answer = scanner.next(); to answer = scanner.nextLine();
EDIT:
As you don't have any error control you can consider this code:
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(Integer.valueOf(scanner.nextLine()));
System.out.println("Please Enter Playtime: ");
time.add(Integer.valueOf(scanner.nextLine()));
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.nextLine();
} while (!answer.equals("quit"));
I changed scanner.nextInt() to Integer.valueOf(scanner.nextLine()). Using nextLine() helps scanner to flush all data before your code goes to the next line.

Related

java do while asked for input twice

why do I need to input 2 times? please help I'm new to java, can't find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed the do while but it still asks for the second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
I have updated your code. This will work for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output :
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Explanation : If you are giving valid data, then the loop will continue to take inputs (not taking inputs twice). As soon as, you give invalid data, then, the code will prompt you to enter the valid data and loop will stop executing as you made valid = false.
The reason why it asks you for input twice is due to you in.hasNextInt() which will check your scanner for input from the system. Since your system does not have any input due to you calling age = in.nextInt(); which will move the scanner to the next word before your in.hasNextInt(), The function in.hasNextInt() will require you to input something so that it can validate if it is an Int or not.
what we want to do, is to first check the current scanner's input if it has an integer before we either store it inside age or loop again and ask for new input.
A better way of checking would be to do something like this.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = 0;
System.out.println("Enter your age: ");
while(!in.hasNextInt()){// checks if scanner's next input is an int, return true if next input is not an Int and the while loop continues till the next input is an Int
System.out.println("Please enter a valid age: ");
in.nextLine();//move the scanner to receive the next nextLine
//this is important so the hasNextInt() wont keep checking the same thing
}
//it will only exit the while loop when user have successfully enter an interger for the first word they inputted.
age = in.nextInt();
System.out.println("Your age is: " + age);
}
}
Output:
Enter your age:
boy
Please enter a valid age:
boy girl
Please enter a valid age:
5
Your age is: 5
Hi : D there is becuase of the !in.hasNextInt() it will cause you need to do the input again but you can change it to other condition like if the age is bigger than certain value.
public class stackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age =0 ;
boolean valid = false;
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(age>90) {
System.out.println("Please enter a valid age");
valid=true;
}
else valid=false;
}while(valid);
System.out.println("Age: " + age);
}
}
You should move the System.out.println("Enter your age: "); statement outside the do-while loop.

Scanner doesnt read input in else statement

Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).

Read in input text Yes/No Boolean from user to proceed the next step

I amm at my very beginning at java and just wanted to ask.
I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?
import java.util.Scanner;
public class sff {
public static void main (String args[]) {
System.out.println("Hello There! We want to ask you some questions! but first: ");
System.out.print("Enter your age: ");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int age = num;
if( age == 12){
System.out.println("Hello Dan, I know you very well! ");
}
{
System.out.println("First question: ");
System.out.println("Do you exercise?(Yes/No) ");
// how do i proceed from here??
Use Scanner and get next line, then check if that line is yes or no then handle respectively.
In the example below, I used a while loop to keep asking them to input yes or no in case they enter something different like "maybe".
For example:
Scanner in = new Scanner(System.in);
// Loop until they enter either yes or no.
while(true){
String line = in.nextLine();
// Use this to check if it is yes or no
if(line.equalsIgnoreCase("yes")){
// Process yes
break;
}else if(line.equalsIgnoreCase("no")){
// Process no
break;
}else{
// Tell them to enter yes or no since they entered something else.
}
}
Are you looking for something like this?
//import to use the Scanner
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
//get the user input and store it as a String
String exerciseQuestion = in.nextLine();
//check what the user said.
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do you code when he exercises
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}
System.out.println("Ask your next question so on....");
}//main
}//class
If you want to deal with answers other than yes/no you can use this code:
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
String exerciseQuestion;
while (true){
//get the user input
exerciseQuestion = in.nextLine();
//check if user input is yes or no
if((exerciseQuestion.equalsIgnoreCase("yes")) ||
exerciseQuestion.equalsIgnoreCase("no"))
//if yes break and continue with your code
break;
else
//else loop back to get user input until answer is yes/no
System.out.println("Please answer with yes or no only");
}//while . i.e answer not yes or no
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do your code
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}//else
}//main
}//class

How to accept enter as valid input to Scanner.nextLine()?

I just want the scanner to read new line as empty string then continue to next process if the user press enter. So valid input must be y,n,enter. Any idea how to do this?
This is my code:
String gender = "", employed = "";
Scanner in = new Scanner(System.in);
System.out.print("Gender M/F, press enter to skip... ");
while(!in.hasNext("[mfMF]$")){
System.out.print("Invalid, please choose m/f only... ");
in.nextLine();
}
if(in.hasNextLine()){
gender = in.nextLine();
}
System.out.print("Employed? y/n, press enter to skip... ");
while(!in.hasNext("[ynYN]$|")){
System.out.print("Invalid, please choose y/n only... ");
in.nextLine();
}
if(in.hasNextLine()){
employed = in.nextLine();
}
System.out.println(gender + " : " + employed);
Try This :
import java.util.*;
class Scanner1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s;
do
{
s=sc.nextLine();
if(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")))
{
System.out.println("Please Enter valid input");
}
}while(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")));
}
}
So, to check if the user has pressed enter, you would have to make use of the isEmpty() method. The way to do that is shown below:
String enter = in.nextLine();
if (enter.isEmpty()) {
// do what is needed
}

inputs and loops

I'm trying to do as the picture shows here:
This is my code:
import java.util.Scanner;
public class IcsProject
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner (System.in);
int menuNum,ID,semNum,semCode,semCourses;
do{
System.out.println("Please Enter your Choice from the menu:");
System.out.println("1. Enter Student Sanscript");
System.out.println("2. Display Transcript Summary");
System.out.println("3. Read Student Franscript from a File");
System.out.println("4. Write Transcript Summary to a File");
System.out.println("5. Exit");
menuNum = keyboard.nextInt();
if (menuNum == 2 || menuNum == 3 || menuNum == 4)
System.out.println("Not working");
} while (menuNum > 1 && menuNum < 5);
//// Option 1: Enter student transcript
if (menuNum == 1)
System.out.println("Please enter your student's FIRST and LAST name:");
String stuName = keyboard.nextLine();
System.out.println("Please enter the ID number for " + stuName);
ID = keyboard.nextInt();
System.out.println("Please enter the number of semesters");
semNum = keyboard.nextInt();
for(int i=1 ; i < semNum ; i++)
{System.out.println("Please enter semester code for semester n# " + semNum);
semCode = keyboard.nextInt();
System.out.println("Please enter the number of courses taken in " + semCode );
semCourses = keyboard.nextInt();}
System.out.println("Enter course code, credit hours, and letter grade ")
///I stopped here
}
Do I have to use array starting from the semester code? show me an example please.
After entering all the values The program should show the Menu again so I can choose from it. How to do that?
I'm having a problem at the first question "entering the student first and last name"
The program just skip it and move to next question. Is there a mistake with my keyboard.nextLine();
I would use a list of objects which have all the fields you want to record.
For examples, just use google.
http://www.google.com/search?q=java+list+examples 27.9 million result
http://www.google.com/search?q=java+object+examples 18 million results.
http://www.google.com/search?q=java+array+examples 15 million results.
Regarding issue #2 - put the menu in a separate method. use a loop that it's condition is the menu or something similar to process according to the result from menu (this is abstract, I think you can figure it out from here):
while(doAnotherLoop)
{
switch(showMenu())
{
case 1:
...
case 2:
...
case 5: // Exit
doAnotherLoop = false;
}
}
Regarding issue #3. You read an int: menuNum = keyboard.nextInt(); but the line is not over, so the next nextLine (String stuName = keyboard.nextLine();) takes the rest of the line. use nextLine() and parse the integers instead.

Categories

Resources