This is my input file:
0 I 4325 <4214, 6> <4718, 9> <1203, 11>
18 L 4214 12 <4325, 6> <4718, 5> <1483, 9>
35 F 4109
I am trying to write a method that will read in the first column, second column (either I, L or F) and store all the pairs in each row e.g., (4214, 6), (4718, 9). What I've done is used the delimiter from the scanner class to get rid of '<', ',' and '>', and it does but when I try calling temp.next(), I keep on getting an error. My code is below (sometime the error goes away when I use skip(" "):
public void parseFile(Scanner input) {
int prevSeqNo = -1;
while (input.hasNextLine()) {
String line = input.nextLine();
if (!line.startsWith("#") && !line.isEmpty()) { // ignore comments
// and blank lines
Scanner temp = new Scanner(line).useDelimiter("<|,| |>"); // ignore all '<', ',' and '>'
// while(temp.hasNext())
// System.out.print(" " + temp.next() );
// System.out.println();
int timeStamp = temp.nextInt();
System.out.println("Timestamp: " + timeStamp);
temp.skip(" ");
String event = temp.next();
System.out.println("Event: " + event);
if (event.equals("I")) {
temp.skip(" ");
startNode = temp.nextInt();
System.out.println("starting node: " + startNode);
// while (temp.hasNext()) {
temp.skip(" ");
int node = temp.nextInt();
System.out.println(node);
temp.skip("");
int weight = temp.nextInt();
System.out.println(weight);
// System.out.println("<" + node + ", " + weight + ">");
// }
} else if (event.equals("L")) {
int currSeqNo = temp.nextInt();
System.out.println("Sequence number: " + currSeqNo); // discard if LSP has smaller or equal sequence number to max seen so far
if (currSeqNo >= prevSeqNo) {
prevSeqNo = currSeqNo; // update the previous sequence
// number
} else { // else if event == "F"
}
}
}
}
input.close();
}
After removing symbols:
0 I 4325 4214 6 4718 9 1203 11
18 L 4214 12 4325 6 4718 5 1483 9
29 L 4109 78 4718 3 1483 2
35 F 4109
Here is the error message:
Timestamp: 0
Event: I
starting node: 4325
4214
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at LinkedStateRouting.parseFile(LinkedStateRouting.java:41)
at LinkedStateRouting.main(LinkedStateRouting.java:88)
Related
Is it possible to group a string every nth character?
For example, suppose I have a string containing the following:
"Hello how are you"
What I'm trying to do is if the user inputs 4, then based on the integer, break into 4 groups and assign those to strings.
1 2 3 4 1 2 3 4 1 2 3 4 1 2
H E L L O H O W A R E Y O U
All the letters that has 1 assigned will be group 1, similarly, all the letters that has 2 assigned will be group 2.
Group 1 - "HOAO", Group 2 - "EHRU", Group 3 - "LOE", Group 4 - "LWY"
Below is what I have so far
import java.util.*;
class groupChar {
static void groupLetters(String str, int n) {
String result="";
for(int i = 0; i < str.length(); i = i + n){
result = result + str.charAt(i);
}
System.out.println(result);
}
public static void main(String[] args) {
Scanner inputMessage = new Scanner(System.in);
System.out.println("Enter string : ");
String message = inputMessage.nextLine();
System.out.println("Enter a number : ");
Scanner inputNumber = new Scanner(System.in);
int number = Integer.parseInt(inputNumber.nextLine());
System.out.println("String is - " + message);
System.out.println("Number is - " + number);
groupLetters(message, number);
}
}
So far I'm only able to create one group based on the user input.
You can approach this problem using Map to track all the groups and using StringBuilder to construct the individual group.
Firstly, we need to generate a HashMap populated with entries having the keys corresponding to the indices of the groups and empty StringBuilders as *values.
Then we have to iterate over the given string, maintaining two indices: i - position in the string and groupId - index of the group. At iteration step, we need to update the current group by appending the current character.
That's how it can be implemented:
public static Map<Integer, StringBuilder> groupLetters(String str, int n) {
Map<Integer, StringBuilder> groupByGroupId = createGroups(n);
for (int i = 0, groupId = 1; i < str.length(); i++, groupId = (groupId++ % n) + 1) {
groupByGroupId.get(groupId).append(str.charAt(i));
}
return groupByGroupId;
}
public static Map<Integer, StringBuilder> createGroups(int n) {
Map<Integer, StringBuilder> groupByGroupId = new HashMap<>();
for (int i = 1; i <= n; i++) {
groupByGroupId.put(i, new StringBuilder());
}
return groupByGroupId;
}
main
public static void main(String[] args) {
for (Map.Entry<Integer, StringBuilder> entry: groupLetters("hellohowareyou", 4).entrySet()) {
System.out.println("Group " + entry.getKey() + " -> " + entry.getValue());
}
}
Output:
Group 1 -> hoao
Group 2 -> ehru
Group 3 -> loe
Group 4 -> lwy
The suggested solution would be to use a map or dictionary with <int,List>. But I recommend the most simple and understandable way without using Map based on your code.
I used the same example as you provided, but starting from 0 would make it easier to understand the code.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 1 2 3 0 1 2 3 0 1 2 3 0 1
H E L L O H O W A R E Y O U
The Algorithm:
Group 1 : 0,(0 + (1 x 4)),(0 + (2 x 4)),(0 + (3 x 4)) ...
Group 2 : 1,(1 + (1 x 4)),(1 + (2 x 4)),(1 + (3 x 4)) ...
Group 3 : 2,(2 + (1 x 4)),(2 + (2 x 4)),(2 + (3 x 4)) ...
Therefore, Group a+1 : a, (a + (1 x N)), (a + (2 x N)), (a + (3 x N))...
WHERE the total number of elements in each group is
(total number of Char in string) / (number of droup) + 1
Code
We used a for loop for a AND a for loop for the increment 1,2,3...
Therefore, I have modified your code to meet the requirement :
static void groupLetters(String str,int n) {
//Remove the string space and to UPPER CASE
str = str.toUpperCase().replaceAll("\\s+","");
for(int a = 0; a < n; a++){
String result = "";
//Get the Char in Group a with the algorithm mentioned above
for(int i = 0; i < str.length() / n + 1; i++){
if(a + (i * n) < str.length()){
result = result + str.charAt(a + (i * n));
}
}
System.out.println("Group "+ (a + 1) + ": " + result);
}
}
public static void main(String[] args) {
Scanner inputMessage = new Scanner(System.in);
System.out.println("Enter string : ");
String message = inputMessage.nextLine();
System.out.println("Enter a number of group gonna break into : ");
Scanner inputNumber = new Scanner(System.in);
int number = Integer.parseInt(inputNumber.nextLine());
System.out.println("String is - " + message);
System.out.println("Number of Group is - " + number);
groupLetters(message,number);
}
OUTPUT:
String is - Hello how are you
Number of Group is - 4
Group 1: HOA
Group 2: EHR
Group 3: LOE
Group 4: LWY
Splitter can be used to split text by length
com.google.common.base.Splitter , see -> https://www.geeksforgeeks.org/splitter-class-guava-java/
I slightly modified the code :
import java.util.Scanner;
import com.google.common.base.Splitter;
public class test {
public static String result="";
public static int index = 0;
static void groupLetters(String str, int n) {
str = str.replaceAll("\\s", "");
Iterable<String> fullString = Splitter.fixedLength(n).split(str);
int length = str.length() % n == 0 ? str.length() / n : (str.length() / n) + 1;
for(int i = 0; i < length + 1; i++){
fullString.forEach(s->{
if(s.length()>index){
result+=s.charAt(index)+"";
}
});
result+=" ";
index++;
}
System.out.println(result);
}
public static void main(String[] args) {
Scanner inputMessage = new Scanner(System.in);
System.out.println("Enter string : ");
String message = inputMessage.nextLine();
System.out.println("Enter a number : ");
Scanner inputNumber = new Scanner(System.in);
int number = Integer.parseInt(inputNumber.nextLine());
System.out.println("String is - " + message);
System.out.println("Number is - " + number);
groupLetters(message, number);
}
}
I'm doing exercice 3 from Chapter 4 of the book "Introduction to Java" by Walter Savitch.
Instructions:
Develop an algorithm for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code os 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond 2 and 7. Allow the user to guess a fixed number of times
Current problems:
my code looks dirty and too long. I'm a beginner, but looking for ways to make it more efficient
when entering a 'guess number' that starts with any other number than 0 it works but when it starts with 0, my program ignores the first digit
I've spent two hours on it. There's still another 25 exercises waiting for me in this chapter only so I hope to be more efficient with the other exercises.
public static void main(String[] args) {
int SecretCode = 12140;
int Win = 0;
//just checking the incrementor
int sum = 0;
System.out.println("Ceci est un jeu de lotterie. \nPouvez-vous deviner le nombre à 5 chiffres caché ?\n");
Scanner fromPlayer = new Scanner(System.in);
do {
System.out.println("Votre nombre porte-bonheur: ");
int guess = fromPlayer.nextInt();
//Interprets Guess int to string
String stringGuess = String.valueOf(guess);
int length = stringGuess.length();
boolean CorrectLength = (length == 5);
if (CorrectLength) {
String Firstdigit = stringGuess.substring(0, 1);
String Seconddigit = stringGuess.substring(1, 2);
String Thirddigit = stringGuess.substring(2, 3);
String Fourthdigit = stringGuess.substring(3, 4);
String Fifthdigit = stringGuess.substring(4);
//Interprets Secret Code int to string
String stringSecretCode = String.valueOf(SecretCode);
String FirstdigitCode = stringSecretCode.substring(0, 1);
String SeconddigitCode = stringSecretCode.substring(1, 2);
String ThirddigitCode = stringSecretCode.substring(2, 3);
String FourthdigitCode = stringSecretCode.substring(3, 4);
String FifthdigitCode = stringSecretCode.substring(4);
//Just checking the values that the program will compare to secret code
System.out.println("Vous avez entré \n" + Firstdigit + "\n" + Seconddigit + "\n" + Thirddigit + "\n" + Fourthdigit + "\n" + Fifthdigit);
if (Firstdigit.equals(FirstdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Firstdigit);
System.out.println("Premier numéro est : correct. Score: " + Win);
} else {
System.out.println("Premier numéro est : incorrect. Score:" + Win);
}
if (Seconddigit.equals(SeconddigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Seconddigit);
System.out.println("Deuxième numéro est : correct. Score: " + Win);
} else {
System.out.println("Deuxième numéro est : incorrect. Score: " + Win);
}
if (Thirddigit.equals(ThirddigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Thirddigit);
System.out.println("Troisième numéro est : correct. Score: " + Win);
} else {
System.out.println("Troisième numéro est : incorrect. Score: " + Win);
}
if (Fourthdigit.equals(FourthdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Fourthdigit);
System.out.println("Quatrième numéro est : correct. Score: " + Win);
} else {
System.out.println("Quatrième numéro est : incorrect. Score: " + Win);
}
if (Fifthdigit.equals(FifthdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Fifthdigit);
System.out.println("Cinquième numéro est : correct. Score: " + Win);
} else {
System.out.println("Cinquième numéro est : incorrect. Score: " + Win);
}
System.out.println("Vous avez deviné " + Win + " numéros. Leur total vaut " + sum);
} else {
System.out.println("ERREUR. Il faut entrer 5 chiffres.");
}
I expect the output of 02140 to be
"Premier numéro est : incorrect. Score: 0
Deuxième numéro est : correct. Score: 1
Troisième numéro est : correct. Score: 2
Quatrième numéro est : correct. Score: 3
Cinquième numéro est : correct. Score: 4
Vous avez deviné 4 numéros. Leur total vaut 7"
BUT the actual output is: ERREUR. Il faut entrer 5 chiffres.
as if the program doesn't identify 0 as a digit.
Instead of using
String stringGuess = String.valueOf(guess);
you should use
String stringGuess = String.format("%05d", guess);
to always convert the number you've read into a five digit long String. In your current solution you should see that if you print stringGuess leading zeros will have been removed from the input.
Instead, you could use the following code which uses the nextLine() method of the Scanner class to solve your problem:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] expected = "53849".toCharArray();
// enter CTRL-D to stop
while (scanner.hasNext()) {
String input = scanner.nextLine();
if (input.length() != 5) {
System.err.println("wrong length");
continue;
}
char[] actual = input.toCharArray();
int digitSum = 0;
int correctDigits = 0;
for (int i = 0; i < expected.length; i++) {
if (actual[i] == expected[i]) {
correctDigits++;
digitSum += actual[i] - '0';
}
}
String msg = String.format(
"Number of correct digits: %d, their sum: %d",
correctDigits, digitSum
);
System.out.println(msg);
}
Try the one below and see if it works for you. Take the input directly into stringGuess instead of taking it into int and then converting it into String.
int guess = fromPlayer.nextInt(); //remove this and take input into the below variable directly
String stringGuess = fromPlayer.next();
Check this for your reference why the int cannot store leading zeroes.
I need load file .txt with strings and int.
When it is loaded, the program prints the sum of ASCII values that was calculated using a method (I wrote already). My problem is sum all The strings and int.
It necessary to sum all rows, except the last line that shows the sum in ASCII.
NOTICE: There is 2 groups (colors) with same info
This the file. In yellow is the sum of all the info in .txt
My code:
System.out.println("Enter Path To File:");
File fileName = new File("Game.txt");
Scanner sFromFile = new Scanner(fileName);
String size = sFromFile.nextLine();
int sizeBoard = Integer.parseInt(size);System.out.println("Board size loading size= "+size+"X"+size);
String team = sFromFile.next();
// int numOfSoliders = sFromFile.nextInt();
Point arrSol []= new Point[sizeBoard];for(
int i = 0;i<arrSol.length;i++)
{
arrSol[i] = new Point(sFromFile);
System.out.println("Solider created successfully!");
}
// int numOfDragon = sFromFile.nextInt();
Point arrDragon[] = new Point[sizeBoard];for(
int i = 0;i<arrDragon.length;i++)
{
arrDragon[i] = new Point(sFromFile);
System.out.println("Dragon created successfully!");
}
// ALSO DID THE SAME TO OTHER GROUP...
// THE LAST LINE READING INPUT
int fileHashCode = sFromFile.nextInt();System.out.println("HashCode loading...\n Loaded hashCode= "+fileHashCode);
// TRY USE STRING METHOD
// while (sFromFile.hasNext()) {
// String str = sFromFile.nextLine();
// System.out.print(str + ". ");
// }
sFromFile.close();
// ALSO TRY OUTSIDE METHOD
public static String readFile(String fName) throws FileNotFoundException {
File f = new File(fName);
Scanner sFromFile = new Scanner(f);
for (int i = 0; i < board.length; i++) {
while (sFromFile.hasNext()) {
String str= sFromFile.nextLine();
String sum+=str;
// System.out.print(str + ". ");
}
}
sFromFile.close();
return sum;
}
It means to sum all characters (except line breaks) of the first 7 lines of text.
Proof
String input = "8\r\n" +
"RED\r\n" +
"8 0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7\r\n" +
"8 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7\r\n" +
"BLUE\r\n" +
"8 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7\r\n" +
"8 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7\r\n" +
"6139";
try (Scanner sc = new Scanner(input)) {
int sum = 0;
for (int i = 0; i < 7; i++)
sum += sc.nextLine().chars().sum();
System.out.println("Calculated: " + sum);
System.out.println("Last line : " + sc.nextLine());
}
Output
Calculated: 6139
Last line : 6139
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
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));
}