I am taking input for my application using scanner. My code is as follows:
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO")
if(sc.next().equals("YES")){
System.out.println("which input? student or teacher name")
if(sc.next().equals("student")){
system.out.println("do something");
}
if(sc.next().equals("teacher")){
system.out.println("do something");
}
}
}else
{
system.out.println("program will run itseld");
}
Code is working fine but it is asking input twice. Suppose if I enter student it will not proceed but when I enter student again second time my program starts working. I also saw some similar questions on stackoverflow and tried their solutions but I am not able to resolve this. Please help.
sc.next() grabs an input each time. Store this to a variable and just use the variable when comparing.
String input = sc.next();
if(input.equals("YES")) {
// logic here
}
try something like this
import java.io.*;
import java.util.*;
class SumsInLoopTester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO");
String input = sc.next();
if (input.equals("YES")) {
System.out.println("which input? student or teacher name");
String input2 = sc.next();
if (input2.equals("student")) {
System.out.println("do something");
} else if (input2.equals("teacher")) {
System.out.println("do something");
}
} else {
System.out.println("program will run itseld");
}
}
}
Related
I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.
Code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int counter = 0;
boolean run = true;
int userInput = 0;
while (run) {
System.out.print("Enter an integer: ");
if (inputScanner.hasNextInt()) {
userInput = inputScanner.nextInt();
} else if (!inputScanner.hasNextInt()) {
while (!inputScanner.hasNextInt()) {
System.out.print("You need to enter an Integer: ");
userInput = inputScanner.nextInt();
}
}
System.out.println(userInput);
if (counter == 6) {
run = false;
}
counter++;
}
}
}
At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.
In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:
try {
new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
System.out.println(“<error message>”)
}
In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.
package somePackage;
import java.util.Scanner;
public class SomeClass {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.print("Please enter a command (start or stop) : ");
String scanner = input.nextLine();
if ("start".equals(scanner)) {
System.out.println("System is starting");
} else if ("stop".equals(scanner)) {
System.out.println("System is closing");
}
while (!"start".equals(scanner) && (!"stop".equals(scanner))) {
System.out.print("Please try again : ");
scanner = input.nextLine();
}
}
}
when a user doesn't input "start" or "stop". The program will ask the user to "Try again : ". Let's say the user inputs "start" after that, the output will be blank. How can I make my loop go back to the original System.out.print() in the if() or else if() statement?
P.S , I'm new to Java so any feedback would help :) Thanks!
If the if statement just need to be shown one time, is enough to put that after the while loop, because if type start or stop break to the while loop and it will print the correct message, for example:
public class SomeClass {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.print("Please enter a command (start or stop) : ");
String scanner = input.nextLine();
while (!"start".equals(scanner) && (!"stop".equals(scanner))) {
System.out.print("Please try again : ");
scanner = input.nextLine();
}
if ("start".equals(scanner)) {
System.out.println("System is starting");
} else if ("stop".equals(scanner)) {
System.out.println("System is closing");
}
}
}
A while loop can't "go back to" a statement outside its body.
You need everything you want to loop back to inside the loop's body. For example:
System.out.print("Please enter a command (start or stop) : ");
while (true) {
scanner = input.nextLine();
if ("start".equals(scanner)) {
System.out.println("System is starting");
break; // Exits the loop, so it doesn't run again.
} else if ("stop".equals(scanner)) {
System.out.println("System is closing");
break;
}
// No need for conditional, we know it's neither "start" nor "stop".
System.out.print("Please try again : ");
// After this statement, the loop will run again from the start.
}
You could simply loop until you get the desired output; an example using a do-while:
input = new Scanner(System.in);
String scanner;
do {
System.out.print("Please enter a command (start or stop) : ");
scanner = input.nextLine();
} while (!"start".equals(scanner) && !"stop".equals(scanner));
if ("start".equals(scanner)) {
System.out.println("System is starting");
}
else if ("stop".equals(scanner)) {
System.out.println("System is closing");
}
I'm trying to make a simple program that asks for the user's age and displays an error when the user inputs a non-integer value.
Here's what I did so far:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
if(!ageinput.hasNextInt()){
System.out.println("Please enter an integer");
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
}
Here's what I want:
Every time the user inputs a non integer, I want the Please enter an integer error to appear. The user should then be able to input their age again, which will again be checked if it's an integer and so on. This will continue until the user inputs an integer and only then will the message You've entered a valid age be shown. I'm sure about neither which loop to use in this case (for, while, do while) nor how to implement it in the code.
String stringAge;
do {
System.out.println("Please Enter an int");
stringAge = ageinput.next();
} while (!stringAge.matches("^-?\\d+$")); //regex matches for - sign, and then a number
System.out.println("You entered an int");
int age = Integer.parseInt(stringAge);
As you know in Java they're 3 types of loops:
The while and do-while Statements
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
while is simply a pre-test loop, that is the condition first will be checked before moving on to the body of the loop:
while(condition) # First check, if true or false
{
# Body
}
do-while loop however, checks the condition after executing of the body of the loop at least once, it's a post-test loop:
do{
# Body executed at least once
}while(condition);
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied
Notice that in your code, asking the user for the age, the proper choice would be do-while, because you need to execute your program at least once to prompt the message and then you have to check the condition, if that's what you intended to do then this will suffice for your purpose. Though, you still can use while.
This is your code edited:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + input.nextLine() + "!");
System.out.println("Please enter your age");
do{
if(input.hasNextInt()){
System.out.println("You've entered a valid age");
break;
}
else{
System.out.println("Please enter an integer");
input.next();
}
}while(true);
}
}
Since the condition for the loop is the Boolean true it really doesn't matter here if you use while instead of do-while unless if you want to change the condition, that's up to you. For now, this code is very much close to the original code you posted and from my perspective it works, but it may not be the best code out there, there could be other approaches simpler or more complex to the same problem domain.
First of all, there's no need to have multiple Scanner objects wrapping the System.in input stream. (How to use multiple Scanner objects on System.in?)
As for the actual code, here's what came to mind:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name to begin:");
String name = scanner.nextLine();
System.out.println("Hello " + name + "!");
System.out.println("Please enter your age:");
int age;
while (true) {
try { // Try to read in the age.
age = scanner.nextInt();
} catch (InputMismatchException ex) { // The input wasn't a valid integer; parsing the value failed.
System.out.println("Please enter an integer:");
continue; // Attempt reading the age again.
}
break; // The input was a valid integer. Break out of the loop.
}
scanner.close();
System.out.println("You've entered a valid age");
}
}
Hope this is what you wanted. i would suggest that using while is the way to go (my preference)
Using while::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
while (!ageinput.hasNextInt()) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using for::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
for (; !ageinput.hasNextInt();) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using do while
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
int i = 0;
do {
if (i == 0) {
System.out.println("Please enter your age");
i++;
} else {
System.out.println("Please enter an integer");
ageinput.next();
}
} while (!ageinput.hasNextInt());
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
This question already has answers here:
Breaks from loop
(3 answers)
Closed 8 years ago.
I have looped my code so it keeps repeating until a "yes" or a "no" is given when being asked "Continue?". But my code breaks from the loop after entering a random value and then yes.
for example:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
It should say:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
Add or delete another name?
actual code
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(new File("names.txt"));
Scanner myScan = new Scanner(System.in);
Scanner scanRedo = new Scanner(System.in);
String userRedo;
String userResponse;
while (scan.hasNext())
names.add(scan.next());
do {
System.out.print("Add or delete another name? ");
userResponse = myScan.next();
if (userResponse.equalsIgnoreCase("add")) {
System.out.print("Please enter a name you want to add: ");
names.add(myScan.next());
} else if (userResponse.equalsIgnoreCase("delete")) {
System.out.print("Please enter a name you want to delete: ");
names.remove(myScan.next());
} else {
System.out.print("Invalid Choice");
}
PrintWriter writer = new PrintWriter("namesupdated.txt");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
System.out.print("Continue? ");
userRedo = scanRedo.next();
} while (userRedo.equalsIgnoreCase("yes"));
do { // THIS LOOP IS HERE BECAUSE IF THE USER ENTERS A VALUE OTHER THAN CONTINUE, YES OR NO, THE QUESTION REPEATS
if(userRedo.equalsIgnoreCase("no")) {
System.out.print("Thank You.");
userRedo = scanRedo.next();
} else if (!userRedo.equalsIgnoreCase("yes")) {
System.out.print("Continue? "); // LOOP ENDS EARLY HERE
userRedo = scanRedo.next();
}
} while (!userRedo.equalsIgnoreCase("yes")); // NOT SURE HOW TO RESTART PREVIOUS LOOP
scan.close();
myScan.close();
scanRedo.close();
}
}
The way you do this is always with a while loop with some sort of changable condition:
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
...
System.out.println("Continue? Yes or No");
String s = Scan.nextLine();
if(s.equals("No")) {
stop = true;
}
}
I'm budding into java and I've been trying to write this basic program where it asks you a yes or no question, you give it an answer and then it does something based off that answer. currently my code is this.
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner inputvar = new Scanner (System.in);
String yes, no;
System.out.println("Enter yes or no");
yes = inputvar.nextLine();
no = inputvar.nextLine();
if (inputvar.equals(yes))
{
System.out.println("You said yes!");
}
else if (inputvar.equals(no)){
System.out.println("You said no");
}
}
}
I don't get any errors when compiling but when I run the program It doesn't reply when I put anything in. It allows me to enter two lines of text then it terminates.
Your code yes, no variables are not correct, you invoke nextLine() twice in your code, that's why you are asked to enter inputs twice.
yes = inputvar.nextLine();
no = inputvar.nextLine();
inputvar is a Scanner instance, not a String object, you cannot try
inputvar.equals(yes)
You should only define:
String myInput = inputvar.nextLine();
and checks
if (myInput.equals("yes")){
//do some stuff
}else if(myInput.equals("no")){
//do other stuff
}
Scanner inputvar = new Scanner (System.in);
String yes, no;
System.out.println("Enter yes or no");
yes = inputvar.nextLine(); // You enter the first line
no = inputvar.nextLine(); // You enter the second line
if (inputvar.equals(yes)) // You try to compare an instance of
// Scanner with the firstline (not equal)
{
System.out.println("You said yes!");
}
else if (inputvar.equals(no)){ // You try to compare an instance of
// Scanner with the firstline (not equal)
System.out.println("You said no");
}
// You terminate the program
You should do something like:
String yes = "yes";
String no = "no";
String input = inputvar.nextLine();
if(yes.equals(input)) { [...]
You should change your code to this
Scanner inputvar = new Scanner (System.in);
String input;
System.out.println("Enter yes or no");
input = inputvar.nextLine();
if (input.equals(yes))
{
System.out.println("You said yes!");
}
else if (input.equals(no)){
System.out.println("You said no");
}
Hope this helps and best of luck.