import java.util.Scanner;
public class TriangleDriver {
public static void main(String[] args) {
System.out.println("Please enter value of N: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
for (int i = 1; i <= num; i++) {
System.out.printf("%d\t", i);
}
System.out.println("");
System.out.println("---- ----");
for (int i = 0; i < num; i++) {
System.out.print((i + 1) + " ");
for (int j = 1; j <= num; j++) {
System.out.printf("%7.2f", Math.sqrt(i * i + j * j));
}
System.out.println();
}
}
}
This could be useful to others that are new to coding. I do need help on it though. When you input a number, say 8,
-it is not spaced properly
-The first actual row of data should not include 1.00, 2.00, 3.00
-Personal Preference: I would like to include ---- on the top after the i numbers and | on the side for the J numbers
What do you guys think?
This is close to how your code should look
public class TriangleDriver {
private static final String REQUEST = "Please enter value of N: ";
private static final String SPACER3 = " ";
private static final String SPACER4 = " ";
private static final String DIVIDER = "----";
private static final String FORMAT_ONE = " %d ";
private static final String FORMAT_FIRST_ROW = "%7.0f";
private static final String FORMAT_ADDITIONAL_ROWS = "%7.2f";
private static final int HEADER_LINES = 2;
public static void main(String[] args) {
int num = getIntInput(REQUEST);
StringBuilder[] result = solution(num);
printSBArray(result);
}
static private int getIntInput(String request){
System.out.print(request);
return new Scanner(System.in).nextInt();
}
static private void printSBArray(StringBuilder[] sbArray){
for (StringBuilder sb : sbArray)
System.out.println(sb.toString());
}
static private StringBuilder[] solution(int num){
StringBuilder output[] = new StringBuilder[num + HEADER_LINES];
for(int i = 0; i < output.length; i++)
output[i] = new StringBuilder("");
// build line 0
output[0].append(SPACER4 + SPACER4);
for (int i = 1; i <= num; i++) {
output[0].append(String.format(FORMAT_ONE, i));
}
// build line 1
output[1].append(DIVIDER + SPACER4);
for (int i = 0; i < num; i++)
output[1].append(String.format(DIVIDER + SPACER3));
// build line 2
int i = 0;
output[2].append((i + 1) + SPACER4);
for (int j = 1; j <= num; j++) {
output[2].append(String.format(FORMAT_FIRST_ROW, Math.sqrt(i * i + j * j)));
}
// build line 3+
for (i = 1; i < num; i++) {
output[i + 2].append((i + 1) + SPACER4);
for (int j = 1; j <= num; j++) {
output[i + 2].append(String.format(FORMAT_ADDITIONAL_ROWS, Math.sqrt(i * i + j * j)));
}
}
return output;
}
}
This gives good separation of functionality, keeps strings out of logic code, and minimizes main to only essential calls. Also uses StringBuilder to build the result. This allows you to maintain separation of functionality. Code should do one thing, ie calculate results but not print them. Technically, this should have been separated into it's own class.
On a side note, I would not turn this in as your homework your teacher might just get a bit suspicious.
Final Result:
import java.util.Scanner;
public class TriangleDriver {
public static void main(String[] args) {
System.out.println("Please enter value of N: ");
Scanner scan = new Scanner(System. in );
int num = scan.nextInt();
System.out.print("\t");
for (int i = 1; i <= num; i++) {
System.out.printf("%d\t", i);
}
System.out.println();
String barrier = "\t";
for (int i = 0; i < num; i++)
barrier += "----\t";
System.out.println(barrier);
for (int i = 0; i < num; i++) {
System.out.print((i + 1) + "");
for (int j = 1; j <= num; j++) {
System.out.printf("\t%.2f", Math.sqrt(i * i + j * j));
}
System.out.println();
}
}
}
Explanation:
First of all, you used 7.2f in your printf(), which was a pain to troubleshoot. The 7 in 7.2f states that you want the output to always be 7 spaces long, regardless of number length. This is not equal to the amount added by \t, so the columns don't line up. To create the ---- barriers under each line, I used a for loop to add N sections. It should be easy to add the |s.
In regards to
The first actual row of data should not include 1.00, 2.00, 3.00
I don't know what you really want. I'm not sure what you want the first value to be - it seems to follow the Math.sqrt(i * i + j * j) calculation that you are using to generate the data for the other rows.
Related
I have a task to ask user for input (user's name) and then to print a rhombus pattern out of it.
For example:
If user's name is Thomas, then the output should be like this:
T
Th
Tho
Thom
Thoma
Thomas
homas
omas
mas
as
s
This is my code so far. I am having trouble with second for loop. I can easily print out lines until "Thomas", but I don't know, how to print whitespace infront so that the end of the word will be on the same place.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
for (int j = 1, k = 1; j <= enteredNamesLength; i++, k++) {
System.out.println(k * " " + name.substring(j, enteredNamesLength));
}
}
}
}
I think there must be one for loop to print the name like what you did, then another for space and inside the same print the substring.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
}
for(int i = 1;i <= enteredNamesLength; i++ ) {
for(int j = 0;j < i; j++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
}
It would be easier to do it in 2 times : substring from start to an index, and then print the spaces followed by the end of the world, ans some changes to do :
no need to cast i as int, it's already an int
first loop : start index i at 1 and not 0, no avoid empty line
second loop : end index for i at enteredNamesLength-1 and not enteredNamesLength to avoid also an empty line
for (int i = 1; i <= enteredNamesLength; i++) { // start at 1
System.out.println(name.substring(0, i)); // don't cast
}
for (int i = 1; i < enteredNamesLength; i++) { // stop at enteredNamesLength-1
for (int space = 0; space <= i; space++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
Here is another solution, you can extract a print method which accepts a start and stop. If the index between them, then print character at index, otherwise print whitespace.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int start = 0, stop = 0; start < enteredNamesLength && stop < enteredNamesLength; ) {
print(start, stop, name);
if (stop < enteredNamesLength - 1) {
stop++;
} else {
start++;
}
}
}
private static void print(int start, int stop, String name) {
for (int index = 0; index < name.length(); index++) {
if (index >= start && index <= stop) {
System.out.print(name.charAt(index));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
You can combine the upper increasing part and the lower decreasing part in one loop.
Try it online!
public static void main(String[] args) {
String str = "RHOMBUS";
int n = str.length();
// two parts: negative and positive
for (int i = 1 - n; i < n; i++) {
// leading whitespaces for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, n + i);
// positive part: str.substring(i, n);
String sub = str.substring(Math.max(0, i), Math.min(n + i, n));
// output the line
System.out.println(sub);
}
}
Output:
R
RH
RHO
RHOM
RHOMB
RHOMBU
RHOMBUS
HOMBUS
OMBUS
MBUS
BUS
US
S
See also: Writing a word in a rhombus / diamond shape
This code works with both regular UTF8 characters and surrogate pairs.
Try it online!
public static void main(String[] args) {
String str = "π₯π·πΎπΌπ±ππ¦";//"RHOMBUS";
int n = (int) str.codePoints().count();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
IntStream.range(1 - n, n)
// leading whitespaces for the positive part
.peek(i -> IntStream.range(0, i)
.forEach(j -> System.out.print(" ")))
// negative part: range(0, n + i);
// positive part: range(i, n);
.mapToObj(i -> str.codePoints()
.skip(Math.max(0, i))
.limit(Math.min(n + i, n))
.mapToObj(Character::toString)
.collect(Collectors.joining()))
// output the line
.forEach(System.out::println);
}
Output:
π₯
π₯π·
π₯π·πΎ
π₯π·πΎπΌ
π₯π·πΎπΌπ±
π₯π·πΎπΌπ±π
π₯π·πΎπΌπ±ππ¦
π·πΎπΌπ±ππ¦
πΎπΌπ±ππ¦
πΌπ±ππ¦
π±ππ¦
ππ¦
π¦
So, I'm creating this minesweeper game and I am confused with 2 of my methods which one, will initialize the array with a certain character and one method will actually print the game. Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = 0;
int b = 0;
System.out.println("Welcome to Mine Sweeper!");
a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);
eraseMap(new char[b][a]);
simplePrintMap(new char[b][a]);
}
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userInput;
System.out.println(prompt);
userInput = in.nextInt();
while (userInput < min || userInput > max) {
System.out.println("Expected a number from 3 to 20.");
userInput = in.nextInt();
}
return userInput;
}
public static void eraseMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
map[i][j] = (Config.UNSWEPT);
}
}
return;
}
public static void simplePrintMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
System.out.print(map[b][a] + " ");
}
System.out.println();
}
return;
}
The methods that are in question is eraseMap and simplePrintMap. eraseMap is supposed to initialize the array with "." and simplePrintMap is supposed to actually print the array. So if i input 3 and 4, it will print periods will a width of 3 and height of 4.
(each period separated by space).
A) You create 2 seperate maps. You perform the erase on the first, then throw it all away, create a new map and print that. Which, of course, is empty.
Try creating one map and work on it:
char[][] map = new char[b][a]
eraseMap(map);
simplePrintMap(map);
B) in the print method, you use the wrong indices:
System.out.print(map[b][a] + " ");
change these to
System.out.print(map[i][j] + " ");
C) not an error, just a hint: you don't need return; at the end of void methods.
I need the first method for generating a random number should receive the beginning and ending value of the range within its parameter list. It should send back the random number through the method name. And the second method to display the array which I have but apparently the code is not broken down into two methods and I don't understand how to accomplish this. I am lost after working on this for so long.
Here is my UPDATED code but still receiving 4 errors:
import java.util.Scanner;
import java.util.Random;
public final class {
public static Random generator = new Random();
public int createNum(int[] randomNumbers, int SIZE, int n, int i) {
int x;
SIZE = 20;
randomNumbers = new int[SIZE];
Random generator = new Random();
for (i = 0; i < SIZE; i++) {
n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
return n;
}
public void print(int i, int randomNumbers, int SIZE){
SIZE = 20;
randomNumbers = new int[SIZE];
for (i = 0; i < SIZE; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public static void main(String[] args){
do{
Scanner inputReader = new Scanner(System.in);
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
}
First thing's first, don't put everything in main if the task is to decompose your solution. What you need is a class that exercises the logic of your requirements or at least two additional methods that perform the work independently.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
represents two distinct tasks. You can tell because they are not dependent on each other.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
generates and places the numbers.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
prints them.
Since it seems beneficial for you to figure this out on your own; what's needed now? hint: read the first part again
Hey guys so this is my homework question: Write a method that displays an n by n matrix in a dialog box using the following header:
public static void printMatrix(int n)
Each element in the matrix is 0 or 1, which is generated randomly.
A 3 by 3 matrix may look like this:
0 1 0
0 0 0
1 1 1
So far, I could easily print out my problem in a scanner, however I'm not sure how to do it in a dialog box.
At the moment I'm getting the error:
error: 'void' type not allowed here JOptionPane.showMessageDialog(null, printMatrix(n));
1 error
I know that it's a void, and can't be returned however, my assignment requires the method to be void. My real question is how would I print it in the method then? I've been working on this problem for 4 hours and it's really frustrating me.
import java.util.*;
import java.lang.*;
import java.io.*;
import javax.swing.JOptionPane;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
// Main method
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);
// Convert string to integer
int n = Integer.parseInt(stringInteger);
JOptionPane.showMessageDialog(null, printMatrix(n));
}
// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
}
}
}
}
I think you are being asked to print. Also, I would prefer Random.nextBoolean() for generating the character. Loop and call System.out.print. Something like,
public static void printMatrix(int n) {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(rand.nextBoolean() ? "1 " : "0 ");
}
System.out.println();
}
}
public static void main(String[] args) {
printMatrix(3);
}
If you really want to use a JOptionPane you might use a StringBuilder to construct the matrix and then display it. Something like,
public static void printMatrix(int n) {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sb.append(rand.nextBoolean() ? "1 " : "0 ");
}
sb.append(System.lineSeparator());
}
JOptionPane.showMessageDialog(null, sb.toString());
}
But a void method doesn't return anything, so you can't print the result of a void method in the caller.
A slight modification done to your method I am providing screenshot of output.
private static Object printMatrix(int n) {
// Column depending on n times
String randomN[][] = new String[n][n];
for(int row = 0 ;row<n;row++)
{
for (int col = 0; col < n; col++)
{
randomN[row][col] = ((int)(Math.random() * 2)+ " ");
}
}
String s = Arrays.deepToString(randomN).replace("], ", "\n").replaceAll(",|\\[|\\]", "");
return s;
}
Hope you found my code helpful cheers happy coding.
This code will do everything inside your printMatrix();
class DialogPrint
{
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);
// Convert string to integer
int n = Integer.parseInt(stringInteger);
printMatrix(n);
}
// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
String sb="";
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
sb+=randomN;
}
sb+="\n";
}
System.out.print(sb);
JOptionPane.showMessageDialog(null, sb);
}
}
How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}