I have this code that is based on seats but the rows exceeded to 10+. When i input 1A it will change the seat row 1 column a from '*' to 'x'. Now my problem is when it comes to 2 digits e.g. 12B, it will give me error because it only takes the '1' not the whole '12' in a char that detects the row to change it to 'x'.
I kind of have the idea on my problem, it is because it's character and follows ASCII but can't seem to find the solution to my problem. I know this is a assignment and got some of the code references from this site also, but i study them as i took some references, not just copy and paste.
This is where i get stuck
if (choice == 'c') {
input.nextLine();
String seatchoice = input.nextLine();
char[][] seats = new char [13][6];
for(i = 0; i < 13; i++) {
seats[i][0] = '*';
seats[i][1] = '*';
seats[i][2] = '*';
seats[i][3] = '*';
seats[i][4] = '*';
seats[i][5] = '*';
}
while (seatchoice.length() > 0 ) {
int row = seatchoice.charAt(0) - '1';
int col = seatchoice.charAt(1) - 'A';
if (seats[row][col] != 'x') {
seats[row][col] = 'x';
System.out.println(" ");
printSeats(seats);
}
}
}
the method printSeats
private static void printSeats(char[][] seats) {
System.out.println("\t A B C D E F");
for (int i = 0; i < seats.length; i++) {
System.out.println("Row " + (1 + i) + "\t " + seats[i][0] + " " + seats[i][1] + " " + seats[i][2] + " "
+ seats[i][3] + " " + seats[i][4] + " " + seats[i][5]);
}
}
Now, when i try inputting "10A" it will give me, Index -17 out of bounds for length 6. I'm expecting it to change the row 10 column A to be x
A B C D E F
Row 8 * * * * * *
Row 9 * * * * * *
Row 10 x * * * * *
Row 11 * * * * * *
Row 12 * * * * * *
Row 13 * * * * * *
Thank you in advance. Please correct me in any ways or if there's something that i should learn. I'm willing to accept any criticism.
Since the Letter is always in the last index you can do it this way
int row = Integer.parseInt(seatchoice.substring(0, seatchoice.length() - 1)) - 1;
int col = seatchoice.charAt(seatchoice.length() - 1) - 'A';
Related
I need to write a function that takes an array and prints '*' for each index by the value of the index
for example for 1,2,3,4 the output will look like this:
enter image description here
but my output is vertical
1
2
3
4
this is my printing code :
public static void printStars(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j <= a[i]; j++)
System.out.print("*");
System.out.println(" " + a[i]);
}
}
[edit] try the following:
public static void printStars(int[] a) {
int maxValue = Collections.max(Arrays.stream(a).boxed().toList());
String[] line = new String[a.length]; //this also works
for (int i = maxValue; i >=0 ; i--) {
//String[] line = new String[a.length]; //this will keep allocating new memory
for (int j = 0; j < a.length; j++) {
if (i == 0) {
line[j] = String.valueOf(j+1); //<change j+1 to a[j] in order to print out the value at each index of the array if you are not looking to print indexes
}else if (a[j] >= i) {
line[j] = "*";
}else {
line[j] = " ";
}
}
System.out.println(String.join(" ", line));
}
}
it takes the maximum value in the array and stores in a variable. This is used to iterate each line. After that, it checks if at this current iteration, does an index of your array contain an asterisk in this location? if yes, assign asterisk to the specific index of the string array corresponding to index of original array, else assign whitespace.
Finally, when it goes to 0, you assign the either the values of your array or the indexes of the array to the string[]. Then you print the array by using String.join() with a delimiter of whitespace. This allows you to focus on white index contains a whitespace or not, and not need to focus on the formatting of whitespaces in between each item.
for the input [1,2,3,4] output is:
*
* *
* * *
* * * *
1 2 3 4
for the input [1,7,3,4]:
*
*
*
* *
* * *
* * *
* * * *
1 2 3 4
The solution from the previous answer works but I provided a slightly more compact version printStars and renamed the old one to printStarsOld. Here is the code:
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class IntTest {
public static void printStarsOld(int[] a) {
int maxValue = Collections.max(Arrays.stream(a).boxed().toList());
String[] line = new String[a.length]; //this also works
for (int i = maxValue; i >= 0; i--) {
for (int j = 0; j < a.length; j++) {
if (i == 0) {
line[j] = String.valueOf(j + 1);
} else if (a[j] >= i) {
line[j] = "*";
} else {
line[j] = " ";
}
}
System.out.println(String.join(" ", line));
}
}
public static void printStars(int[] a) {
List<Integer> list = Arrays.stream(a).boxed().toList();
StringBuffer string = new StringBuffer();
Integer max = list.stream().max(Integer::compare).get();
for (int i = max; i > 0; i--) {
int finalI = i;
list.forEach(integer -> string.append(integer - finalI < 0 ? ' ' : '*').append(' '));
System.out.println(string.toString());
string.setLength(0);
}
for (Integer i=1; i<=list.size();i++) System.out.print(i.toString() + ' ');
}
#Test
public void test() {
System.out.println("Old output: ");
printStarsOld(new int[]{2, 4, 5, 1, 3});
System.out.println("New output: ");
printStars(new int[]{2, 4, 5, 1, 3});
}
}
The output is:
Old output:
*
* *
* * *
* * * *
* * * * *
1 2 3 4 5
New output:
*
* *
* * *
* * * *
* * * * *
1 2 3 4 5
My goal is to get this output when input is 3:
* *
* *
* *
*
* *
* *
* *
Here is my code:
public static void PrintX (int number) {
for (int i = 0; i <= (number * 2 + 1); i++)
{
for (int j = 0; j <= (number * 2 + 1); j++)
{
if (i == j)
{
System.out.print("*");
}
else if (i + j == (number * 2 + 2))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println("");
}
}
My output when input is 3 is like this and I'm not sure why there is the extra star at the top.
*
* *
* *
* *
*
* *
* *
* *
Your outer loop would work as you expect if you set an initial i value of 1. However, you could also make this a little shorter. First, consider storing the number * 2 + 1. Then you might combine a few lambda expressions with IntStream. Basically, you want to map each possible index to a " " or a "*" - so
public static void PrintX(int number) {
int len = number * 2 + 1;
IntStream.rangeClosed(1, len).forEachOrdered(i -> {
IntStream.rangeClosed(0, len)
.mapToObj(j -> i == j || i + j == len + 1 ? "*" : " ")
.forEachOrdered(System.out::print);
System.out.println();
});
}
Set i = 1 inside outer for loop. Compile and run the example below:
public class TestPrintX {
public static void PrintX (int number) {
for (int i = 1; i <= (number * 2 + 1); i++)
{
for (int j = 0; j <= (number * 2 + 1); j++)
{
if (i == j)
{
System.out.print("*");
}
else if (i + j == (number * 2 + 2))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println("");
}
}
public static void main(String arg[]) {
PrintX(3);
} // end of main method
} // end of class
I am trying to print each digit of an integer and then sum of each digit like this. There is something wrong with the loops but I cant seem to figure it out. I want it to be like this:
Please enter a number: 194
1 * 100 = 100
9 * 10 = 90
4 * 1 = 4
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = ""+num;
double d = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = s.length()-1; j >= 0; j--) {
d = Math.pow(10,j);
System.out.println(s.charAt(i) + " * " + d
+ " = " + (s.charAt(i)*d));
}
}
}
}
This is the output of my code:
Enter the number: 194
1 * 100.0 = 4900.0
1 * 10.0 = 490.0
1 * 1.0 = 49.0
9 * 100.0 = 5700.0
9 * 10.0 = 570.0
9 * 1.0 = 57.0
4 * 100.0 = 5200.0
4 * 10.0 = 520.0
4 * 1.0 = 52.0
There's a couple problems with your code.
The first problem is that you don't need two loops, you just need one.
The second problem is confusing chars and ints. '0' is not the same as 0; instead, '0' is a numeric value representing the encoding of that character (which turns out to be 48). So to get the correct value that you want, you should subtract '0' from the char before doing your math.
for(int i = 0; i < s.length(); i++) {
d = Math.pow(10, s.length() - i - 1);
int value = s.charAt(i) - '0';
System.out.println(value + " * " + d
+ " = " + (value*d));
}
This will get it close to the output you wanted. It's still showing the .0 at the end though, because d is a double. Make it an int to fix that.
//This can be scoped to inside the loop, so you don't need to declare it beforehand
int d = (int)Math.pow(10,j);
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = "" + num;
int len = s.length() - 1;
long d = 0;
if (len < 2) {
d = 1;//For single digit
} else {
d = (long)Math.pow(10, len);
}
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + " * " + d + " = "
+ ((s.charAt(i) - '0') * d));
d = d / 10;
}
}
}
For some reason only the odd numbered lines are spacing correctly. Can someone please explain this? Here is my code.
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
int i, j, k1;
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of the side of your equilateral triangle: ");
int side = in.nextInt();
System.out.println("Enter the character you want your triangle filled with: ");
char fill = in.next().charAt(0);
while (side<=0 || side>50){
System.out.print("Please enter a length between 1 and 50: ");
side = in.nextInt();
break;
}
for(i=1; i<=side;i++){
for (k1=0; k1 < (side-i/2);k1++){
System.out.print("\t");
}
for(j=1;j<=i;j++){
System.out.print(fill + "\t");
}
System.out.println('\n');
}
in.close();
}
}
This is my outcome:
Enter the length of the side of your equilateral triangle:
5
Enter the character you want your triangle filled with:
*
*
* *
* * *
* * * *
* * * * *
I want this:
#
# #
# # #
# # # #
# # # # #
Just add this and change /t to 4 spaces:
if(i%2 ==0 && j ==1){
System.out.print(" "); // two spaces
}
Full code
for(i=1; i<=side;i++){
for (k1=0; k1 < (side-i/2);k1++){
System.out.print(" ");
}
for(j=1;j<=i;j++){
if(i%2 ==0 && j ==1){
System.out.print(" ");
}
System.out.print(fill + " ");
}
System.out.println('\n');
}
The reason is because every even line needs to start with a little offset since it has to be in the middle of the filler character and i get this
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
You haven't stated the desired outcome, but remove the /2 might do the trick.
Maybe replace both \t with a space.
Remove the '\n' from println, unless you want a blank line between lines.
How about this:
try (final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
System.out.print("Enter the length of the side of your equilateral triangle: ");
final int side = scanner.nextInt();
System.out.print("Enter the character you want your triangle to be filled with: ");
final char character = scanner.next().charAt(0);
for (int i = 1; i <= side; i++) {
final StringBuilder builder = new StringBuilder(side);
for (int k = 0; k < (side - i); k++) {
builder.append(' ');
}
System.out.printf(builder.toString());
for (int j = 0; j < i; j++) {
System.out.printf("%s ", character);
}
System.out.println();
}
}
Please notice the try-with-resources with Scanner — only available in from Java 7 (and onwards).
I managed to get the result if I enter the base and exponent, but the output should be
For example: the output should look like this
>>base:5 exponent: 2
5^2 = 25
5^1 = 5
I need help to put something somewhere to make this happen...
import java.util.Scanner;
public class recursion {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int base = 0;
int expo = 0;
System.out.print("Enter number for base ");
for (int i = 0; i < 1; i++)
base = scanner.nextInt();
System.out.print("Enter number for exponent ");
for (int j = 0; j < 1; j++)
expo = scanner.nextInt();
System.out.println(base + "^" +expo +" = " + pow(base,expo));
}
public static int pow(int x, int p) {
System.out.println(x + "^" +p +" = " );
if (p == 0)
return 1;
if (p % 2 == 0) {
int a = pow(x, (p / 2));
return a * a; // This line
} else {
int a = pow(x, ((p - 1) / 2));
return x * a * a; // This line
}
}
}
Firstly, the following code snippets demands a review:
{
for (int i = 0; i < 1; i++)
/*
* This for loop is unnecessary.
* It asserts that the following clause is run only once,
* which is true for any statements anyway.
*/
// ...
}
return a * a;
} /* if (p % 2 == 0) */ else {
/*
* Statements are unnecessarily nested within else clause.
* The corresponding then clause does not complete normally.
* Moving the following code snippet out of an else block
* would have the same effect, but simplifies the control
* statements.
*/
int a = pow(x, ((p - 1) / 2));
return x * a * a;
}
Within your pow() method, you have a System.out.println() method. You're calling it for debugging, but it's unnecessary as the process returns normally. As you're looking for printing the operations for exponent as "from user-specified exponent -> 1" ("in descending order"), use a loop to print your System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));:
do // New!
System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));
while (expo-- > 1); // New!
} /* main( args ) */
and you can remove the debugging line in pow().
Example: (>> denotes STDIN)
Enter number for base >> 5
Enter number for exponent >> 2
5^2 = 25
5^1 = 5
Enter number for base >> 4
Enter number for exponent >> 5
4^5 = 1024
4^4 = 256
4^3 = 64
4^2 = 16
4^1 = 4
View a live code demo.
void power(int base, int exp){
//Use for loop to iterate through each exp down to 0
for(int i=exp; i>=0; i--){
int result= exponent(base,i);
System.out.println(base + "^" + i + "=" + result)//Will display result as 5^2=25
}
//Recursively computes the result of b^e.
int exponent(int b, int e){
if(e==0){//Base case occurs when e=0.
return (1);
}
return (b * exponent(b,e-1));
}