So I've been a little stuck with this for a bit now.
I have a program where I'm trying to run two loops, the first loop I'm running will try something until I enter a "ending" character other then my check condition.
My next loop I'm trying to read in (scanner inputs) to check them for a sentinel value (-1) and to collect and do some work with them. Like add then eventually print out after my program is complete. Inputs to read in as an example: try 1: (- 6) 5 4 7 9 -1, try 2: -9 6 9 4 -1.
Numbers have spaces between.
The code works until it arrives at line "int UserValue = YN.nextInt() ;." At this point it throws an error such as exception but not sure why? I'm never able to insert an integer.
I tried creating an internal scanner with different name to see if it was my scanner but the same happened. Reading online about scanners, the embedded scanner is a BIG no no.
Well, thanks for reading and if you have any suggestions I will review them any input will be much appreciated!! Thanks!
import java.util.Scanner; // Importing the java package for reading from users (me)
public class InputScannerWhile {
public static void main(String args[] ) {
Scanner YN = new Scanner(System.in) ; // create new scanner to grab scanner data
System.out.println("Retry: Enter Y/N " ); // enter y or n
String retry = "y" ; // Skip the first run on the code, this will jump right into the while loop
while(retry.equalsIgnoreCase("Y")) { // loop for retry or not code
String IntList = " " ; /// output string is initially empty
int SumValues = 0 ; /// add positive vales
System.out.println("Enter Positive integers (-1 to quit) ") ; // Print prompt for user to
int UserValue = YN.nextInt() ;
while(UserValue != (-1)) {
if(UserValue == (-1)) {
break ;
} // Exit the 1st IF condition for -1 value
if(UserValue != (-1) ) {
SumValues += UserValue ;
IntList += IntList + UserValue + " " ;
System.out.println("Entered numbers: " + IntList );
System.out.println("The Added Values: " +SumValues);
}
} // Exit the second while loop */
System.out.print("Retry: Y/N " ) ; // enter y or n to continue
retry = YN.next() ; // Retry variable
} // Exit the Outside while loop
System.out.println("!!! Program terminated !!!") ;
}
} //public class bracket
error details below***
Retry: Enter Y/N
y
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at InputScannerWhile.main(InputScannerWhile.java:18)
you have an extra sub while loop which is unnecessary and causes a logic error.
Remove this (and the corresponding close curly bracket):
while(UserValue != (-1)) {
Actually you are prompting the message to enter Y/N but you are not taking input from the user... So add the input taking statement before starting the loop. Also one problem will come after that you will run into an endless loop. To get that worked out, take the input for UserValue as well within that loop itself where you are checking otherwise if you once entered a number except -1 then you will run into a forever loop. These changes may get you rid out of the errors (but I don't know whether you will actually be able to achieve what you are aiming through this program since I never got what is you aim through this code...)
Also remove
if(UserValue == (-1)) {
break ;
from your code since that does not have any use (since if UserValue would have been -1, the loop condition must had thrown the control out of the loop.)
I solved it.
There was an issue with the code in a way where i was dropping the scanner input. Also i created a loop that will read values until the sentinel value was entered.
If you would like to discuss the code let me know. I can send if you would like.
Thanks
SVR
You can try this:
import java.util.Scanner;
public class ScannerTest{
public static int enterNum(Scanner sc){
System.out.println("Enter Positive integers (-1 to quit) ") ;
return sc.nextInt();
}
public static String enterRetry(Scanner sc){
System.out.println("Retry: Enter Y/N " );
return sc.next();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String retry = enterRetry(sc);
while(retry.equalsIgnoreCase("Y")) {
int exist = enterNum(sc);
StringBuilder sb = new StringBuilder();
while(exist != -1){
sb.append(exist).append(" ");
exist = enterNum(sc);
}
System.out.println("Values:" +sb.toString());
retry = enterRetry(sc);
}
System.out.println("!!! Program terminated !!!") ;
}
}
Related
So I have an assignment in my CISP 1 class that requires me to create a program that displays a bar chart comprised of asterisks based on the amount of sales 5 different stores have had. I've got a base made, but I still want to add a loop that validates the input from the user(i.e. throws an error when the user tries to enter a negative number), and I want to add the option to run the program or exit it. I'm just a little lost on how to do all of that, so I figured I'd reach out on this website and ask. I know a lot of this code could be simplified with arrays, but we haven't started studying that yet - so I'm afraid to be messing with something I don't fully understand. Below is my code:
import java.util.Scanner;
public class BarChart
{
public static void main(String[] args)
{
int store1, store2, store3, store4, store5;
Scanner keyboard = new Scanner(System.in);
System.out.println("This program will display a bar chart " +
" comprised of astericks based on five different stores' " +
"sales. 1 asterick = $100 in sales.");
System.out.print("Enter today's sales for store 1: ");
store1 = keyboard.nextInt();
System.out.print("Enter today's sales for store 2: ");
store2 = keyboard.nextInt();
System.out.print("Enter today's sales for store 3: ");
store3 = keyboard.nextInt();
System.out.print("Enter today's sales for store 4: ");
store4 = keyboard.nextInt();
System.out.print("Enter today's sales for store 5: ");
store5 = keyboard.nextInt();
System.out.println("Sales \t Bar Chart");
System.out.println("----- \t ---------");
System.out.print("\nStore 1: ");
for (int num = 0; num < store1; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 2: ");
for (int num = 0; num < store2; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 3: ");
for (int num = 0; num < store3; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 4: ");
for (int num = 0; num < store4; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 5: ");
for (int num = 0; num < store5; num += 100)
{
System.out.print("*");
}
}
}
I've tried adding if statements each time the user is asked to enter a sales amount, but that didn't work.
I still want to add a loop that validates the input from the user(i.e.
throws an error when the user tries to enter a negative number)
Here's a quick example that shows how to ask again when an invalind number is entered:
do {
System.out.print("Enter today's sales for store 1: ");
store1 = keyboard.nextInt();
if (store<0) {
System.out.println("Sales must be non-negative!");
}
while (store<0);
I want to add the option to run the program or exit it.
This would be similar to the do { ... } while( ... ); above except you'd put the whole program from below the Scanner line inside the body of the do loop. Then you just ask at the bottom if they want to start over and write your conditional statement in the while portion appropriately.
pls take the time to read through
Solution to the problem
do-while loop
What you're looking for is a while loop that this answer suggests, however you can specify whether to force the user to retry, or break the program and throw an error.
If you'd like to make the user retry and not throw an error that makes the program break, possibly with a retry message every time the user inputs negative numbers, you can use a do-while loop. The do-while loop will execute as "do this then check" rather than the while loop being "check than do this" (you can ensure that your code is more concise this way).
The do-while loop version:
int input; // Declare the variable to be initialized inside the do {} block.
int storeSales; // You can just relax and declare here.
do { // This is the start of the do-while loop
System.out.print("..."); // Your prompt goes here
storeSales = scanner.nextInt(); // Grabbing input from the user
if (storeSales < 0) { // Checking if the input is smaller than 0
System.out.print("..."); // Your message when input is invalid
}
} while (storeSales < 0); // The condition goes here
The caveat of the do-while loop for situations like this is for having conditions in the while loop that the do block will be always executed at least once, requires a variable that isn't initialized first but initialized in the loop itself. Initializing a "user input" variable but then giving it a value of "value that makes a statement work" makes the code awkward and dirty.
while loop
The while loop version will look like this:
int storeSales = -1; // You have to initialize first here, since the while is checked first.
while (storeSales < 0) { // Awkward!
System.out.print(""); // Your prompt goes here
storeSales = scanner.nextInt(); // Grabbing input from the user
if (storeSales < 0) { // Checking if the input is smaller than 0
System.out.print(""); // Your message when input is invalid
}
}
Exceptions
If instead, you'd like to break the program when the input is invalid (smaller than 0):
Introducing the throw statement:
Try this code out:
public class BarChart {
public static void main(String[] args) {
System.out.println(5 / 0);
}
}
You'll yell at me: WTF is this, you're making a program that throws ArithmeticException runtime exception! Division by 0 doesn't make sense!
Well, that's the point. Exceptions in Java are those that happen during runtime because of some condition that doesn't have to do with syntax, clear mistakes like String x = 0, etc. That's the kind of exception you're looking for. To throw such an error similar to the example above , use the throw statement and don't use a loop:
int storeSales = scanner.nextInt();
if (storeSales < 0) {
// Since the exception is related to math, you can use something like ArithmeticException. Your choice though.
throw new ArithmeticException(); // An exception is also an object, so you initialize it that way.
}
CAVEAT, Java doesn't expect exceptions in the first place, and so you have to declare that your method throws exceptions. Even main(). And when you call OTHER methods that ALSO have exceptions, you either have to handle them with a try-catch block, or leave it and add the exceptions to the method definition. But that's for another day I guess.
General improvements
You're doing the same thing, same code, same names (essentially), same print() statements a hard-coded 5 times! You can use a for loop. Unless your names have to be unique and declared separately (which I digress, you names are literally store1, store2, store3, etc.) you can just use a general, reinitialized variable name in every iteration of the for loop.
You can also scan the user input about how many stores (instead of hard-coding 5) to show the data, to make the program completely soft-coded and dynamic (The assignment probably doesn't require you this, refactor the code to your needs)
This code below will be grabbing the user input, then printing it out INSTANTLY AFTER. Now that I look at your solution, maybe it was right after all to define separate variables instead of putting the input in an array, since you want all the input at once then print everything at once.
Here's how it goes:
// You'd want to reformat the code to your preference.
import java.util.Scanner;
public class BarChart {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int storeCount = scanner.nextInt();
for (int i = 0; i < storeCount; i++) { // A loop that repeats 5 times.
// Choose one of the three solutions above and insert them here, I choose the do-while since it's the cleanest
int storeSales;
do {
// You can "concatenate" strings (numbers becomes themselves but in text)
System.out.print("Enter today's sales for store " + (i + 1) + ": ");
storeSales = scanner.nextInt();
if (storeSales < 0) {
System.out.print("Sales cannot be negative, please try again");
}
} while (storeSales < 0);
// Now that the storeSales value has been definitely initialized (or you chose the exceptions solution, I don't blame you) the printing goes here.
System.out.println("Store " + (i + 1) + "'s sales:");
for (int j = 0; j < storeSales; j += 100) {
System.out.print("*");
}
System.out.println();
}
}
}
There's not much to do with your code otherwise, since without the use of arrays, the best you can do is define separate variables, then having a method or two (a reusable piece of code with a name) to do the inputting and printing job for you to make the code cleaner and less repetitive.
In the end, just choose one of the three solutions and apply them to each of your variables. Your code is quite good (if it's intended this way). CHEERS!
oh my god someone read till the end of the post i love you
Scanner keyboard = new Scanner(System.in); // initialize scanner
while (true) { // infinite loop starts
<Do something...> // here you can do the things you need to do (e.g., change variables or record input)
if (condition) { // condition for exiting the loop (e.g., input of positive number)
break; // exiting infinite loop
} // end of IF statement
} // end of WHILE statement
You can use it as separate method and validate each input. It will not let the user to proceed until the valid value will be inputted.
I'm trying to allow the user to put in multiple inputs from the user that contain a char and integers.
Something like this as input: A 26 16 34 9
and output each int added to an array.
I was thinking I could have the first input as a character and then read the rest as a string which then I separate and put into an array.
I'm not new to coding but new to java. I've been doing c++ so the syntax is a bit different.
This is what I have so far, I haven't set up my array yet for the integers.
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
int firstNumber;
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
int n = reader.nextInt();
if (n=='A') {
//if array is full System.out.println("The list is full!");
//else
System.out.println("Integer " + " " + "has been added to the list");
}
else if (n=='Q') {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Could you specify better how should your input be given? From your question, if I understand well, the user simply type "A" followed by a list of numbers separated by a space. So I would simply read the next line, split it in words (separated by a space) and check if the first word is the letter "A". Here it goes:
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
String line = reader.nextLine();
String[] words = line.split(" ");
if (words.length > 0 && words[0].equals("A")) {
//if array is full System.out.println("The list is full!");
// => I don't understand this part
//else
for(int i = 1; i<words.length; i++){
int integer = Integer.parseInt(words[i]);
System.out.println("Integer " + integer + " has been added to the list");
//do your stuff here
}
}
else if (words.length > 0 && words[0].equals("Q")) {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Note that in your solution, you read the next int from your scanner and then try to compare it with the character 'A'. This will not work because A is not an int. If you really want to get the first character from your scanner, you could do:
String line = reader.nextLine();
if(line.length() > 0){
char firstChar = line.charAt(0);
//do your stuff here
}
A character is not an int. You cannot read an int to expect something like 'A'. You can read a String and take its first character though. Scanner doesn't offer a convenient method to read the next String and expect it to be only one-character long. You'd need to handle that yourself.
But considering you don't know in advance how many numbers there will be to read, your solution to read the entire line and interpret it entirely, is the better one. That means you can't use nextInt() nor nextDouble() nor next() nor nextWhateverElse().
You need nextLine(), and it will give you the entire line as a String.
Then you can split() the result, and check if the first is one-char-long. Then you can parse all the others as int.
I don't immediately recall how to write this in Java – it's been a bit of a while – but what I'd do is to first separate the string by spaces, then attempt to do ParseInt on each piece.
If the string isn't a valid integer, this method will throw an exception, which you can catch. So:
If you make it to the next statement, an exception didn't happen, so the value is an integer.
If, instead, you find yourself in the exception-handler (having caught [only ...] the expected kind of exception, the value is a string.
Of course, don't "catch" any exception-type other than the NumberFormatException that you're expecting.
By the way, it is perfectly routine to use exceptions in this way. Let Java's runtime engine be the authority as to whether it's an integer or not.
public class Two {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
while(obj.nextInt() > 5)
{
System.out.println(obj.nextInt());
}
}
}
If i input the number ( > 5) for first time there is no output on the console but if i input a number on second try there is output on the console.
So I get an output alternatively.
Can anyone explain why is it so?
The java.util.Scanner.nextInt() method Scans the next token of the input as an int and returns it. After the token is read another nextInt()-Call will read (as the name says) the next Integer.
I think you were expecting something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int read;
while((read = scanner.nextInt()) > 5)
{
System.out.println(read);
}
}
Now the read Integer is stored in the variable read and is printed, if it was greater than five.
The reason you're getting output every other input is because you're prompting the Scanner object to gather input twice within your loop system. Every time you call a next... method on your Scanner you are prompting the user.
So in your condition for the while loop you are asking the user to input a value integer value which is then compared against 5. THEN, in your print statement you call the nextInt() method again, which will then prompt the user again for another value integer input.
So given a series of 6 integer inputs for your current loop, 6 2 10 4, you loop will only print 2 and 4.
Instead, you should prompt and store once outside of your loop, then test with the condition and reprompt after the print within the loop like so...
int input = obj.nextInt();
while (input > 5){
System.out.println(input);
input = obj.nextInt();
}
Need to write a java program from pseudo code, I've got a bit of code written, its not working and I'm not sure if i've done it right or not as I simply tried to follow the pseudo code -
Read i
While i > 0
Print the remainder i % 2
Set i to i / 2
import java.util.Scanner;
import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
int i = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
while (!scan.hasNextInt()) // while non-integers are present
{
scan.next();
System.out.println ("Bad input. Enter an integer.");
}
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
}
}
Frankly speaking, you didn't(Ah missed it earlier) exactly followed the pseudo-code. The pseudo code tells you to read i, whereas you are reading input. That's one problem.
Second problem is that, you should read the input outside the while loop where you are doing the processing with the input. That is the 2nd thing you didn't followed.
Currently your while loop is: -
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
This is read input from user on every iteration which you don't want.
So, you need to modify your code a little bit: -
int i = scan.nextInt(); // Read input outside the while loop
while (i>0) // while greater than 0
{
System.out.println (i%2);
i = i/2; // You don't need a bracket here
}
How about:
System.out.println(Integer.toBinaryString(i));
The pseudo code reads first (outside the loop), but in your code you read second (inside the loop)
I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?
The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.