Java Powers display table - java

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.

Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.

Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed

Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();

import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}

Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Related

How do i put the total sum of my input on top of my codes?

First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n

cannot find symbol error in condition of while loop

I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).

Adding numbers 1 to n with a loop

So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1

Mutliple lines of a while loop printing in gui dialog (Java)

I want to print multiple lines of a while loop in 1 gui dialog box.
This is the code I have currently
package Tempconv1;
import javax.swing.JOptionPane;
public class TimesTables
{
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
String multimsg = ("The calculation is " + num1 + " x " + counter + "=" + total);
JOptionPane.showMessageDialog(null, multimsg);
}
JOptionPane.showMessageDialog(null, "All Done");
}
}
It works but prints out "The calculation is 5x1 = 5" and then opens a new message box to show "The calculation is 5x2 = 10".
I want it to print out
The Calculation is 5x1 = 5
The Calculation is 5x2 = 10
etc
All inside 1 textbox
What you are telling your program to do is create a string of the individual calculation, and then create a dialog box. Then do it again for each loop.
You will want to build all of the messages into one string inside your loop, and then create the dialog box outside the loop.
String multimsg = "";
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
multimsg += ("The calculation is " + num1 + " x " + counter + "=" + total);
}
JOptionPane.showMessageDialog(null, multimsg);
you might want to look into using stringbuilder or similar to be more efficient about building the message string. (https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)
The problem is that you are showing the message inside the while loop. The syntax with the while loop can be a little bit confusing.
If you are using java 8 you can replace the while/counter with an IntStream and you can compose the message by joining the Strings in the collector:
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
The first line creates a stream of integers from 1 to 12. The second line maps every number to an individual textmessage. The last line concatenates all the individual messages by joining them with a ,
Your main method would look something like this:
public static void main(String[] args){
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
JOptionPane.showMessageDialog(null, message);
JOptionPane.showMessageDialog(null, "All Done");
}
before loop:String multimsg = "";
in loop after the maths:multimsg=multimsg+"The calculation is " + num1 + " x " + counter + "=" + total;
and after while loop JOptionPane.showMessageDialog(null, multimsg);
Build only the msg inside the loop and save it to StringBuilder.
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
sb.append("The calculation is ").append(num1).append(" x ").append(counter).append("=").append(total).append(" ");
}
JOptionPane.showMessageDialog(null, sb.toString());
JOptionPane.showMessageDialog(null, "All Done");
}

Trying to write to an outfile.txt using variables from an if block

I am trying to write to an outfile.txt using variables that are inside if statements.
when I compile it it keeps saying the variable has not been initialized when in fact they have been, one as a string and char as the other.
import java.io.*;
import java.util.Scanner;
public class program5{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
public static void main(String[] args) throws IOException{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int i, gradeA_count = 0, gradeB_count = 0, gradeC_count = 0,
gradeD_count = 0, gradeF_count = 0, first_grade,
second_grade, third_grade, fourth_grade,
total_of_grades;
String remarks, course_name, semester, instructor_name, student_name;
char grade;
double average_grade;
int[] array_of_int_numbers = new int[10];
Scanner sc = new Scanner(System.in);
// set up a outfile to write to
Writer outfile = new BufferedWriter(new FileWriter("e:outfile.txt"));
// Write the class information to the outfile
outfile.write(" CMPS 161 Program Five, Fall 2015\n\n");
// separate top and next line for ease of sight
outfile.write(" -------------------------------- \n\n");
System.out.println("Enter the course name: ");
course_name=input.readLine();
System.out.println("Enter the Semester: ");
semester=input.readLine();
System.out.println("Enter the Instructor: ");
instructor_name=input.readLine();
outfile.write("Course: " +(String.format("%-8s",course_name))+ " Semester: " +(String.format("%-10s",semester))+ " Instructor: " +(String.format("%-12s",instructor_name))+ "\n\n");
outfile.write("Array Item Student Name T1 T2 T3 T4 Avg Grade Remarks\n\n");
outfile.write("=================================================================\n\n");
// array initialization
for (i = 0; i < 1; i++) array_of_int_numbers[i] = 0;
// prompt user for a value into the array
for (i = 0; i < 1; i++){
System.out.println("Enter a Students Name: ");
student_name=input.readLine();
System.out.println("Enter the first grade: ");
first_grade=sc.nextInt();
System.out.println("Enter the second grade: ");
second_grade=sc.nextInt();
System.out.println("Enter the third grade: ");
third_grade=sc.nextInt();
System.out.println("Enter the fourth grade: ");
fourth_grade=sc.nextInt();
total_of_grades = first_grade + second_grade + third_grade + fourth_grade;
average_grade = (double) total_of_grades / 4.0;
System.out.println("Your average grade is " +(String.format("%.1f",average_grade))+ "\n");
if (average_grade >= 90){
remarks = "Excellent";
grade = 'A';
gradeA_count++;
}else if (average_grade >= 80){
remarks = "Very Good";
grade = 'B';
gradeB_count++;
}else if (average_grade >= 70){
remarks = "Good";
grade = 'C';
gradeC_count++;
}else if (average_grade >= 60){
remarks = "Poor";
grade = 'D';
gradeD_count++;
}else if (average_grade >= 0){
remarks = "Fail";
grade = 'F';
gradeF_count++;
}
outfile.write("["+i+"]"+ student_name +
"" + first_grade +
"" + second_grade +
"" + third_grade +
""+ fourth_grade +
"%" + average_grade +
"" + grade +
"" + remarks + "\n");
}
for (i = 0; i < array_of_int_numbers.length; i++){
System.out.println("array_of_int_numbers["+(i+1)+ "] = "+array_of_int_numbers[i]);
}
System.out.println("Number of A's : " + gradeA_count);
System.out.println("Number of B's : " + gradeB_count);
System.out.println("Number of C's : " + gradeC_count);
System.out.println("Number of D's : " + gradeD_count);
System.out.println("Number of F's : " + gradeF_count);
outfile.close();
} // end program
} // end class
I am new to coding (only my fifth program) and this is my first semester in college, any help would be greatly appreciated.
I am using JGrasp as my professor requires it and coding in java.
Edit:
Here are the exceptions being thrown:
program5.java:107: error: variable grade might not have been initialized
"" + grade +
^
program5.java:108: error: variable remarks might not have been initialized
"" + remarks + "\n");
^
At the beginning of the program, when you declare grade and remarks, you aren't initializing it. You must set these variables to a default value.
For example:
String remarks = "";
char grade = '0';
It doesn't really matter what they're set to right now, because they'll be changed later.
Now, if you know that average_grade will never be negative, then you can replace that last else if statement with a simple else. This is why Java thinks that the variables may not be initialized, because there is the possibility that average_grade could become negative.

Categories

Resources