The If statement in my for loop is acting strangely - java

My program takes user input to create a sport score table.
Its validation function prints "Invalid input" when the array "words" contains less than 4 elements
for (int i = 0; i < counter; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input into 4 strings
if (words.length != 4) { // If the length of the array elements does not equal 4 then print error message
System.out.println("Input was not valid");
When I enter an incorrect input FIRST, it then makes the rest of the following scores to be deemed equally incorrect even when they are correct - here is an example of what that looks like on the text console.
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 :
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 : 1
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 : 1
Home team : Away team : Home score : Away score
Leeds : Liverpool : 2 : 1
Home team : Away team : Home score : Away score
quit
Input was not valid
Input was not valid
Input was not valid
Input was not valid
Totals
------------------------- Total games played: 0*
END--
This is where I think the problem is:
for (int i = 0; i < counter; i++) {
String[] words = football_list[i].split(":"); 4 strings
if (words.length != 4) {
System.out.println("Input was not valid");
counter--;
i--;
} else {
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " [" + words[3].trim() + "]"); // Formats and prints the output
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" Totals ");
System.out.println("-------------------------");
System.out.println("Total games played: " + counter);
}
}

Don't decrement i inside the loop.

Because you decrement i and counter if input is invalid. And after that increase i in for-statement. In this case you are reading invalid row again and again while counter > i

To make things more readable and less error prone, you could simply use the length of your array to control your loop ending, and increment counter (starting at 0) only when the input is valid :
int counter = 0;
for (int i = 0; i < football_list.length; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input into 4 strings
if (words.length != 4) { // If the length of the array elements does not equal 4 then print error message
System.out.println("Input was not valid");
} else {
counter++;
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["
+ words[3].trim() + "]"); // Formats and prints the output
}
}

Related

Parking Lot doesn`t save in matrix more than 1 line

So I have this project for my college and I'm stuck here, I tried everything I had in mind to make this code save more than 1 slot, as I must save up to 100 into a matrix database. Everything works great but the program always overwrites the first line, never passes on to the second...Here's the code:
Reserve part method:
for (n=1; n<100; n++) {
parkinglot[n][0] = Integer.toString(n);
parkinglot[n][1] = JOptionPane.showInputDialog(null, "License plate: ").toUpperCase();
String hourofreservation = JOptionPane.showInputDialog(null, "Reservation hour(hh:mm): ");
parkinglot[n][2] = hourofreservation;
parkinglot[n][3] = formatter.format(date);
parkingtime = Integer.parseInt(JOptionPane.showInputDialog(null, "Hours : "));
parkinglot[n][4] = Integer.toString(parkingtime);
int totalfee = (toMinutes(parkingtime)/30) * fee;
pay(totalfee);
//SaveReservation(nrinmat, parkinglot);
//save
JOptionPane.showMessageDialog(null, "This is yout reservation" + "\n\n" + " | " + parkinglot[n][0] + " | " + parkinglot[n][1] + " | " + parkinglot[n][2] + " | " + parkinglot[n][3] + " | " + parkinglot[n][4] + " HOURS |");
break;
}
Database method:
public static String[][] database(String [][]parkinglot)
{
System.out.println("This is database");
for (int i = 1; i < parkinglot.length; i++) {
for (int j = 0; j < parkinglot[i].length; j++) {
System.out.print(parkinglot[i][j] + "\t");
}
System.out.println();
}
return parkinglot;
}
Your program is starting at 1 every time because you have this line:
for (n=1; n<100; n++)
which initializes n to 1 before you enter the loop. (As noted in a comment, usually you would initialize n to zero, but that's not your problem here.)
Later, you break out of the loop, when n is still 1. When you call this code again (I assume it's in a function), it reinitializes n to 1 at the start of the loop. So n is never anything other than 1.
If you only want to fill in one record each time you run the program, then you don't need a loop at all. You need to store the value of n somewhere (like on disk, or in a database) and then read it back when you run the program again. Or, if you're saving the contents of parkinglot somewhere and reading it back in, you could scan it (using a for loop) to find the first empty entry, and initialize n to that, something like:
int n = 1; // or 0
for (; n < parkinglot.length && parkinglot[n][0] != null; n++);
if (n < parkinglot.length) {
populateParkingLotEntry(parkinglot, n);
} else {
// No more slots left...
}

How do I output to the console in a specific layout?

I am working on a small project that takes user input (match results) on one line, splits the input and outputs the same data in a different format. I am struggling to find a way to output the data in a specific format. As well as total games played, I want my program to produce a chart like output in the format
home_name [home_score] | away_name [away_score]
This is the code I have at the minute which allows users to input results line after line in the following format
home_name : away_name : home_score : away_score
until they enter stop, which breaks the loop (and hopefully soon outputs the data).
import java.util.*;
public class results {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int totalGames = 0;
String input = null;
System.out.println("Please enter results in the following format"
+ " home_name : away_name : home_score : away_score"
+ ", or enter stop to quit");
while (null != (input = scan.nextLine())){
if ("stop".equals(input)){
break;
}
String results[] = input.split(" : ");
for (int x = 0; x < results.length; x++) {
}
totalGames++;
}
System.out.println("Total games played is " + totalGames);
}
}
You can see here.
You can format your text as you wish.
The general syntax is
%[arg_index$][flags][width][.precision]conversion char  Argument
numbering starts with 1 (not 0). So to print the first argument, you
should use 1$ (if you are using explicit ordering).
You can use regEx to parse the line:
(\w)\s(\w)\s|\s(\w)\s(\w)
Base on Java code from (from http://tutorials.jenkov.com/java-regex/matcher.html)
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatcherFindStartEndExample{
public static void main(String[] args){
String text = "Belenenses 6 | Benfica 0";
String patternString = "(\\w+)\\s(\\w+)\\s\\|\\s(\\w+)\\s(\\w+)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()){
System.out.println("found: " + matcher.group(1));
System.out.println("found: " + matcher.group(2));
System.out.println("found: " + matcher.group(3));
System.out.println("found: " + matcher.group(4));
}
}}
Use this code instead of your
String results[] = input.split(" : ");
for (int x = 0; x < results.length; x++) {
}
You should do things in two times :
1) retrieving information entered by the user and storing it in instances of a custom class : PlayerResult.
2) performing the output according to the expected format. You should also compute the max size of each column before creating the graphical table.
Otherwise you could have a ugly rendering.
First step :
List<PlayerResult> playerResults = new ArrayList<PlayerResult>();
...
String[4] results = input.split(" : ");
playerResults.add(new PlayerResult(results[0],results[1],results[2],results[3])
Second step :
// compute length of column
int[] lengthByColumn = computeLengthByColumn(results);
int lengthHomeColumn = lengthByColumn[0];
int lengthAwayColumn = lengthByColumn[1];
// render header
System.out.print(adjustLength("home_name [home_score]", lengthHomeColumn));
System.out.println(adjustLength("away_name [away_score]", lengthAwayColumn));
// render data
for (PlayerResult playerResult : playerResults){
System.out.print(adjustLength(playerResult.getHomeName() + "[" + playerResult.getHomeName() + "]", lengthHomeColumn));
System.out.println(adjustLength(playerResult.getAwayName() + "[" + playerResult.getAwayScore() + "]", lengthAwayColumn));
}
You can keep the games statistics by adding results array values to the finalResults ArrayList. And then outputting its results as stop input is entered.
For counting the total results per team HashMap<String, Integer> is the best choice.
Here is the complete code with comments to make it clear:
import java.util.*;
// following the naming conventions class name must start with a capital letter
public class Results {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int totalGames = 0;
String input;
System.out.println("Please enter results in the following format: \n"
+ "'HOME_NAME : AWAY_NAME : HOME_SCORE : AWAY_SCORE' \n"
+ "or enter 'stop' to quit");
// HashMap to keep team name as a key and its total score as value
Map<String, Integer> scoreMap = new HashMap<>();
// ArrayList for storing game history
List<String> finalResults = new ArrayList<>();
// don't compare null to value. Read more http://stackoverflow.com/questions/6883646/obj-null-vs-null-obj
while ((input = scan.nextLine()) != null) {
if (input.equalsIgnoreCase("stop")) { // 'Stop', 'STOP' and 'stop' are all OK
scan.close(); // close Scanner object
break;
}
String[] results = input.split(" : ");
// add result as String.format. Read more https://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/
finalResults.add(String.format("%s [%s] | %s [%s]", results[0], results[2], results[1], results[3]));
// check if the map already contains the team
// results[0] and results[1] are team names, results[2] and results[3] are their scores
for (int i = 0; i < 2; i++) {
// here is used the Ternary operator. Read more http://alvinalexander.com/java/edu/pj/pj010018
scoreMap.put(results[i], !scoreMap.containsKey(results[i]) ?
Integer.valueOf(results[i + 2]) :
Integer.valueOf(scoreMap.get(results[i]) + Integer.valueOf(results[i + 2])));
}
totalGames++; // increment totalGames
}
System.out.printf("%nTotal games played: %d.%n", totalGames); // output the total played games
// output the games statistics from ArrayList finalResults
for (String finalResult : finalResults) {
System.out.println(finalResult);
}
// output the score table from HashMap scoreMap
System.out.println("\nScore table:");
for (Map.Entry<String, Integer> score : scoreMap.entrySet()) {
System.out.println(score.getKey() + " : " + score.getValue());
}
}
}
Now testing with input:
team1 : team2 : 1 : 0
team3 : team1 : 3 : 2
team3 : team2 : 2 : 2
sToP
The output is:
Total games played: 3.
team1 [1] | team2 [0]
team3 [3] | team1 [2]
team3 [2] | team2 [2]
Score table:
team3 : 5
team1 : 3
team2 : 2

Finding positions of a number in an array and giving points, Java

I'm trying to write a program that generates and stores 20 random numbers in the array Data[] and asks the user to enter their guess. If their number appears in the array, they get 10 points for each occurrence, the array is printed and all positions where the lucky number can be found. If it doesn't appear in the array, I have to print the lowest and highest values of the array and allow only one more try. if the player gets it right the second time they get 1 point for each appearance.
For example: Data[]={3,1,8,31,25,6,3,20,41,12,3,23,7,3,65,49,5,0,13,17}
and if the user inputs 3 then the program would output
3 can be found on the following positions:
0 6 10 13
3 appears 4 times. You get 40 points!
and for the same Data[]={3,1,8,31,25,6,3,20,41,12,3,23,7,3,65,49,5,0,13,17} if the user inputs 2 then the program would output
Sorry your lucky number 2 is not in the array!
Hint: Lowest Value:1 Highest Value 65 Try again with a different number in this range.
if they input 65 on their second try then the program would output
You get 1 point(s)!
This is my code I have tried but it is not working. It keeps telling me my numbers are not in the array. The lowest and highest values work. I do not know how to fix it. I have to have this done by tomorrow. Any help would be greatly appreciated.
String input1 = JOptionPane.showInputDialog("Please enter your lucky number between 0 and 100.");
luck=Integer.parseInt(input1);
System.out.println("Input " +luck);
int Data[] = new int [20];
for( int i=0; i<Data.length;++i){
Data[i] = (int) (Math.random() * 100);
System.out.print(Data[i]+ " \t");
}
for( int i=0; i<Data.length;++i){
if(Data[i]==luck){
System.out.println(luck+ " can be found in the following positions: ");
System.out.println(i);
score=score+10;
System.out.println(luck+ " appears " +(luck/10)+ " times. You get " +score+ " points.");
}else if(Data[i]!=luck){
Arrays.sort(Data);
System.out.println();
System.out.println(luck+ " is not in the array.");
System.out.println("Hint: " +Data[0]+ " is the lowest value and " +Data[19]+ " is the highest.");
input1 = JOptionPane.showInputDialog("Please enter another number between 0 and 100.");
luck=Integer.parseInt(input1);
}
}
System.out.println();
System.out.println("Score: " +score);
}}
The problem is you are not checking your value against every value in your array. If the entered value does not match the first value in your Array (i=0), then you are asking the user for another value.
What you have to do is ask for a value, compare it against EVERY value in the table, then make your decision. Either it's present or its not.
I added a boolean. We set it to true if we find our number, otherwise we display the message and ask the user to try again.
Try this:
boolean found = false;
for( int i=0; i<Data.length;++i){
if(Data[i]==luck){
System.out.println(luck+ " can be found in the following positions: ");
System.out.println(i);
score=score+10;
System.out.println(luck+ " appears " +(luck/10)+ " times. You get " +score+ " points.");
found = true;
}
}
if(!found){
Arrays.sort(Data);
System.out.println();
System.out.println(luck+ " is not in the array.");
System.out.println("Hint: " +Data[0]+ " is the lowest value and " +Data[19]+ " is the highest.");
input1 = JOptionPane.showInputDialog("Please enter another number between 0 and 100.");
luck=Integer.parseInt(input1);
}
Finally, you need to implement a counter inside your loop, and then display your information as required... Right now, it will display "# can be found in the following positions" and other messages for each instance found in the array.
Implement a counter, and a way to track indexes of values found, and then you can display all that information coherently from outside the for loop
Edit: To give you more complete implementation...
This code should basically take you almost where you need to go:
public static void main(String[] args) {
int Data[] = new int [20];
for( int i=0; i<Data.length;++i){
Data[i] = (int) (Math.random() * 100);
System.out.print(Data[i]+ " \t");
}
while(true){
String input1 = JOptionPane.showInputDialog("Please enter your lucky number between 0 and 100.");
int luck=Integer.parseInt(input1);
int score = 0;
String positions = "";
int counter = 0;
System.out.println("Input " +luck);
boolean found = false;
for( int i=0; i<Data.length;++i){
if(Data[i]==luck){
positions += i + " ";
counter++;
score=score+10;
found = true;
}
}
if(found){
System.out.println(luck+ " can be found in the following positions: ");
System.out.println(positions);
System.out.println(luck+ " appears " + counter + " times. You get " +score+ " points.");
}
else{
Arrays.sort(Data);
System.out.println();
System.out.println(luck+ " is not in the array.");
System.out.println("Hint: " +Data[0]+ " is the lowest value and " +Data[19]+ " is the highest.");
}
System.out.println();
System.out.println("Score: " +score);
}
}

How to count valid and invalid lines in file

I have the following code:
public class generator {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("results.txt"));// creates a scanner to
// scan from a file
String line;
String HomeTeam, AwayTeam;
while (s.hasNext()) {
line = s.nextLine(); // reads the next line from the file
line = line.trim(); // trims the line
String[] elements = line.split(":"); // splits the line
if (elements.length == 4) {
HomeTeam = elements[0].trim(); // trims home team
AwayTeam = elements[1].trim(); // trims away team
elements[2] = elements[2].trim();
elements[3] = elements[3].trim();
if (HomeTeam.length() != 0 && AwayTeam.length() != 0) { // check if position is present
try { // "try" is a special statement which allows us to deal with "exceptions"
int HomeScore = Integer.parseInt(elements[2]); // attempt to convert the String into an Integer type value
int AwayScore = Integer.parseInt(elements[3]);
System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
}
catch (NumberFormatException e) {
}
}
}
}
}
}
Now my question is: how do I count the valid and invalid lines as well as total number of score in entire file?
Sample input file is:
Leeds United : Liverpool : 1 : 2
Chelsea : Manchester City : 1 : 1
Aston Villa : Middlesbrough : 3 : 1
Tottenham Hotspur : Stoke City : 0 : 0
West Ham United : Wigan Athletic :2 : 1
Fulham : Liverpool : 1 : 2
Wigan Athletic : Leeds United : 2 : 2
Arsenal Liverpool :2:2
Hull City: Tottenham Hotspur : 3 : 5
Everton : Portsmouth:4 : 2
Stoke City : West Bromwich Albion : 5 : 4
Leeds United : Liverpool : 1: 10
Blackburn Rovers : Fulham : 1 : 1
West Ham United : Newcastle United : 0 : 0
Manchester United : Wigan Athletic : 1 : 2
Hull City : Sunderland : 2 : 3
Chelsea : Manchester City :1
Fulham : Leeds United : 1 : 2
Wigan Athletic : Tottenham Hotspur : 2 : 2
Hull City : Everton : 3 : 5
: :2:0
Sunderland : Blackburn Rovers : 4 : 2
Stoke City : West Bromwich Albion : 5 : 4
Hull : Liverpool : 5: x
Blackburn Rovers : Fulham : 1 : 1
Chelsea : Everton : a : 1
Sunderland : Newcastle United : 0 : 0
Hull : :2:3
Sunderland : Blackburn Rovers : 1 : 2
Hull City : Everton : 2 : 3
Leeds United : Chelsea : 1 : 2
Chelsea : Manchester City : 1 : 1
Aston Villa:Fulham:3:1
Manchester City : Stoke City : 0 : 0
West Ham United : Middlesbrough : 2 : 1
Actually You check validity so what's the problem with counting? Create two variables: ValidNumb and InvalidNumb. Increase ValidNumb after System.out.println(). Increase InvalidNumb if elements.length not equal 4, lenght of team names equal 0 or You catch exception during conversions scores to integers.
To count all scores: create one more variable allScores and add them to HomeScore and AwayScore in try block.
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("results.txt"));// creates a scanner to
// scan from a file
String line;
String HomeTeam, AwayTeam;
Int ValidNumb = 0, InvalidNumb = 0; //counters of valid and invalid lines
Int AllScores = 0; //sum of all goals
while (s.hasNext()) {
line = s.nextLine(); // reads the next line from the file
line = line.trim(); // trims the line
String[] elements = line.split(":"); // splits the line
if (elements.length == 4) {
HomeTeam = elements[0].trim(); // trims home team
AwayTeam = elements[1].trim(); // trims away team
elements[2] = elements[2].trim();
elements[3] = elements[3].trim();
if (HomeTeam.length() != 0 && AwayTeam.length() != 0) { // check if position is present
try { // "try" is a special statement which allows us to deal with "exceptions"
int HomeScore = Integer.parseInt(elements[2]); // attempt to convert the String into an Integer type value
int AwayScore = Integer.parseInt(elements[3]);
AllScores = AllScores + HomeScore + AwayScore; //sum up scores
System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
ValidNumb++; //line is valid
}
catch (NumberFormatException e) {
InvalidNumb++; //scores are not integers
}
}
else {InvalidNumb++;} //HomeTeam or AwayTeam are empty
}
else {InvalidNumb++;} //not enough elements in line
}
}
So you would need counter variables for every metrics that you need.So before your while loop define them as:
int totalAwayScore = 0, totalHomeScore = 0, invalidLines = 0, totalLines = 0;
Within while loop, increment totalLines as
totalLines++;
which means you have next line to read. Your try catch is where you know how much is score so keep on adding to metrics that you defined above like:
try { // "try" is a special statement which allows us to deal with "exceptions"
int HomeScore = Integer.parseInt(elements[2]); // attempt to convert the String into an Integer type value
int AwayScore = Integer.parseInt(elements[3]);
totalAwayScore += AwayScore;
totalHomeScore += HomeScore;
System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
} catch (NumberFormatException e) {
invalidLines++;
}
Here if you get number format exception, you get to know that it's invalid line and hence increment the value of variable that holds invalid lines in a file.
At the end of the while loop you print the stats like:
System.out.println("Total home score is " + totalHomeScore + " totalAway score is " + totalAwayScore + " invalid lines were " + invalidLines + " of total " + totalLines);
I'm not sure I understood but:
you need to increment a counter of invalid lines in the catch
section. It indicates that the line is wrong because the number is
not a number;
you need to increment a counter of invalid lines in an else section
of the if
if (elements.length == 4)
it means that you have too much or too many arguments;
you need to increment a counter of invalid lines if HomeTeam and
AwayTeam are =="" because you don't have the name of the team;
Cheers
You can add two counters - one for all (allCounter) and one for wrong lines (wrongCounter):
at the beginning of every loop iteration increment allCounter:
while (s.hasNext()) {
allCounter++;
line = s.nextLine(); // reads the next line from the file
...
if something is wrong, increment wrongCounter and continue to next iteration of loop
if (elements.length != 4) {
++wrongCounter;
continue; //breaks this iteration and moves to next one
}
//otherwise proceed normally
homeTeam = elements[0].trim(); // trims home team
awayTeam = elements[1].trim(); // trims away team
...
Similarly in second if and catch clause:
catch (NumberFormatException e) {
++wrongCounter;
}
And of course:
int correctCounter = allCounter - wrongCounter;
One more thing: By Java convention you should write all variable/method names with camelCase, i.e start with small letter and then start every new word with capital letter:
Example: not HomeTeam, but homeTeam

Java Powers display table

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));
}

Categories

Resources