New to programming here. I need to write application that does the following...
Squaring application instructions
The code I have so far follows. I am running into a problem where my code will not read from negative integers to strings and properly prompt the user to enter valid data. I believe I need to nest my loops but am having trouble doing so. Any help would be greatly appreciated. Thanks.
import java.util.Scanner;
public class Squaring {
public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}
Without any try-catch:
public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;
while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");
if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();
if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = getValidInt(1, scan);
System.out.println(a);
int total = 0;
long n = a;
while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}
System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}
I've come up with the following:
public static int getValidInt(int greaterThan, Scanner scan) {
int number = greaterThan;
do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();
if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}
} while (number < greaterThan);
return number;
}
It has a do while loop which makes sure number cannot be smaller than greaterThan, if it is it will do the while loop again.
Inside the do while loop is another loop which tells the user that their input is garbage, and will continue doing so until a number is inserted.
Related
Here is my code:
System.out.print("Enter the number of ROWS and COLUMNS of the array : ");
Scanner sc = new Scanner(System.in);
int numRows = sc.nextInt();
int numColumns = sc.nextInt();
import java.util.Scanner;
public class ArrayRowColumnInputVerify {
public static void main(String[] args) {
int rows = accept_user_input("ROWS");
int cols = accept_user_input("COLUMNS");
System.out.println("The rows and columns you entered are : " +rows + " rows & " + cols + " columns.");
}
public static int accept_user_input(String dimension) {
int input_dimension=0;
boolean input_correct=false;
while(!input_correct) {
System.out.print("Please, enter the number of " + dimension + " of the array : ");
Scanner sc = new Scanner(System.in);
input_dimension = sc.nextInt();
if (input_dimension>0) {
input_correct=true;
} else {
System.out.print("The number you entered " + input_dimension + " must be greater than 0. ");
}
}
return input_dimension;
}
}
I hope the above helps. If you need help understanding the code I will be happy to explain.
boolean b = (numRows > 0 && numColums > 0);
System.out.println("Each number is > 0" + b);
b will be false if one of the numbers is <= 0;
b will be true if both > 0
Since you want the input to be simultaneous maybe try :
import java.util.Scanner;
public class ArrayRowColumnInputVerify2 {
public static void main(String[] args) {
int[] dimensions = accept_user_input("ROWS & COLUMNS");
System.out.println("The rows and columns you entered are : " +dimensions[0] + " rows & " + dimensions[1] + " columns.");
}
public static int[] accept_user_input(String dimension) {
int rows=0;
int cols=0;
boolean input_correct=false;
while(!input_correct) {
System.out.print("Please, enter the number of " + dimension + " of the array : ");
Scanner sc = new Scanner(System.in);
rows = sc.nextInt();
cols = sc.nextInt();
if (rows>0 && cols>0) {
input_correct=true;
} else {
System.out.print("The number you entered : rows:" + rows + " & cols:"+ cols + " must be greater than 0. ");
}
}
int[] input = {rows, cols};
return input;
}
}
Simplified further:
import java.util.Scanner;
public class ArrayRowColumnInputVerify2 {
public static void main(String[] args) {
int rows=0;
int cols=0;
boolean input_correct=false;
while(!input_correct) {
System.out.print("Please, enter the number of ROWS & COLUMNS of the array : ");
Scanner sc = new Scanner(System.in);
rows = sc.nextInt();
cols = sc.nextInt();
if (rows>0 && cols>0) {
input_correct=true;
} else {
System.out.print("The number you entered : rows:" + rows + " & cols:"+ cols + " must be greater than 0. ");
}
}
System.out.println("The rows and columns you entered are : " +rows + " rows & " + cols + " columns.");
}
}
My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}
I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.
In this java program you (the user) keeps entering numbers until you enter a zero, which is when the list terminates. It will compute the sum of positive even & sum of odd even and negative numbers. It will also compute the average.
I'm stuck at the part to get the average of sum of even positive numbers, sum of odd positive numbers, and sum of negative numbers.
import java.util.*;
class sumPositiveAverage {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println ("Enter numbers. List terminates when you enter a zero.
Enter a zero when you want to begin the addition.");
int a = sc.nextInt();
int esum=0;
int osum=0;
int nsum=0;
while (a !=0)
{
if (a>0)
{
if (a%2==0)
{
esum = esum+a;
}// end of 3rd innermost if statement
else
{
osum = osum+a;
}// end of 3rd else statement
}//end of 2nd middle if-else-loop
else if (a<0)
{
nsum=nsum+a;
}//end of 2nd middle else statement
}//end of while loop
System.out.println ("The sum of even positive numbers is "+esum);
System.out.println ("The sum of odd positive numbers is "+osum);
System.out.println ("The sum of negative numbers is "+nsum);
}//end of main
}//end of class2
import java.util.*;
public class sumPositiveAverage {
public static void main(String[] args)
{
int sum_even = 0;
int sum_odd = 0;
int sum_negative = 0;
int sum_positive = 0;
int count_even = 0;
int count_odd = 0;
int count_negative = 0;
int count_positive = 0;
double avg_sum_even = 0;
double avg_sum_odd = 0;
double avg_sum_negative = 0;
double avg_sum_positive = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
int data = 0;
do
{
System.out.print("Type in a positive or negative number and press enter key, if 0 is entered program stops: ");
data = input.nextInt();
if(data > 0){
if(data%2 == 0){
//even number
sum_even = sum_even + data;
count_even++;
}else{
//odd
sum_odd = sum_odd + data;
count_odd++;
}
sum_positive = sum_positive + data;
count_positive++;
}else if(data < 0) {
//negative number
sum_negative = sum_negative + data;
count_negative++;
}
}
//Stops if the value of data is ZERO(0) and continues if it's not
while(data != 0);
//here means zero has been entered
if(count_positive > 0) { avg_sum_positive = (double)sum_positive/count_positive; }
if(count_negative > 0) { avg_sum_negative = (double)sum_negative/count_negative; }
if(count_even > 0) { avg_sum_even = (double)sum_even/count_even; }
if(count_odd > 0) { avg_sum_odd = (double)sum_odd/count_odd; }
System.out.println("Sum of Positive Numbers = " + sum_positive);
System.out.println("Sum of negative Numbers = " + sum_negative);
System.out.println("Sum of odd Numbers = " + sum_odd);
System.out.println("Sum of even Numbers = " + sum_even);
System.out.println("Count of Positive Numbers = " + count_positive);
System.out.println("Count of negative Numbers = " + count_negative);
System.out.println("Count of odd Numbers = " + count_odd);
System.out.println("Count of even Numbers = " + count_even);
System.out.println("Average of Positive Numbers = " + avg_sum_positive);
System.out.println("Average of negative Numbers = " + avg_sum_negative);
System.out.println("Average of odd Numbers = " + avg_sum_odd);
System.out.println("Average of even Numbers = " + avg_sum_even);
}//closing main
} // closing class
I am trying to have the code listed below receive an int input from user, then find amount of even numbers in that int. I'm getting an error when I try to print the return... any help?
import java.util.Scanner;
public class evenDigits {
public static int countEvenDigits(int number){
if (number == 0)
return 0;
else{
int lastDigit = number % 10;
int result = countEvenDigits(number / 10);
if (lastDigit % 2 == 0)
return result + 1;
else
return result;
}
}
public static void main(String[] args) {
System.out.println("Please enter an integer.");
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt();
countEvenDigits(number);
System.out.println("There are " + result + " even digits in " + number);
}
}
Specifically, there is an error in this statement:
System.out.println("There are " + result + " even digits in " + number);
In main you need to change:
countEvenDigits(number);
to:
int result = countEvenDigits(number);
Otherwise, you're accessing a nonexistent variable in your println