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)
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.
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 !!!") ;
}
}
I'm currently working on a small project for an introductory java class. We're supposed to make a program which can take in an integer from the user and output the number of odds, evens, and zeroes present within the code. This seemed pretty easy to me, and I managed to implement the code, but a class mate, after I criticized his code for incorrectly following the prompt, noted that my code would crash if anything but digits was input.
Out of spite I've tried to go beyond the prompt and have the program output an error message if it encounters characters aside from digits (instead of having my compiler return an error). However I'm returning multiple errors within the Eclipse compiler when using the isDigit method in the Character class.
I don't know exactly what's causing this, and I feel I must be missing something crucial, but my teacher quite frankly isn't qualified enough to understand what's causing the error, and none of my classmates can seem to figure it out either.
package ppCH5;
import java.util.Scanner;
public class PP5_3
{
public static void main(String[]args)
{
int even = 0;
int odd = 0;
int zero = 0;
int num = 0;
int count = 0;
boolean inputError = false;
System.out.println("please provide some integer");
Scanner scan = new Scanner(System.in);
String numbers = scan.next();
scan.close();
Scanner intSeperate = new Scanner(numbers);
intSeperate.useDelimiter("");
while(intSeperate.hasNext())
{
if(Character.isDigit(numbers.charAt(count)))
{
count++;
num = intSeperate.nextInt();
if((num % 2)==1)
odd++;
if((num % 2)==0)
if(num==0)
zero++;
else
even++;
}
else
{
count++;
inputError = true;
}
}
intSeperate.close();
if(!inputError)
{
System.out.println("There are " + even + " even digits.\n" + odd + " odd digits.\nAnd there are " + zero + " zeros in that integer.");
}
else
{
System.out.println("You have provided a disallowed input");
}
}
}
Any help would be appreciated, I'm currently at a loss.
When you enter a single non-digit character, say a, the else branch inside the while loop will get executed, incrementing count, right? And then the loop will start a new iteration, right?
In this new iteration, intSeparator.hasNext() still returns true. Why? Because the input a is never read by the scanner (unlike if you have entered a digit, intSeparator.nextInt would be called and would have consumed the input).
Now count is 1 and is an invalid index for the 1-character string. Therefore, numbers.charAt(count) throws an exception.
This can be avoided if you break; out of the loop immediately in the else block:
else
{
inputError = true;
break;
}
Also, don't close the scan scanner. scan is connected to the System.in stream. You didn't open that stream, so don't close it yourself.
My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);
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.