When I run the code in the stdin line the program gives me an exception. How to solve it so the program works?
static double read_matrix(double matrix[][]) {
int i, j;
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
System.out.println("Enter elements:");
matrix[i][j]=stdin.nextInt();
}
}
return 0;
}
You are not declaring stdin inside your method.
To read from the user-input you can use for example: Scanner(System.in) that is provided by java.util.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main.read_matrix(new double[2][2]);
}
static double read_matrix(double matrix[][]) {
int i, j;
final Scanner scanner = new Scanner(System.in);
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
System.out.println("Enter element:");
matrix[i][j] = scanner.nextInt();
System.out.println("[" + i + "][" + j + "] = " + matrix[i][j]);
}
}
scanner.close(); // make sure to close it to prevent memory leaks
return 0;
}
}
Related
I am actually trying to print this pattern: https://imgur.com/a/ObixO5I
import java.util.*;
public class ques5 {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int n = 4;
// outer loop
for (int i = 1; i <= n; i++) {
// inner loop
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
}
}
}
}
Output I am getting is : * ** *******
Add System.out.println() at end of second inner loop.
Try this
import java.util.*;
public class ques5 {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int n = 4,m=1;
// outer loop
for (int i = n; i >=1; i--) {
// inner loop
for (int j = 1; j <= i - 1; j++) {
System.out.print(" ");
}
for (int k = 1; k <= m; k++) {
System.out.print("*");
}
System.out.print("\n");
m++;
}
}
}
}
import java.util.*;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
sc.close();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input))
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
}
}
}
}
}
When I get a number input, I want to make a code that represents this number as the sum of three numbers.
The code is complete, but there are several combinations. I want to print out only one combination. How can I edit it?
First, some important suggestions:
Do not parse input inside the nested loop as it will hit the performance. Do it once outside the nested loops.
Do not close Sacnner for System.in as it also closes System.in and there is no way to open it again without restarting JVM. It means that if it is being used in some other part of your application, your application will crash.
Always follow Java naming conventions e.g. you could name numJ instead of num_j.
Coming back to your problem, there are many ways to solve it and I have listed below just a couple of them:
Use break <<label>> to exit the nested loops:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
start: for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
break start;
}
}
}
}
}
}
A sample run:
Enter a number : 123
You entered: 123
(1, 22, 100)
Put the logic in a method and return:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
printFirstCombination(num);
}
static void printFirstCombination(int num) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
return;
}
}
}
}
}
}
You can create a seperate function for that and after you find a combination, print it and return there and then to the main function. In case you didn't find a combination you return 1 which can be handled in the main function,
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int res = printCombination(input);
if(res == 1) {
// Do something
}
sc.close();
}
private static int printCombination(String input) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input)) {
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
return 0;
}
}
}
}
return 1;
}
}
I basically need to find the number of sub arrays that have a negative sum.
import java.io.*;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static int add(int a[]) {
int sum = 0;
for (int i = 0; i < a.length; ++i) {
sum = sum + a[i];
}
return sum;
}
public static void main(String[] args) {
/*
* Enter your code here.
* Read input from STDIN.
* Print output to STDOUT.
* Your class should be named Solution.
*/
int count = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int k = 0; k < n; ++k) {
arr[k] = sc.nextInt();
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
if (add(slice) < 0) {
++count;
}
}
}
System.out.println(count);
}
}
Compile Message
Solution.java:32: error: variable j is already defined in method main(String[])
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
^
1 error
Exit Status
255
Its because of the scope of the variable j here. When you refer a variable in map, JVM tries to initiliaze this. In your case, JVM is trying to initialize j with the contents of the map but it is already available at that point from your second for loop. Just use any other variable such as 'k' to get it done.
import java.io.*;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static int add(int a[])
{
int sum= 0;
for(int i = 0; i < a.length; ++i)
{
sum = sum + a[i];
}
return sum;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int count = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int k = 0; k < n; ++k)
{
arr[k] = sc.nextInt();
}
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n - i; ++j)
{
int slice[] = IntStream.range(j, j + i + 1).map(k -> arr[k]).toArray();
if(add(slice) < 0)
{
++count;
}
}
}
System.out.println(count);
}
}
This line declares a variable j which is already declared as the loop counter in that scope:
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
You will have to give it a differen name to get rid of this compilation error:
for (int i = 0; i < n; ++i) {
// this is where j is defined for the loop scope
for (int j = 0; j < n - i; ++j) {
// replace the j inside the .map(...)
int slice[] = IntStream.range(j, j + i + 1).map(s -> arr[s]).toArray();
if (add(slice) < 0) {
++count;
}
}
}
I'm having some trouble in a couple of areas here. First, when the array is printed to screen, the "P" is placed at [0][0] - which is OK, but it is surrounded by 'null' for any other cell. I'd like it to be filled with dashes " - ". I'm also needing to code in an infinite loop that asks the user to input either 'up', 'down', 'left', 'right' or 'exit'. Does this infinite loop go into the "Driver" class, or the "World" class, and would a switch statement work for this?
Second - the rows and columns are not being summed and displayed. The "World" class is:
import java.util.*;
public class World
{
private static final String P = "P";
private String[][] array;
public World()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld()
{
System.out.println();
for(int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
System.out.print(array[i][j] + " - ");
}
System.out.println();
}
}
public void moveUp()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i - 1][j] = P;
}
return;
}
}
}
}
public void moveDown()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i + 1][j] = P;
}
return;
}
}
}
}
public void moveLeft()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i][j - 1] = P;
}
return;
}
}
}
}
public void moveRight()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i][j + 1] = P;
}
return;
}
}
}
}
}
The "Driver" class is:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
World world=new World();
world.moveUp();
world.moveDown();
world.moveLeft();
world.moveRight();
world.displayWorld();
}
}
You need to intialize every element in the array. Add this to the end of the World constructor:
for(int i=0;i<crow;i++){
for(int j=0;j<ccol;j++){
array[crow][ccol]="-";
}
}
You will need to add the infinite loop asking for input in the Driver class. In the infinite loop you need to:
Get input
Use switch statement to detect left, right, etc
Driver.java:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
World world = new World();
Scanner s = new Scanner(System.in);
while (true) {
String input = s.nextLine();
switch (input) {
case "up":
world.moveUp();
case "down":
world.moveDown();
case "left":
world.moveLeft();
case "right":
world.moveRight();
}
}
s.close();
}
}
I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code:
for(int i=1;i<=10;i++){
for(int j=10;j>i;j--){
System.out.println(" ");
}
for(int k=1;k<=i;k++){
System.out.print("*");
}
for(int l=10;l<=1;l++){
for(int h=1;h<=10;h++){
System.out.print(" ");
}
}
System.out.println();
}
What I am trying to do is:
*
***
*****
*******
Try this much simpler code:
public class ChristmasTree {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i; j++)
System.out.print(" ");
for (int k = 0; k < (2 * i + 1); k++)
System.out.print("*");
System.out.println();
}
}
}
It uses 3 loops:
first one for the number of rows,
second one for printing the spaces,
third one for printing the asterisks.
You can do it with simple logic
for (int i = 0; i < 4; i++)
System.out.println(" *******".substring(i, 4 + 2*i));
import java.util.Scanner;
public class cmastree{
public static void main (String[]args){
Scanner keyboard=new Scanner (System.in);
int j;
System.out.println ("Enter a number");
j=keyboard.nextInt();
/*take the above part out and change the j variable if you want to set
the size*/
for(int i=1; i<=j; i+=2){
int numSpaces = (j-i)/2;
for (int k=0; k<numSpaces; k++){
System.out.print(" ");
}
for(int k=0; k<numSpaces; k++){
System.out.print("*");
}
System.out.println();
}
}
}
public class ChrismasTree {
public static void main(String[] args) {
int sizeOfTree = 9;
double remainderVal = sizeOfTree % 2 ;
double ans = sizeOfTree / 2 ;
if (remainderVal == 0) {
System.out.println("Invalid number enter 9,19 calculat rest yourself u looser ..");
System.exit(0);
}
int middlePos = (int) Math.round(ans + .5);
for (int i = 0; i <= sizeOfTree; i++) {
int lStar = middlePos - i;
int rStar = middlePos + i;
if (lStar < 1) {
break;
}
printleaves(lStar, rStar, sizeOfTree);
}
}
public static void printleaves(int a,int b, int size){
System.out.println();
for (int i = 1; i <= size; i++) {
if (i > a && i < b ){
System.out.print("*");
}else System.out.print(" ");
}
}
}
public class Stars {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter Row/Column Value::");
int i,j,k,n;
n=s.nextInt();
for(i=1; i<n; i++){
for(j=n+(n/2); j>i; j--){
System.out.print(" ");}
for(k=1; k<=2*i-1; k++){
System.out.print("*");}
System.out.println("");
}
for(i=1; i<n+(n/2); i++){
for(j=n+(n/2); j>i; j--){
System.out.print(" ");}
for(k=1; k<=2*i-1; k++){
System.out.print("*");}
System.out.println("");
}
for(i=1; i<n-(n/2); i++){
for(j=n+(n/2); j>1; j--){
System.out.print(" ");}
for(k=n/2; k<=(n/2)+1; k++){
System.out.print("*");}
System.out.println("");
}
}
}
public class ChristmasTree {
public static void printStars(int number) {
for (int i = 1; i <= number; i++) {
System.out.print("*");
}
System.out.println("");
}
public static void printSpaces(int number) {
for (int i = 0; i < number; i++) {
System.out.print(" ");
}
}
public static void christmasTree(int height) {
for (int i = 1; i <= height; i++) {
printSpaces(height - i);
printStars(i + (i - 1));
}
}
public static void main(String[] args) {
// int x = pick some number, but not TOO big )))
christmasTree(x);
}
}
def fist(n)
k=2*n-2
for i in range(0,n):
for j in range(0,k):
k=k-1
print(end=" ')
for j in range(0,i+1):
print("*",end=" ")
print()
def second(n)
k=2*n-2
for i in range(0,n):
for j in range(0,k):
k=k-1
print(end=" ')
for j in range(0,i+1):
print("*",end=" ")
print()
def stem(m)
k=11
for i in range(0,5):
for j in range(0,k):
print(end=" ")
for j in range(0,3):
print("*",end=" ")
print()
first(7)
second(7)
steam(3)