the program will ask the user to enter the code of the item he wants to search for. if the item's code exists it will print it to the screen and all works fine until here. The problem is when the user enters code that not exists, the program won't work. it doesn't print "Item not found"
here is the code
public void searchItem(){
boolean invalidInput;
int q = -1;
do {
try {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = s.nextInt();
out: for (int i = 0; i<items.length; i++){
if(q == items[i].getCode()){
System.out.println(items[i].toString());
found = true;
System.exit(2);
}
counter++;
}
if(!found)
System.out.print("Item not found");
} catch (InputMismatchException e) {
System.out.println("Please enter a valid code [Numbers Only]");
s.next();
invalidInput = true; // This is what will get the program to loop back
}
} while (invalidInput);
}
If i use this (condensed form) of your code it works, and prints "Item not found" as we would expect... So the problem is somewhere else I feel....
Please provide further information about what happens if you enter a missing (but valid) item number!
public static void main(String[] args) {
boolean invalidInput;
int q = -1;
int[] items = { 1, 2, 3, 4 };
do {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = 5;
for (int i = 0; i < items.length; i++) {
if (q == items[i]) {
System.out.println(items[i]);
found = true;
System.exit(2);
}
}
if (!found)
System.out.print("Item not found");
} while (invalidInput);
}
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! ");
}
}
I tried to do an input check (need to take 3 numbers using Scanner).
Before that, I used a similar method (.hasNext(int)) in another task - everything worked fine. In this case, it doesn't work.
The first "while" loop works correctly, on the second loop .hasNextInt() returns false and loops the loop - not giving the opportunity to enter data.
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
while (!num1IsInt) { //check first number is int
Scanner sc1 = new Scanner(System.in);
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc1.hasNextInt()) {
scaicius1 = sc1.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc1.close();
}
while (!num2IsInt) { //check second number is int
Scanner sc2 = new Scanner(System.in);
System.out.println("(2)Įveskyte antras skaicius");
if (sc2.hasNextInt()) {
scaicius2 = sc2.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc2.close();
}
while (!num3IsInt) { //check third number is int
Scanner sc3 = new Scanner(System.in);
System.out.println("(3)Įveskyte trecias skaicius");
if (sc3.hasNextInt()) {
scaicius3 = sc3.nextInt();
num3IsInt = true;
sc3.close();
} else {
System.out.println("Not correct integer");
continue;
}
sc3.close();
}
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);
Thank you - #Thomas Kläger. I change code like was at the begin (with only one Scanner, cose with 3 scanners it's didn't work) and add to all else statements reader for this "ghost element which loop my code".
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
**Scanner sc = new Scanner(System.in);**
while (!num1IsInt) { //check first number is int
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc.hasNextInt()) {
scaicius1 = sc.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
**sc.next();**
}
}
while (!num2IsInt) { //check second number is int
System.out.println("(2)Įveskyte antras skaicius");
if (sc.hasNextInt()) {
scaicius2 = sc.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
while (!num3IsInt) { //check third number is int
System.out.println("(3)Įveskyte trecias skaicius");
if (sc.hasNextInt()) {
scaicius3 = sc.nextInt();
num3IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
sc.close();
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);
#MadProgrammer, I have used the NumberFormatException to capture blanks or characters and throw back a warning message. It was successful for the main page but for the option, "add t", instead of display each t-shirt color it loops around the first color, blue. I have also tried 'while' loop statement but it causes the program to stop. If it worked for the first part, display_menu(), I don't understand why it doesn't work for "add_t".
import javax.swing.JOptionPane;
public class OnlineStore {
String[] ColorType = { "blue", "green", "black" };
final int COLOURS = 3; // t choices
int[] Color = new int[COLOURS];
int sum;
public int display_menu(){ // Not the main program but the main menu.
String input = null;
boolean test = true;
while (test == true) {
try {
input = JOptionPane.showInputDialog("Welcome!" + "\n\n1. Add t order\n2. Edit t order\n3. View current order\n4. Checkout" + "\n\nPlease enter your choice: ");
return Integer.parseInt(input);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
}
return Integer.parseInt(input);
}
public OnlineStore(){ // Switch-case program
boolean exit = false;
do {
switch (display_menu()) {
case 1:
add_t();
break;
case 2:
exit = true;
break;
default: // If an error is encountered.
JOptionPane.showMessageDialog(null, "Oh dear! Error!");
break;
}
} while (!exit);
}
public final int add_t() {
for (int index = 0; index < ColorType.length; index++) {
boolean test = true;
while (test == true) {
try {
String orderItems = JOptionPane.showInputDialog("Please enter your t order for " + ColorType[index]);
int items = Integer.parseInt(orderItems);
Color[index] = items;
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
}
}
sum = Color[0] + Color[1] + Color[2];
JOptionPane.showMessageDialog(null, "Your total order is " + sum);
return Color.length;
}
public static void main(String[] args){ // Main program
new OnlineStore(); // Call out the program.
}
}
Let's have a quick look at add_t...
public final int add_t() {
for (int index = 0; index < ColorType.length; index++) {
boolean test = true;
while (test == true) {
try {
String orderItems = JOptionPane.showInputDialog("Please enter your t order for " + ColorType[index]);
int items = Integer.parseInt(orderItems);
Color[index] = items;
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
}
}
sum = Color[0] + Color[1] + Color[2];
JOptionPane.showMessageDialog(null, "Your total order is " + sum);
return Color.length;
}
First, you have a for-loop so you can prompt for each color type, not unreasonable, next you have while (test == true), now, having a quick loop inside the loop, there's no exit condition, no where do you set test to false so the loop can exit...opps, infinite loop.
The reason it works in your previous attempt is, if no error is generated by Integer.parseInt, the value is automatically returned
return Integer.parseInt(input);
Now, I'm old school, I like one entry point and one exit from a method, it prevents mistakes or misunderstandings like this one.
Instead, since this seems like something you might do a lot, I'd write a simple "prompt for a integer" method, something like...
public Integer promptForInt(String prompt) {
Integer value = null;
boolean exit = false;
do {
String input = JOptionPane.showInputDialog(prompt);
if (input != null) {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
} else {
exit = true;
}
} while (value == null && !exit);
return value;
}
Now, all this does is asks the user for int value. It will keep looping until the user either enters a valid int value or presses cancel. The method will either return a int (Integer to be exact) or a null. The null indicating that the user pressed the cancel button
Now, you can simply use
public int display_menu() // Not the main program but the main menu.
{
Integer value = promptForInt("Welcome!" + "\n\n1. Add t order\n2. Edit t order\n3. View current order\n4. Checkout" + "\n\nPlease enter your choice: ");
return value != null ? value : 4;
}
and
public final int add_t() {
boolean canceled = false;
for (int index = 0; index < ColorType.length; index++) {
Integer value = promptForInt("Please enter your t order for " + ColorType[index]);
if (value != null) {
Color[index] = value;
} else {
canceled = true;
break;
}
}
if (!canceled) {
sum = Color[0] + Color[1] + Color[2];
JOptionPane.showMessageDialog(null, "Your total order is " + sum);
}
return canceled ? -1 : Color.length;
}
to ask for int values from the user
I'm making a program of battleship with the user going against the computers random inputs choices in an 8x8 grid.
What I'm having trouble with is that I don't want my program to crash if my user inputs a String, such as "asdfklasdn", "h", etc... It doesn't crash if its an integer, such as 1,5,etc. Is there any way to change this without changing the rows and columns to strings? If I use try catch, it just gives me an error in the if-else statements right after in the userFire method.
Any help will be much appreciated. Thank you!
import java.util.*;
import java.util.Scanner;
public class Battleship
{
Scanner input = new Scanner(System.in);
public static final boolean DEBUG = false;
public static void breakln()
{
System.out.println("─────────────");
}
public static void createBoard(String [][]board)
{
for( int r = 0; r<board.length; r++)
{
for(int c= 0; c<board[0].length; c++)
{
board[r][c] = "-";
}
}
}
public static void showBoard(String[][] board)
{
breakln();
for(int r =0; r<board.length;r++)
{
if(DEBUG == true)
{
for(int c = 0; c<board[0].length;c++)
{
System.out.print(" " +board[r][c]);
}
System.out.println("");
}
else
{
for(int c = 0; c<board[0].length;c++)
{
if(board[r][c].equals("S"))
{
System.out.print(" " + "-");
}
else
{
System.out.print(" " + board[r][c]);
}
}
System.out.println("");
}
}
breakln();
}
public static void createShip(String[][] board, int size)
{
if(Math.random()<0.5)
{
int col = (int)(Math.random()*5);
int row = (int)(Math.random()*7);
for(int i = 0; i<size; i++)
{
board[row][col+i]="S";
}
}
else
{
int col = (int)(Math.random()*7);
int row = (int)(Math.random()*5);
for(int i = 0; i<size; i++)
{
board[row+i][col]="S";
}
}
}
public static int userFire(String[][] board, int hits, int torps)
{
Scanner input = new Scanner(System.in);
int row,col;
System.out.println("You have: " + torps + " torpedos");
System.out.println("Select row to fire in: ");
row = input.nextInt();
while(row>8||row<1)
{
System.out.println("Invalid. Enter a valid row (1-8)");
row = input.nextInt();
}
System.out.println("Select column to fire in: ");
col = input.nextInt();
while(col>8 || col<1)
{
System.out.println("Invalid. Enter a valid column (1-8)");
col = input.nextInt();
}
if(board[row-1][col-1].equals("S"))
{
hits++;
System.out.println("HIT ");
board[row-1][col-1] = "×";
}
else
{
System.out.println("MISS");
board[row-1][col-1] = "Ø";
}
return hits;
}
public static void endOfGame(int hits, int torps)
{
if(hits<4)
System.out.println(" LOSE ");
if(torps<1)
System.out.println("You have lost all your torpedos.");
else
if(hits>=4)
{
System.out.println("WINNER");
}
System.out.println("");
}
public static void main(String[] args)
{
System.out.println(" BATTLESHIP ");
System.out.println("");
String[][] board = new String[8][8];
createBoard(board);
createShip(board,4);
int torps = 25;
int hits = 0;
while(torps>0 && hits<4)
{
showBoard(board);
hits = userFire(board,hits,torps);
torps--;
}
endOfGame(hits, torps);
}
}
I've tried everyone's answers, but I received errors in this code.
if(board[row-1][col-1].equals("S"))
{
hits++;
System.out.println("╠══ HIT ══╣");
board[row-1][col-1] = "×";
}
else
{
System.out.println("╠══ MISS ══╣");
board[row-1][col-1] = "Ø";
}
return hits;
Add try/catch block inside row=input.nextInt() or every variable who receives input;
Here's sample code
try{
row = input.nextInt();
}
catch(Exception)
{
}
Just catch the exception, e.g.
try {
row = input.nextInt();
} catch (InputMismatchException e) {
System.err.println("Input is not an integer"); // or do some error handling
}
Try this out:
System.out.println("Invalid. Enter a valid row (1-8)");
String userInput = input.next();
try {
row = Integer.parseInt(userInput);
} catch (NumberFormatException exp) {
// Failed : Invalid input. Take actions if required.
// May be prompt user for correct input
}
You can use while(input.hasNextInt()) and println a message saying you only want ints?
Or a catch block as BroSlow said.
try {
xxx = input.nextInt();
} catch(NumberFormatException nfe) {
doXXXLoop();
}
// ....
public void doXXXLoop() {
System.out.println("Not a valid number. Enter another:");
try {
xxx = input.nextInt();
} catch(NumberFormatException nfe) {
doXXXLoop();
}
}
Unlike other code, this will easy repeat until a valid int is entered. Replace XXX with Row or Col or whatever you want.
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!");
}
}
}