void searchForPopulationChange()
{
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
input = scan.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
}
}
}
hello!
I am working on a method that will take an users input,
lets say (5000) and search a data file with those corresponding numbers.
and return the corresponding number, and county that it corresponds with.
However, I am able to get this code to run to return the correct value,
but i am unable to get it to run when i enter an "incorrect" value.
Any pointers?
Thank you!
It's a bit unclear, but I assume you want something to handle if the input is incorrect (not an integer)? Use hasNextInt so you will only capture integers.
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
int num = scanner.nextInt();
This will keep looping the input until it is a valid integer. You can include a message in the loop reminding the user to input a correct number.
If you want something to display if your number has no match inside of the array, simply add code after your for block, if found == false. For example:
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
Since found is still false, your while loop kicks in and prints your line requesting for input again.
EDIT: Since you seem to have problem adding these two concepts to your code, here's the whole function:
void searchForPopulationChange() {
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
input = scanner.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
}
}
Related
Condition 1: if you input more than or equal to 10 straight heads and are able to show in the input then the return is "Streak is found"
Condition 2: if you input less than 10 straight heads then the return is "Streak is broken"
However, I have a problem with condition 1 where it didn't execute to the output.
The code:
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Scanner;
public class LinkedListProgram2
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println ("Welcome to the Program #2 ");
//ask for the boolean value. It can be head and tail or true and false.
System.out.print ("\nEnter the boolean value (head=true, tail=false): ");
for (int i = 0; i<18; i++)
{
cointoss.add(input.next());
}
Iterator<String> it = cointoss.iterator();
while (it.hasNext())
{
if(streakcount >= 10)
{
streak = true;
System.out.println ("Streak is found! ");
break;
}
else if(streakcount < 10)
{
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
}
}
2 logic needs to be added atleast.
Increment the streakcount when true is found
Resetting the counter when false is found
You can have the outer if condition inside the while loop to print broken for every instance or let it be outside while to be printed at the end of loop
while (it.hasNext()) {
String val = it.next();
if (val.equals("true"))
streakcount++;
else
streakcount = 0;
if (streakcount >= 10) {
streak = true;
System.out.println("Streak is found! ");
break;
}
}
if (!streak) {
System.out.println("Streak is broken! ");
}
You miss something in your code, you need to check the input value, and increase streakcount, untested example code:
while (it.hasNext()) {
String val = it.next();
if (val.equals("true")) {
streakcount++;
if (streakcount >= 10) {
streak = true;
System.out.println ("Streak is found! ");
break;
}
}
else if (val.equals("false")) {
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
There are more action to do, check different input value, or do you need to find streak if it is not from starting array...
According to your description, this is actually a small program that counts specific strings, and doesn't even need LinkedList
I modified your code and now it should satisfy the two conditions you proposed
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println("Welcome to the Program #2 ");
// ask for the boolean value. It can be head and tail or true and false.
System.out.println("Enter the boolean value (head=true, tail=false): ");
for (int i = 0; i < 18; i++) {
String next = input.next();
if (next.equals("true") || next.equals("head")) {
streakcount++;
}
cointoss.add(next);
}
if (streakcount >= 10) {
System.out.println("Streak is found! ");
} else {
System.out.println("Streak is broken! ");
}
}
There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}
This while loop that is suppose to prompt for a price and a y/n and end if price = 0. However, when I run the code, it asks for the price, takes it, goes to a blank line, and I have to enter the number again before asking me the next question. For the second question, I only have to enter the input once.
And when I print the price array, the value is the number I inputted the second time.
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) {
prices.add(in.nextDouble());
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Help please?
That's because each time you write in.nextDouble(), the user will be need to type something into the scanner. Instead, you should store the input in a tempory variable:
Double input = in.nextDouble(); // Keep the input in this variable
if (input > 0) { // You can use it on each of these lines
prices.add(input); // so that the user doesn't have to type it twice.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
A little side note: keepGoing should probably be a boolean instead of an int
Also, you can use new String("Y").equalsIgnoreCase(input) so that you don't need the ||
It asks you twice because you call the in.nextDouble() method twice, one in the if statement and another time in the following line.
Take a look at the comments on your code below:
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) { // <-- You are asking for the input here
prices.add(in.nextDouble()); // <-- and asking for the input here again.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Just change your code to be like this:
int keepGoing = 1;
double d = 0;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
d = in.nextDouble();
if (d > 0) {
prices.add(d);
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
void searchForPopulationChange()
{
int input;
int searchCount = 0;
System.out.println ("Enter the Number for Population Change to be found: ");
input = scan.nextInt();
boolean found = false;
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
break;
}
}
if (found)
{
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
else
{
System.out.print("WRONG INPUT");
}
}
}
hello, above is currently my program.
I am having an issue with having it pull out ALL of the corresponding variables.
IE: I enter "200", there are (2) units in the array that have a corresponding (200) value,
however, this only prints out 1 of them.
Anyone have any quick pointers?
instead of breaking when you find your value
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
break;
}
}
if (found)
{
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
just print it on the spot
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
you can still check for wrong input after your loop is finished
if (found == false)
{
System.out.print("WRONG INPUT");
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Hoping someone could assist. Missing something obvious I think. I have to get a user to input an account number. I need to validate this against two checks. One being that it is not yet used and that it is in the correct format.
I have played around with this and tried different ways of doing this. I think that the reason it fails is because halfway through going through the array, I am asking for user input.
It stops the for-loop and then continues from there when user has input the data. how do I validate both?
System.out.println("Please enter an ID (format PNOnnn)");
String pnoID = console.next();
boolean pnoIDValid = false;
while (pnoIDValid);
{
for (int i = 0 ; i < pno.length ; i++)
{
if (pno[i] != null)
{
if (pnoID.compareToIgnoreCase(pno[i].getmID()) == 0)
{
System.out.println("ID already used");
//pnoID = console.next();
}
else
{
if (!(pnoID.matches("PNO\\d{3}")))
{
System.out.println("Must be in format PNOnnn");
//pnoID = console.next();
}
else
{
pnoIDValid = true;
}
}
}
}
}
I wonder if this is not resulting in the array not getting checked. I have tried it this way as well. logically it makes sense to me, but it is just not working.
System.out.println("Please enter a ID (format PNOnnn)");
String pnoID = console.next();
boolean pnoIDValid = false;
while (pnoIDValid);
{
for (int i = 0 ; i < pno.length ; i++)
{
if (pno[i] != null)
{
if ((pnoID.compareToIgnoreCase(pno[i].getmID()) == 0) ||
(!(pnoID.matches ("PNO\\d{3}"))))
{
System.out.println("ID already used");
pnoID = console.next();
}
else
{
pnoIDValid = true;
}
}
}
}
I eventually went with:
int subSelection = console.nextInt();
if(subSelection == 1){
System.out.println("Enter ID");
String pnoID = cons.next();
int test1=0; int test2=0;
for (int i = 0 ; i < pno.length ; i++){
if (pno[i]!=null && pnoID.compareTo(pno[i].getmID()) == 0)){
test1 = 1;
}else{
test2 = 1;
}
}
int test3 = 0; int test4 = 0;
if (pnoID.matches("PNO\\d{3}")){
test3 = 1;
}else{
test4 = 1;
}
if (test1 == 1 && test4 == 1){
System.out.println("This ID exists or format invalid");
}else{
System.out.println("enter name (first and last)");
String name = cons.nextLine();
System.out.println("enter phone number");
String phone = cons.nextLine();
}
The odd thing however is that the first time i go through this, I am able to enter the details correctly. The second time however it is not giving me the option to enter an ID. It shows the question "enter id", but then immediately goes to the next question "enter name".
I have two scanners; one for menu selections and one for userinput. might this cause a conflict?
RESOLVED:
This has now been resolved as well. From what I have read online; with the scanner, a new line character (carriage return/enter key stroke) is left in the buffer and this is picked up, whihc results in the second console entry being skipped.
The suggested solution is to use bufferedreader nextLine() which I tried for all string entries and this has successfully resolved my issue.
Extract uniqueness check to separate method:
private boolean isIDUnique(String pnoID) {
for (int i = 0; i < pno.length; i++) {
if (pno[i] != null && pnoID.compareToIgnoreCase(pnoID)) {
return false;
}
}
return true;
}
Main method:
System.out.println("Please enter a ID (format PNOnnn)");
String pnoID;
boolean pnoIDValid = false;
do {
pnoID = console.next();
if (!isIDUnique(pnoID) {
System.out.println("ID is not unique");
} else if (!pnoID.matches("PNO\\d{3}") {
System.out.println("Invalid format");
} else {
pnoIDValid = true;
}
} while(!pnoIDValid);