Good day, i'm stuck figuring out correct way to implement a function, the function has the following functionality.
1. When program starts, text is displayed to enter a key or leave field empty.
2. If text was entered , do A.
3. If text wasn't entered do B.
This is what i've done so far.
System.out.println("Enter any key to get data or leave empty");
//Just give some value
int value = 0;
try {
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000);
//If enter was pressed then theoretically value
//should be 1(Not working)
value = System.in.read();
}
if (value != 0) {
Database.getInstance().getAllStamps();
} else {
start();
}
} catch (Exception e) {
e.printStackTrace();
}
Scanner sc = new Scanner(System.in);
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000); // Execution pauses
if(sc.hasNext())
// call your function
break;
}
}
or
boolean flag = false;
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000); // Execution pauses
if(sc.hasNext())
flag = true;
}
}
if(flag) {
// call your function
}
One way to get raw input is to use a java.util.Scanner.
Use something like this:
Scanner sc = new Scanner(System.in);
if(sc.hasNext()){
//do stuff with input
}
else{
//handle stuff
}
Related
Read whole numbers from a user, then display the list of numbers input and the frequency of each value. The number of inputs should vary from 1-30, and the values accept 0-9.
My issue is that the array always defaults to 1 even if I change it to int[] numbers = new int[numInputs];. It appears that numInputs gets written over to 1 during the first for loop but even changing the value of numInputs it still caps out at 1. I'm sure my logic is wrong but I'm not sure where.
public class Occurrence
{
public static void main(String[] args)
{
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 1, temp;
int[] numbers = new int[31];
int[] count = new int[31];
boolean success = false;
//start of program
System.out.println("How many input values [max:30]?");
//while no valid input
while (!success)
{
try
{
numInputs = keyboard.nextInt(); //get a number
numInputChecker(numInputs); //is it valid?
success = true; //ok
}
catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 1 through 30 only, please.");
}
}
//reset the loop checker
success = false;
//read numbers to fill that array
System.out.println("Enter " + numInputs + " numbers.");
for(int i = 0; i < numInputs; i++) //from 0 to max number
{
while (!success) //while no valid number
{
try
{
numbers[i] = keyboard.nextInt(); //fill the current cell with a number
numberChecker(numbers[i]); //is it valid?
success = true; //ok
}
catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 0 through 9 only, please.");
}
}
}
//take the input and count each use of element
for (int i = 0; i< numbers.length; i++) //for 0 to max number
{
temp = numbers[i]; //get the current value of the cell
count[temp]++; //add the use of that value to a new array's cell
}
for(int i = 0; i < count.length; i++) //from 0 to 9 (expected)
{
if (count[i] > 0 && count[i] == 1) //if cell not empty
{
System.out.println(i + " " + count[i]); //print the current cell and how many times it was used
}
}
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 30)) //if 0 or negative, or if 31+
{
throw new Exception(); //say no
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer > 9)) //if negative or 10+
{
throw new Exception(); //say no
}
}
}
The logic is broken at the second cycle where you do feel up an array, because success variable isn't reset for a subsequent while loops. It's quite easy to fix it as such:
for (int i = 0; i < numInputs; i++) //from 0 to max number
{
while (!success) //while no valid number
{
try {
numbers[i] = keyboard.nextInt(); //fill the current cell with a number
numberChecker(numbers[i]); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 0 through 9 only, please.");
}
}
success = false; // [amsilf]: That's the cycle reset
}
Probably, java.util.NoSuchElementException occurs and catches the error handling the block.
Use keyboard.hasNextInt() before keyboard.nextInt().
Like this!
try {
keyboard.hasNext(); // here!
numInputs = keyboard.nextInt(); //get a number
numInputChecker(numInputs); //is it valid?
success = true; //ok
}
...
In the last for loop should be that
for(int i = 0; i < count.length; i++) //from 0 to 31(expected)
{
if (count[i] > 0) //if cell not empty
{
System.out.println(i + " " + count[i]); //print the current cell and how many times it was used
}
}
I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}
#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 have this method and it works fine. I need to put a try/catch statement so
the method can continue if the user puts in a letter. I don't know where to put the statement, It seems everywhere I put it it get's wrong. Could somebody please show me where to put this statement?
public void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
number = in.nextInt();
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}
if (!end) {
System.out.println("I cant find number " + number
+ " in the array, please try again ");
}
}
}
Your for loop I can't explain, you need only check values between 0 and 20,
And when you call try catch, you have to skip loop after exception
public static void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number=0;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
//check symbol
try{
number = Integer.valueOf(in.next());
}catch(Exception e)
{
System.out.println("It's not a number! ");
continue; //skip loop
}
if((number>=0)&&(number<=20))
{
System.out.println(array[number]);
end=true;
}
else
System.out.println("I cant find number " + number
+ " in the array, please try again ");
/* why do you use loop here???
* u need to check if number between 0-20
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}*/
}
}
public static void main(String[] args) {
Test test = new Test();
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
System.out.println("Please give an number between 0-20: ");
do{
try{
number = Integer.parseInt(in.next());
}
catch(Exception e){
System.out.println("Please give an number between 0-20: ");
number = -1;
}
}
while(!(number <= 20 && number >=0 ));
System.out.println(array[number]);
}
System.out.println("Please give an number between 0-20: ");
try{
number = in.nextInt();
}catch(Exception e){
number = 1; //Put random number of default number here
}
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);
}