I'm writing a java program where the initial part is a scanner. I need the user to enter a folder name and then the program needs to confirm. The scanner is asking the relevant question and accepting the answer. I then need it to confirm Y or N. Y, the program will continue. N, I need the code to loop back and ask the first question again. I've searched around, and I can see a number of solution for integers, but not for text.
import java.util.Scanner;
public class webSiteGenerator {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Please enter a source folder: ");
String sourceFolder = obj.nextLine();
System.out.println("You have selected the folder '" + sourceFolder + "'. Are you sure (Y/N)");
String confirmation = obj.nextLine();
while (!"Y".equalsIgnoreCase(confirmation) && "N".equalsIgnoreCase(confirmation)) {
System.out.println("Response not recognised. Please confirm... Are you sure (Y/N)");
confirmation = obj.next();
}
}
}
The reaponce of "Y' and "N" will be stored in the string sourceFolder, so you just need to compare the string sourcFolder with Y and N.
so your code be like:
int flag = 0;
while (flag!=1){
if(sourceFolder.equals("Y") || sourceFolder.equals("y")){
//Your Code
flag=1;
}else if((sourceFolder.equals("N") || sourceFolder.equals("n")){
flag=1;
} else{
print("Invalid Input! Please choose only between Y or N ");
flag=1;
}
}
P.S flag is actually used for exit the while condition. You can use any word instead of flag.
Ask if anything creates a doubt.
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.
I'm trying to learn (self-taught) Java by reading Big Java, Late Objects from by Cay Horstmann. I'm using repl.it to write my code (if you may want to look it up, it's public)
A selfcheck question of Chapter 4 Loops is:
How can you overcome the problem of when the user doesn't provide any input in the algorithm of section 4.7.5 (titled Maximum and Minimum) and the WHILE loop just terminates the program for this reason ?
They basically ask to rewrite the code so it solves this problem.
The information of section 4.7.5 you need to solve this problem: To compute the largest value in a sequence, keep a variable that stores the largest element that you have encountered, and update it when you find a larger one.
(This algorithm requires that there is at least one input.)
double largest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}
This is what the book suggests as the answer to this problem (but I disagree):
One solution is to do all input in the loop and introduce a Boolean variable that checks whether the loop is entered for the first time.
double input = 0;
boolean first = true;
while (in.hasNextDouble())
{
double previous = input;
input = in.nextDouble();
if (first) { first = false; }
else if (input == previous) { System.out.println("Duplicate input"); }
}
I don't fully understand the first sentence. And I disagree this as a solution for the problem because (as far as I can tell) it tests whether the input has been entered before, instead of testing if any sort of user input has been provided..
I tried to merge those two sections of code together but I can't seem to make it work. Or more specific: figure out how to build it. What variables / loops do I need? In which order do I write this?
I've made a flowchart in Visio of the first section of code but have no clue how to continue.
This is what I've written so far:
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number: ");
double largest = 0;
while (input.hasNextDouble())
{
double value = input.nextDouble();
if (value > largest)
{
largest = value;
System.out.println("The largest input till now is: " + largest);
}
}
Can someone:
Ask me questions which help me to solve this question? I.e. Tell me what tools I need (WHILE, FOR etc.)
Provide a solution in text which I can hopefully transform in code
Or write the code for me (I haven't learned arrays yet, so please solve it without)
Thanks in advance,
So I worked on this for a bit and I think I have something close to what you're looking for using a do while loop.
This code accepts user input first, then checks it's value in comparison to the last input and return either "Input a higher value", "Duplicate number found", or it sets the last number entered to the current number.
I hope this helps you get your code to where you'd like it to be! I'm still new, so I apologize if this is not entirely optimized.
Also, I have not added a way to exit the loop, so you may want to add a check on each iteration to see if the user would like to continue.
public static void main(String[] args) {
double userInput = 0;
double prevNum = 0;
boolean hasValue = false;
boolean exitCode = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
userInput = sc.nextDouble();
do {
if (userInput<prevNum) {
System.out.println("Please enter a number higher than " + prevNum);
hasValue=true;
}
else if (userInput==prevNum) {
System.out.println("Duplicate input detected.");
hasValue=true;
}
else {
prevNum = userInput;
hasValue = true;
}
}
while(hasValue==false);
System.out.println(prevNum);
System.out.println(userInput);
}
while(exitCode==false);
}
If you want compute if the number entered is the largest entered from the beginning but declare it at the largest if it's the first iteration then do this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean flag = true;
double largest = 0;
System.out.println("Enter the number: ");
while (input.hasNextDouble()){
double value = input.nextDouble();
if (flag) {
flag = false;
largest = value;
}
else if (value > largest) largest = value;
System.out.println("The largest input till now is: " + largest);
System.out.println("Enter a new number: ");
}
}
Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.
You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));
That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.
I'm trying to get a dice roller happening and I'm having some difficulty adding a loop somewhere so the program doesn't quit after one roll. I want to ask the user if they want to roll and it rolls by saying "y." I want to end the program by asking the user the same question but it ends with "n"
/*
Natasha Shorrock
Assignmnt A6
11/07/16
*/
package diceroller;
import java.util.Random;
import java.util.Scanner;
public class DiceRoller {
public static void main(String []args) {
System.out.println(" Do you want to roll the dice? ");
Random dice = new Random();
Scanner input = new Scanner(System.in);
int faces;
int result;
System.out.println("Dice Roller\n");
System.out.println("How many faces does the dice have?");
faces = input.nextInt();
result = dice.nextInt(faces) + 1;
System.out.println("\nThe dice rolled a " + result );
}//Dice Roller
}//class DiceRoller
You have to read the input after the following expression:
System.out.println(" Do you want to roll the dice? ");
To receive the users input call: input.nextLine();. Thereafter loop while the input is "y". If the user input is not equals to "y" the while-loop gets terminated.
The while(condition) loop is excuted as long as the condition is true
The while statement continually executes a block of statements while a particular condition is true. The while and do-while Statements
For example consider this code :
public static void main(String[] args) {
Random dice = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
String answer = input.nextLine(); // reading the input
// we check if the answer is equals to "y" to execute the loop,
// if the answer is not equals to "y" the loop is not executed
while ("y".equals(answer)) {
System.out.println("Dice Roller");
System.out.println("How many faces does the dice have?");
int faces = input.nextInt();
int result = dice.nextInt(faces) + 1;
input.nextLine(); // to read the newline character (*)
System.out.println("The dice rolled a " + result);
System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
answer = input.nextLine();
}
}
To find out more about the while and do-while mechanisms, please visit this toturial
(*) To understand the use of nextLine() after a call to nextInt() please visit Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
A do-while is a very good option. Another way of doing it could be using a while loop with a switch or preferably an IF/ ELSE IF statement. Perhaps something like below. This is only a suggestion.
boolean checkForExit = false;
while(checkForExit != true) { //while checkForExit does not equal true (therefore false) continue..
System.out.println("Do you want to roll the dice?");
String answer = input.next(); //get char input from user.
if(answer.toLowerCase().equals("y")) { //if 'y' then do this
//ask user for number of faces on dice and roll
} else { // otherwise end the program
//set isTrue to true to exit while loop. ends program
isTrue = true;
}
}
I'm new to java and I decided to write a simple program to practice IFs. Here's what it should do:
Ask the user about the currency.
Ask the user about the amount of money he wants to transfer.
Calculate the commission rate and show the details to the user.
Ask the user for confirmation; if he types "y" , the program should print "A". If he types "n" , the program should print "B".
Here's the code :
import java.util.Scanner;
public class CommissionRate {
static String Confirm;
static byte CommissionRate=10;
static String Commission="1%.";
static double TotalCost;
static double MoneyAmount;
static byte CurrencyNum;
static char CurrencySign;
static Scanner sc = new Scanner(System.in);
public static void Currency(){
System.out.println("Please choose your desired currnecy.");
System.out.println("1.USD");
System.out.println("2.EUR");
System.out.println("3.GBP");
System.out.println("4.CAD");
System.out.println("5.CNY");
System.out.println("6.JPY");
CurrencyNum = sc.nextByte();
if (CurrencyNum==1|CurrencyNum==4) {
CurrencySign= '$';
}
else {
if (CurrencyNum==2){
CurrencySign='€';
}
else {
if (CurrencyNum==3){
CurrencySign='£';
}
else {
if (CurrencyNum==5|CurrencyNum==6){
CurrencySign='¥';
}
}
}
}
}
public static void MoneyAmount() {
System.out.println("Please enter the amount of money you would like to transfer :");
MoneyAmount = sc.nextDouble();
if (MoneyAmount>499 & MoneyAmount<10000){
CommissionRate=5;
Commission="0.5%.";
}
else{
if (MoneyAmount>10000){
CommissionRate= 3;
Commission="0.3%.";
}
}
TotalCost = MoneyAmount + MoneyAmount * CommissionRate/1000;
System.out.println("Please confirm the transfer. ( y/n ) ");
System.out.println("A transfer of "+MoneyAmount+CurrencySign+".");
System.out.println("Commission rate is "+Commission);
System.out.println("You need to pay " + TotalCost+"." );
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){
System.out.println("A");
}
else if (Confirm=="n") {
System.out.println("B");
}
}
}
At first , the program wouldn't wait for the user to confirm/abort the transfer and it would print "B". Then , I read this and added the "sc.nextLine()". However the program just ignores the last if and doesn't print anything. Any ideas on what causes the problem and how to solve it ?
p.s.: Here's what I get when running the program:
Please choose your desired currnecy.
1.USD
2.EUR
3.GBP
4.CAD
5.CNY
6.JPY
2 // my input
Please enter the amount of money you would like to transfer :
120 // my input
Please confirm the transfer. ( y/n )
A transfer of 120.0€.
Commission rate is 1%.
You need to pay 121.2.
y // my input
please try
if (Confirm.equals("y")){
and
else if (Confirm.equals("n"))
with == you compare the object references not the values.
Try equals instead of == and one times should be sc.nextLine();
Confirm = sc.nextLine();
if (Confirm.equals("y")){
instead of
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){