// The program compiles and runs as it should to compute averages I am just struggling to add negative, and double values to it.
import java.util.*;
public class DoWhileLoops {
public static void main (String [] args) {
Scanner kb = new Scanner(System.in);
int sum = 0,
ct = 0;
String input = "";
do {
System.out.println
("Enter a positive whole number, or q to quit.");
int n=0, sct=0;
char c;
input = kb.nextLine();
do {
c = input.charAt(sct);
if (c >= '0' && c <= '9')
{
n = n * 10;
n += (int)(c - '0');
}
sct++;
} while (sct < input.length());
if (n > 0) {
sum += n;
ct++;
}
} while (!input.equalsIgnoreCase("q"));
System.out.printf("The sum of the %d numbers you entered is: %d\n", ct, sum);
if(ct > 0)
System.out.printf("The average is: %.2f", (double)sum/ct);
else
System.out.printf("No numbers entered - can't compute average");
}
}
//Need help having the program so it will recognize positive and negative values as well as doubles.
You use a Regular Expression (regex) within a String#matches() method to determine if the User has entered a string representation of a valid number of either a signed (negative) or unsigned (positive) integer or double data type value, for example:
if (!input.matches("-?\\d+(\\.\\d+)?")) {
System.err.println("Invalid numerical value supplied! Try again..." + ls);
continue;
}
The regular expression used in the matches() method above is: "-?\\d+(\\.\\d+)?" and here is an explanation of what it means:
When summing, you want to use a double data type variable which means then that when the User supplies a value we want to parse it to a double data type. To do this you can use the Double.parseDouble() method to convert the string numerical value to a double data type and add that value to our summation (the sum variable which we've already declared as double).
Here is what the code might look like:
Scanner kb = new Scanner(System.in);
String ls = System.lineSeparator();
double sum = 0;
int counter = 0;
String input;
do {
System.out.print((counter + 1) + ") Enter a numerical value (or q to finish): ");
input = kb.nextLine();
// If the first character supplied by User is a Q then exit loop
if (Character.toString(input.charAt(0)).equalsIgnoreCase("q")) {
break;
}
// If the value supplied is not a numerical value
// then inform User and let him/her/it try again.
if (!input.matches("-?\\d+(\\.\\d+)?")) {
System.err.println("Invalid numerical value supplied! Try again..." + ls);
continue;
}
counter++;
double num = Double.parseDouble(input);
sum += num;
} while (true); // q must be given to exit loop.
System.out.printf(ls + "The sum of the %d numbers you entered is: %f\n", counter, sum);
if (counter > 0) {
System.out.printf("The average is: %.2f", (double) sum / counter);
}
else {
System.out.printf("No numerical values entered! - Can not compute average!");
}
Related
import java.util.Scanner;
public class Digits {
public static void main(String[] args) {
/*
*
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
*/
//Assignment: fix this code to print: 1 2 3 (for 123)
//temp = 3426 -> 3 4 2 6
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int count = 1;
int temp = input.nextInt();
while(temp >= 10){
count++;
temp = temp / 10;
System.out.print(temp + " ");
}
}
}
Need help fixing code.
Example: when you type 123 it becomes 1 2 3.
Your code is dividing by ten each time, that could be used to print the value in reverse. To print it forward you need a bit more math involving logarithms. Sometime like,
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
int p = (int) (Math.log(temp) / Math.log(10));
int v = (int) (temp / Math.pow(10, p));
System.out.print(v + " ");
temp -= v * Math.pow(10, p);
}
Alternatively, read a line of input. Strip out all non digits and then print every character separated by a space. Like,
String temp = input.nextLine().replaceAll("\\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));
Most of your code is correct, and what you are trying to do is divide by 10 and then print out the value - this probably should have been a modulus operation % to get the remainder of the operation and print that out - but a nice way of thinking about it.
Nevertheless.
You can just use a string and then split the string on each character
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
// we know that we are going to get some input - so we will just grab it as a String
// whilst we are expecting an int - we will test this later.
// we are doing this as it makes it easier to split the contents of a string
String temp = input.next();
// is this an int? - we will test this first
try {
// if this parsing fails - then it will throw a java.lang.NumberFormat exception
// see the catch block below
int test = Integer.parseInt(temp);
// at this point it is an int no exception was thrown- so let's go
// through and start printing out each character with a space after it
// the temp(which is a string).toCharArray returns a char[] which we
// can just iterate through and set the variable of each iteration to 'c'
for (char c : temp.toCharArray()) {
// now we are going to print out the character with a space after it
System.out.print(c + " ");
}
} catch (NumberFormatException ex){
// this is not an int as we got a number format exception...
System.out.println("You did not enter an integer. :(");
}
// be nice and close the resource
input.close();
}
Answering solely your question, you can use this one-line code.
int test = 123;
System.out.println(String.join(" ", Integer.toString(test).split("")));
Output is: 1 2 3
So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.
I've created this code to get unlimited values of integers, store them, and calculate the mean. It also does it in a squared format. My problem is, I created it so that the while loop only stops when the the number 0 is entered. However, I only put it there as a substitute, as it's the only way i could test the rest of the code to ensure it all works.
What I really want to do it have the while loop continue until the user provides input that is not an integer. Ive tried everything, using hasNextint() or nextint and so forth, what can I do?
import java.io.*;
import java.util.*;
public class InputStats {
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
int inputNumber; // One of the integers input by the user.
int sum; // The sum of all the integers.
int count; // The number of integers that have been entered.
double mean; // The mean value of the integers, rounded to 2 decimal places.
int squarein; // Value of squared number.
int sumsquare; // The sum of the squares of all the integers.
double meansquare; // The mean value of the squares of integers, rounded to 2 decimal places.
/* Initialize the summation and counting variables. */
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
/* Read and process the user's input. */
System.out.println("Enter your first positive integer: ");
inputNumber = TextIO.nextInt();
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
squarein = inputNumber; //
sumsquare = squarein * squarein; //square inputs
count++; // Count the input by adding 1 to count.
System.out.println("Enter your next positive integer, or 0 to end: ");
inputNumber = TextIO.nextInt();
}
/* Display the result. */
if (count == 0) {
System.out.println("You didn't enter any data!");
} else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
You should read your values in as a string and then convert them to integers with Integer.parseInt(string);
That way you can use the following function to check if they're integers
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Your program would then look like this:
import java.io.*;
import java.util.*;
public class InputStats {
// *** I added this to help your while loop ***
public static boolean isInteger(String s) {
// check if a string is an integer, eg "10" is 10 but "w" is not an int
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
// *** I added this to store the input as a string first ***
String input; // The original string inputted by the user
int inputNumber;
int sum;
int count;
double mean;
int squarein;
int sumsquare;
double meansquare;
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
System.out.println("Enter your first positive integer: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
// *** I made this while it's an integer so it stops when it's a string ***
while (isInteger(input)) {
inputNumber = Integer.parseInt(input);
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein * squarein;
count++;
System.out.println("Enter your next positive integer, or a non integer to end: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
}
if (count == 0) {
System.out.println("You didn't enter any data!");
}
else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
// *** I removed this because it was no longer needed *** TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
hasNextInt() should work
while(TextIO.hasNextInt()) {
inputNumber = TextIO.nextInt();
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein*squarein;
count++;
System.out.println("Enter your next positive integer: ");
}
Another thing, why do you call TextIO.nextInt() before your System.outs? It doesn't seem necessary and could possibly throw an error.
Use a boolean flag. Set it to false initially and when user has inputted set it to true.
boolean userInputted = false;
while (!userInputted) {
.
.
.
// if user has inputted
userInputted = true;
}
You could have the user input one line of text with numbers separated by commas and use .split(",") to separate into an array of strings, then loop through that array by the .length and apply .trim() to each string to remove trailing space, then use Integer.parseInt(strarray[i]) to convert the strings to integers. And obviously put it all in a try...catch in case the user inputs badly formatted data.
What you need is a way to tell if what the user inputs is a number or something else.
Try something like this function.
//Function to parse the input from provided scanner, and return null
//if input is not a number
public static Integer parsedInputFrom(Scanner sc){
String input= sc.next();
Integer inputNumber=null;
try{
inputNumber = Integer.parseInt(input);
} catch (NumberFormatException n){
return null;
}
return inputNumber;
}
I am a novice programmer trying to write a program that converts an entered Binary number into a decimal number. As far as I can tell, the math and code are right, and no compilation errors are returned, however the number that is output is NOT the correct decimal number. My code is as follows:
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
Any Help you could give would be much appreciated. I tried making my question as clear as possible but if you have any questions I will try to answer the best I can. I have not been doing this long. All I need is for someone to look it over and hopefully find the error I made somewhere, thanks.
Change
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
to
result = result + ((num.charAt(i) - '0') * Math.pow(2, i));
or more compactly,
result += (num.charAt(i) - '0') * Math.pow(2, i);
Remember that the character '0' is not the same thing as the number 0 (same for '1' and 1); num.charAt(i) returns the character not the integer.
int a = '0';
int b = 0;
System.out.println(Math.pow(2, a));
System.out.println(Math.pow(2, b));
Output:
2.81474976710656E14
1.0
Big difference isn't there?
The function String.charAt(); does not return the number 0 or 1 which you can multiply with the bit but the character "id". You need to convert the String / char to a number.
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (Integer.parseInt(num.substring(i,i+1)) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
By the way: Why is a string that does not contain either a 0 or a 1 not a binary numer? Think of 1111 for example. I think you should better check for "neither 0 nor 1"
if (num.indexOf("0")==-1 && num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
Note that num.charAt(i) gives the ASCII code for the character at position i. This is not the value you want. You need to convert each character digit to an int before you do any math with the value.
Integer.parseInt(string, base) parse string into an integer using "base" radix, if it cannot be converted, it raises an exception.
import java.util.Scanner;
public class Convertion {
public static void main(String[] args) {
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number");
num = in.nextLine();
try{
//this does the conversion
System.out.println(Integer.parseInt(num, 2));
} catch (NumberFormatException e){
System.out.println("Number entered is not binary");
}
}
}