I have a Printf formating question. I am to print only 10 numbers, before going to the next line and printing 10 more numbers and so on. with the end goal being like a table, with all the columns lining up and being aligned to the right. I am using a while statement as well. I have tried a few different things that I have found in my research, with no success. Would I use a different print statement for it other than Printf? Such as Print, or PrintLn? Also thought about using an If statement as well. Any help would be greatly appreciated! Thank you.
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
}
Using a MOD condition, You can ensure 10 output per line.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while (sqrt < n) {
sqrt = Math.pow(startNum, 2);
if(startNum != 0 && startNum % 10 == 0) {
System.out.println();
}
System.out.printf("%6.0f", sqrt);
startNum++;
}
}
}
Output -
Please enter a maximun integer value: 150
The number you entered was: 150
Squares less than 150 are: 0 1 4 9 16 25 36 49 64 81
121 144 169
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
if(startNum%10==0){
System.out.printf("/n");
}
}
Related
This is related to java.
I am trying to find out numbers in a range which are divisible a particular number say X. Also the digits of the number are divisible by the number X.
For Ex: Range 30 to 40
so the number 30,33,36,39 are divisible by 3 and also the digits are divisible by 3.
But in the code written form my end the loop logic seems not to be correct as it gives me only 30 and 33 as the output.
Can you please help me to understand this please?
Code:
public class Char{
public static void main(String args[]){
//Fill the code
int m,n,i,z = 0;
int x = 3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the range for shipment numbers :");
m = sc.nextInt();
n = sc.nextInt();
//while (m!=0 && n!=0){
System.out.println("Possible shipment numbers :");
for (i=m;i<=n;i++){
if(i%10==z){
if(z%x==0);
z=i/10;
System.out.println(i);
}
}
}
}
Code:
You need to iterate over each digit of the main loop's variable, i. You need an inner loop (the 'while' below) to check each digit of i:
int m, n, i, z = 0;
int x = 3;
boolean div;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the range for shipment numbers :");
m = sc.nextInt();
n = sc.nextInt();
System.out.println("Possible shipment numbers :");
for (i = m; i <= n; i++) {
z = i;
div = true;
while (z > 0) {
if (z % 10 % x != 0) {
div = false;
break;
}
z /= 10;
}
if (div) System.out.println(i);
}
Now this works for much larger number ranges as well. So for example, a run gives:
Enter the range for shipment numbers : 300 400 Possible shipment
numbers : 300 303 306 309 330 333 336 339 360 363 366 369 390 393 396
399
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: output the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, and output the individual digits of 4000 as 4 0 0 0 and the sum as 4.
Moreover, the computer always adds the digits in the positive direction even if the user enters a negative number. For example, output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the question I'm having minor difficulties with, the only part I can't figure out is how can I print the single integers in the order that he wants, from what I learned so far I can only print them in reverse. Here's my code:
import java.util.*;
public class assignment2Q1ForLoop {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
int usernum, remainder;
int counter, sum=0, N;
//Asaking the user to enter a limit so we can use a counter controlled loop
System.out.println("Please enter the number of digits of the integer");
N = console.nextInt();
System.out.println("Please enter your "+N+" digit number");
usernum = console.nextInt();
System.out.println("The individual numbers are:");
for(counter=0; counter < N; counter++) {
if(usernum<0)
usernum=-usernum;
remainder = usernum%10 ;
System.out.print(remainder+" ");
sum = sum+remainder ;
usernum = usernum/10;
}
System.out.println();
System.out.println("the sum of the individual digits is:"+sum);
}
}
You have to storeremainder variables in an array and then print them in the loop from last index to first as shown in this tutorial.
You can either store digits in array and then print them, or you can try something like that:
final Scanner console = new Scanner(System.in);
System.out.println("Please enter your number");
final int un = console.nextInt();
long n = un > 0 ? un : -un;
long d = 1;
while (n > d) d *= 10;
long s = 0;
System.out.println("The individual numbers are:");
while (d > 1) {
d /= 10;
final long t = n / d;
s += t;
System.out.print(t + " ");
n %= d;
}
System.out.println();
System.out.println("the sum of the individual digits is:" + s);
An idea would be : convert int to string and write a method
getChar(int index) : String
which gives you for example 4 from 3456 with
getChar(2);
See Java - Convert integer to string
Here, I wrote a code for your problem with using a stack. If you want a simple code, you can comment my solution and I will wrote another one.
Scanner c1 = new Scanner(System.in);
System.out.print("Enter the number: ");
int numb = c1.nextInt();
numb = Math.abs(numb);
Stack<Integer> digits = new Stack<Integer>();
while(numb>0){
int n = numb%10;
digits.push(n);
numb = numb/10;
}
int sum = 0;
while(!digits.isEmpty()){
int n = digits.pop();
sum+=n;
System.out.print(n+" ");
}
System.out.print(sum);
My program is meant to add up all the even integers between 2 and an input number which is between 20 and 60. The logic for that is correct and will work, but it's supposed to be able to run again if the user wishes, and when it runs again, the input only changes if you input a new integer higher than the previous iteration. If you enter one lower, it just uses the same integer input as before. Here is the code:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number
for no): ");
restart = scan.nextInt();
} while (restart == 1);
}
}
So for example, if I enter 20 as the input, the program outputs:
Sum of even numbers between 2 and 20 is: 110
Enter a new value? (1 for yes, any other number for no):
and then I enter 30 (same run of the program):
Sum of even numbers between 2 and 30 is: 240
Enter a new value? (1 for yes, any other number for no):
and then I try to enter 20 again:
Sum of even numbers between 2 and 20 is: 240
Enter a new value? (1 for yes, any other number for no):
(Should clearly be 110, not 240)
My initial thought was that it wasn't actually scanning for a new input on the second iteration, but because it will work if I keep giving it inputs of greater value I know that is not true.
Use this code inside main()
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
i = 2;
sum = 0;
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number for no): ");
restart = scan.nextInt();
} while (restart == 1);
I have an assignment where I am supposed to determine whether the average of three values is 'above average' or 'below average'. For some reason whatever is input will always be above average as the result. Here is my code below, thank you for any help!
import java.util.Scanner;
class Lesson_12_Activity_One {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter three values");
double x = scan.nextDouble();
double y = scan.nextDouble();
double z = scan.nextDouble();
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
}
The average is t/100 but in your condition you test if t > 89.5 (which is always true since t is the average multiplied by 100).
Just remove both the multiplication by 100 and the division by 100. They don't seem necessary.
double t = Math.round((x+y+z)/3);
System.out.print("The average is " + t);
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
if(t/100 >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
by the way why are you multiplying and then dividing by 100?
I'm gonna guess that you're mixing up perunages and percentages. That means, at one point in your program you use 0.5 and in the other 50, both as 50%.
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
With x, y and z all as 50, this will output 50. t = 100 * (50 + 50 + 50)/3 = 5000, the output is (t/100) = 50.
if(t >= 89.5) however tests with t = 5000.
To solve this, go down one of two paths.
Replace all percentages for perunages. This means inputting numbers from 0 to 1.
To do this, do the following:
change your t-initialization for double t = (double)Math.round(1000*((x+y+z)/3)) / 1000 This will make T be in between 0 and 1 with 3 digits precision.
Replace your if with if (t >= 0.895)
Replace all perunages with percentages. This means inputting numbers from 0 to 100.
To do this, remove the 100* from your double t = (double)Math.round(100*((x+y+z)/3));, and the /100 from the output message.
This program will calculate the average grade for 4 exams using a for loop by prompting
the user for exam grades, one at a time, then calculate the average and display the result.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i <= 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
if (i == 4) {
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
}
}
} // end main ()
} // end class ExamsFor4
My result:
Please enter the first exam: 100
Please enter the next exam: 99
Please enter the next exam: 98
Please enter the next exam: 97
Please enter the next exam: 96
The total sum for all 4 exams is 394
The average for the exams entered is 98.50.
This would be correct except for the last print out of: 'Please enter the next exam: 96'
I tried putting the IF statement between the 'sum' line and the TextIO.put 'Enter next exam', but that isolates it.
Thanks, from a Network Dude trap in a Programmer's world.
You have what is called an off-by-one error, compounded by the fact that you're convoluting your loop logic unnecessarily.
With regards to the loop, I recommend two things:
Don't loop for (int i = 1; i <= N; i++); it's atypical
Do for (int i = 0; i < N; i++); it's more typical
Instead of checking for the last iteration to do something, refactor and take it outside of the loop
Related questions
What is exactly the off-by-one errors in the while loop?
See also
Wikipedia/Off-by-one error
On Double Avg
In Java, variable names start with lowercase. Moreover, Double is a reference type, the box for the primitive double. Whenever possible, you should prefer double to Double
See also
Java Language Guide/Autoboxing
JLS 5.1.7 Boxing Conversion and 5.1.8 Unboxing Conversion
Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives
Related questions
What is the difference between an int and an Integer in Java/C#?
Java: What’s the difference between autoboxing and casting?
Why does int num = Integer.getInteger(“123”) throw NullPointerException?
Why does autoboxing in Java allow me to have 3 possible values for a boolean?
Is it guaranteed that new Integer(i) == i in Java? (YES!!!)
When comparing two Integers in Java does auto-unboxing occur? (NO!!!)
Java noob: generics over objects only? (yes, unfortunately)
Rewrite
Here's a way to rewrite the code that makes it more readable. I used java.util.Scanner since I don't think TextIO is standard, but the essence remains the same.
import java.util.*;
public class ExamsFor4 {
public static void main(String[] arguments) {
Scanner sc = new Scanner(System.in);
final int NUM_EXAMS = 4;
int sum = 0;
for (int i = 0; i < NUM_EXAMS; i++) {
System.out.printf("Please enter the %s exam: ",
(i == 0) ? "first" : "next"
);
sum += sc.nextInt();
}
System.out.printf("Total is %d%n", sum);
System.out.printf("Average is %1.2f%n", ((double) sum) / NUM_EXAMS);
}
}
An example session is as follows:
Please enter the first exam: 4
Please enter the next exam: 5
Please enter the next exam: 7
Please enter the next exam: 9
Total is 25
Average is 6.25
Note that:
Only necessary variables are declared
The loop index is local only to the loop
There are no cluttering comments
Instead, focus on writing clear, concise, readable code
If it makes sense to make something final, do so
Constants in Java is all uppercase
Related questions
Why does (360 / 24) / 60 = 0 in Java
Because it performs integer division. This is why the cast to (double) prior to the division in above code is necessary, so that it performs floating point division.
How does the ternary operator work?
This is the ?: operator in above code, also known as the conditional operator.
See also: JLS 15.25 Conditional Operator ?:
Change your end condition to be strictly less than 4 and put the code that prints out the total and average outside the loop.
You should probably put the if-statment outside the for-loop. That way you don't need the if-statement. Second the statement in the loop should be < 4 instead of <= 4.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i < 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
}
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
} // end main ()
}
Just making few changes in your code makes it work. But you should follow cleaner approach as proposed in some of answers.
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
sum += inputNumber;
for ( i = 1; i < 4; i++ ) {
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
sum += inputNumber; // Add inputNumber to running sum.
}
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
} // end main ()
} // end class ExamsFor4
import java.util.Scanner;
public class ExamsFor4 {
public static void main(String[] arguments) {
int sum = 0; // The sum of the exams.
int i = 1; // Number of exams.
double avg = 0; // The average of the exams.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the first exam: ");
sum += in.nextInt();
i++;
while(i<=4){
System.out.print("Please enter the next exam: ");
sum += in.nextInt();
if(i==4)
break;// this line is so that it wont increment an extra time.
i++;
}
System.out.println("The total sum for all " + i +" exams is " + sum);
avg = ((double)sum/i);
System.out.println("The average for the exams entered is" + avg);
} // end main ()
} // end class ExamsFor4