loop with one new line not multiple JAVA - java

Java Newbie Here,
So i am attempting to write a program that can set the number of hello worlds, and the number of exclamation points that follow it, entering these value using the command line arguments. i have in a manner done it but the output format is wrong.
Desired result
"Hello World !!!!
"Hello World !!!!"
Attempt 1
"Hello World !
!
!
!" (this continues down)
what I am Getting, attempt 2
"Hello World !!!!Hello World!!!!Hello World!!!!"
my code for Attempt 1
public class NHelloWorldWE {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
System.out.println(" ");
}
}
}
}
My Code for Attempt 2
public class NHelloWorldWE {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
}
}
}
}

You need to use a new line print:
System.out.println("Hello World");
Like this:
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
}
System.out.println();
}
}
This one will give you a similar result, but with 1 less exclamation mark in each iteration (I believe this is what you are trying to do)
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a++) {
System.out.print("Hello World");
for (int b = 1; b <= e; b++) {
System.out.print("!");
}
e--;
System.out.println();
}
}

Here is a version of your solution:
public class NHelloWorldWE {
public static void main(String... args) {
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 0; a < n; a++) {
System.out.print("Hello World");
for (int b = 0; b < e; b++) {
System.out.print("!");
}
System.out.println();
}
}
}
And here is one using streams:
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NHelloWorldWE {
public static void main(String... args) {
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
final String hello = "Hello World" + Stream.generate(() -> "!")
.limit(e)
.collect(Collectors.joining());
Stream.generate(() -> hello)
.limit(n)
.forEach(System.out::println);
}
}

Related

How do you return multiple values from a for loop in Java using a return statement?

I would like to send multiple values from my getMultiples method to my main method using a return statement and no print or println statements.
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n")
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int getMultiples(int a, int b) {
int p = 0;
for (int i = 1; i <= a; i++) {
p = getMultiple(a,i);
}
return (p);
}
}
I have tried putting the return statement in the for loop but it does not work.
In Java as soon as return is encountered in the code, method is removed from execution stack and flow is returned back to calling method. So you can not return multiple values from a method. Rather you should create a list/array and return that as below(array example):
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n");
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p[] = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int[] getMultiples(int a, int b) {
int[] p = new int[a];
for (int i = 1; i <= a; i++) {
p[i-1] = getMultiple(a,i);
}
return p;
}
}

Assign values to array that have multible variables in java

I had created an array of the following class , when I try to assign new values it gives me null
my code as follows
public class edge {
public double w = 0 ;
public int a = 0 ;
public int b = 0 ;
}
edge edges[];
edges = new edge[5];
int c = 10
for ( int i = 0 , i< 5 , i++) {
edges[i]=new edge();
edges[i].a = i;
edges[i].b = i + 1;
edges[i].w = i/c ;
}
You have some problems in your code :
First : you should not put your code outside your class like you do
Secondd: you have to use the main method to start your program
Third : you should to separate your statement in your loop with ; and not with , your program should look like this :
public class Edge {
public double w = 0;
public int a = 0;
public int b = 0;
public static void main(String[] args) {
Edge edges[];
edges = new Edge[5];
int c = 10;
for (int i = 0; i < 5; i++) {
edges[i] = new Edge();
edges[i].a = i;
edges[i].b = i + 1;
edges[i].w = i / c;
}
}
}
Or you can separate them in differentiate classes like this :
public class Cls {
public static void main(String[] args) {
Edge edges[];
edges = new Edge[5];
int c = 10;
for (int i = 0; i < 5; i++) {
edges[i] = new Edge();
edges[i].a = i;
edges[i].b = i + 1;
edges[i].w = i / c;
}
System.out.println(Arrays.toString(edges));
//Output
//[edge{w=0.0, a=0, b=1}, edge{w=0.0, a=1, b=2}, edge{w=0.0, a=2, b=3}, edge{w=0.0, a=3, b=4}, edge{w=0.0, a=4, b=5}]
}
}
class Edge {
public double w = 0;
public int a = 0;
public int b = 0;
#Override
public String toString() {
return "edge{" + "w=" + w + ", a=" + a + ", b=" + b + '}';
}
}

Java Bot saves Princess Challenge

Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN.
Here is my code:
package challenges;
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p,String [][] grid){
int botRow=0,botCol=0;
for(int r=0;r<n;r++){
for (int c = 0; c < grid.length; c++) {
if(grid[r][c].equals('m')) {
botRow=r;
botCol=c;
continue;
}
}
if(grid[0][0].equals('P')) {
while(botRow>0) {
botRow--;
System.out.println("UP\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[0][p-1].equals('P')) {
while(botRow>0) {
System.out.println("UP\n");
botRow--;
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
else if(grid[n-1][0].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[n-1][p-1].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
while(j<n){
grid[i][j] = in.next();
j++;
}
}
displayPathtoPrincess(m,n,grid);
}
}
Its giving Null Pointer Exception.can anyone please tel what am i doing wrong in here?
Try this solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
char grid[][] = new char[m][m];
for(int i = 0; i < m; i++)
{
String line = br.readLine();
grid[i] = (line.trim()).toCharArray();
}
displayPathtoPrincess(m, grid);
}
static void displayPathtoPrincess(int m, char[][] grid)
{
int botRow = 0, botCol = 0, princessRow = 0, princessCol = 0;
// Get bot and princess coordinates
for (int r = 0; r < m; r++)
{
for (int c = 0; c < grid.length; c++)
{
if (grid[r][c] == 'm' || grid[r][c] == 'M')
{
botRow = r;
botCol = c;
}
else if (grid[r][c] == 'p' || grid[r][c] == 'P')
{
princessRow = r;
princessCol = c;
}
}
}
// Move the bot up or down till bot reaches same row
if( princessRow < botRow )
{
while(botRow != princessRow)
{
botRow--;
System.out.println("UP");
}
}
else if( princessRow > botRow )
{
while(botRow != princessRow)
{
botRow++;
System.out.println("DOWN");
}
}
// Move the bot left or right till bot reaches same column
if( princessCol < botCol )
{
while(botCol != princessCol)
{
botCol--;
System.out.println("LEFT");
}
}
else if( princessCol > botCol )
{
while(botCol != princessCol)
{
botCol++;
System.out.println("RIGHT");
}
}
}
}
Ok, no offence but this code is a mess.
I know what I will answer won't be exactly what you want, but it might be very helpful for you in the future.
What would I change? (After you change all of this, the error will more likely become apparent or it will be clear enough to ask for help)
First: Variable types.
This is just a tiny detail, but I don't like the way you did it; why use a String if every cell will be represented by a char?
Every time you create a variable (or an Array, or anything at all) think about what you need it to store, and create the variable in a way it will store what you need. If you needed it to store if something is true or false, you wouldn't create a String variable and store "true" or "false", you would use a boolean.
Apply this every time and you will improve faster.
Second: use functions.
Functions are a great way to abstract yourself from the implementation details.
I mean, you can easily see the difference between something like your code, and something like:
static void displayPathtoPrincess(int n, int p,char [][] grid){
Point bot;
Point princess;
getInitialPositions(bot, princess, grid);
Point dif = getRelativePrincessPosition(bot, princess);
while (!bot.equals(princess)) {
switch (dif.y) {
case UP:
move (UP_MOVEMENT);
break;
case DOWN:
move (DOWN_MOVEMENT);
break;
}
switch (dif.x) {
case LEFT:
move(LEFT_MOVEMENT);
break;
case RIGHT:
move(RIGHT_MOVEMENT);
break;
}
}
}
(And then implement the necessary methods, and create the constants, that is something pretty easy to do)
Third: use the appropriate loop every time.
If you know you want to go from j = 0, while j < n, increasing j every iteration; that's not called a while, that's called a for. (Also, as someone else commented in their answer, you forgot to restart the j; so it only goes in once.
Finally: Let's go with your error now.
I believe your code might be pretty buggy and not give you the desired output, but the NullPointerException is something more specific.
Since you don't use the appropriate loop in the main, for j, and you forgot to restart it's value, you didn't fill the whole array.
When you try to read a value you didn't fill (in the for where you find the robot's position), that value is null, and the value for some rows will be null too; hence the NullPointerException (because you try to access the value of a null array).
While taking input you have to make j =0 every time you are coming out of while loop as
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
j = 0;
while(j<n){
grid[i][j] = in.next();
j++;
}
}
i remains 0 due to this mistake.
You should put print statement to check why are you getting error.
here is the solution..
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p, String[][] grid) {
int botRow = 0, botCol = 0;
for (int r = 0; r < n; r++) {
for (int c = 0; c < grid.length; c++) {
if (grid[r][c].equalsIgnoreCase("m")) {
botRow = r;
botCol = c;
}
}
if (grid[0][0].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[0][p - 1].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
} else if (grid[n - 1][0].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[n - 1][p - 1].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
int j;
String grid[][] = new String[m][m];
for(int i = 0; i < m; i++) {
for(j=0;j<m;j++){
grid[i][j] = in.next();
}
}
displayPathtoPrincess(m,m,grid);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static void nextMove(int n, int r, int c, String [] grid){
int xcord=0;
int ycord=0;
for ( int i = 0 ; i <n-1; i++){
String s = grid[i];
xcord=i;
for(int x =0; x<=n-1;x++){
if(s.charAt(x)=='p'){
ycord=x;
if(xcord==r){
if(ycord>c){System.out.println("RIGHT");return;}
else {System.out.println("LEFT");return;}
}else if(xcord<r){System.out.println("UP");return;}
else{ System.out.println("DOWN");return;}
}
}
}
System.out.println(xcord);
System.out.println(ycord);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n,r,c;
n = in.nextInt();
r = in.nextInt();
c = in.nextInt();
in.useDelimiter("\n");
String grid[] = new String[n];
for(int i = 0; i < n; i++) {
grid[i] = in.next();
}
nextMove(n,r,c,grid);
}
}
You might wish to take a look at the following code in Java:
import java.util.Scanner;
public class Solution {
/*
*
*/
static void printPath(int n, String moves) {
for (int i = n / 2; i >= 0; i -= 2) {
System.out.println(moves);
}
}
/*
*
*/
static void displayPathtoPrincess(int n, String [] grid){
// **** princess # top left ****
if (grid[0].substring(0, 1).equals("p")) {
printPath(n, "UP\nLEFT");
}
// **** princess # top right ****
else if (grid[0].substring(n - 1, n).equals("p") ) {
printPath(n, "UP\nRIGHT");
}
// **** princess # bottom right ****
else if (grid[n - 1].substring(n - 1, n).equals("p")) {
printPath(n, "DOWN\nRIGHT");
}
// **** princess # bottom left ****
else {
printPath(n, "DOWN\nLEFT");
}
}
/*
* Test code
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for(int i = 0; i < m; i++) {
grid[i] = in.next();
}
// **** ****
in.close();
// **** ****
displayPathtoPrincess(m,grid);
}
}

Java Fibonacci series

What would be the next step in order to ask the user which of the numbers in this series of 30 he wants to see and prompts for an integer input - a number between 1 and 30 (inclusive)?
So if the user wants to see the fifth (5th) number of the Fibonacci series the user would input the integer 5 in response to the prompt.
public class MyFibonacci {
public static void main(String a[]) {
int febCount = 30;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++) {
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++) {
System.out.print(feb[i] + " ");
}
}
}
Use a Scanner, or some InputStreamReader to read the input from the console. Scanner would be used in this way:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt())
int someInt = scanner.nextInt();
Another option would be to use some reader like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
and parse the required data from the output of the reader. Using Scanner will be simpler in most cases though.
public class Fibonacci_series // upto less than a given number
{
public static void main(long n)
{
long a=0, b=1, c=0;
while (c<n)
{
a=b;
b=c;
System.out.print(c+", ");
c=a+b;
}
System.out.print("....");
}
}
Here you go :
public class TestProgram {
public static void main(String a[]) {
Scanner reader = new Scanner(System.in);
printFibonacciSeries();
System.out.println("");
System.out.println("Fibonacci Series, Enter the number in the series of 30 you want to see");
int num = reader.nextInt();
int febCount = 30;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
if (i == num) {
System.out.print(feb[i] + " ");
}
}
}
public static void printFibonacciSeries() {
int febCount = 31;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
System.out.print(feb[i] + " ");
}
}
}
You could use a command line argument and read it from the main method args:
public class MyFibonacci {
public static void main(String a[]) throws NumberFormatException {
int febCount = Integer.parseInt(a[0]);
then call it with
java MyFibonacci 30
Or pass it in the 'VM options' input in an IntelliJ run configuration

How to create main class for public static int method in java?

I'm sorry for this noob question but I'm not really familiar with this method. This method generates check digit for ean 8 barcodes. How can I create the main class for this method? Are there any other ways of generating check digit for ean 8 barcodes?
public class CheckDigit {
public static int checkdigit(String idWithoutCheckdigit) {
String validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVYWXZ_";
idWithoutCheckdigit = idWithoutCheckdigit.trim().toUpperCase();
int sum = 0;
for (int i = 0; i < idWithoutCheckdigit.length(); i++) {
char ch = idWithoutCheckdigit.charAt(idWithoutCheckdigit.length() - i - 1);
if (validChars.indexOf(ch) == -1)
throw new RuntimeException("\"" + ch + "\" is an invalid character");
int digit = ch - 48;
int weight;
if (i % 2 == 0) {
weight = (2 * digit) - (digit / 5) * 9;
} else {
weight = digit;
}
sum += weight;
}
sum = Math.abs(sum) + 10;
return (10 - (sum % 10)) % 10;
}
}
Just add another method in your class:
public class CheckDigit {
public static int checkdigit(String idWithoutCheckdigit) {
/*
Good looking implementation of your method
*/
}
public static void main(String[] args) {
//fill the String with a expected value
String idWithoutCheckdigit = "...";
//evaluate the String with your method
int useAGoodNameForThisVar = checkdigit(idWithoutCheckdigit);
//print the results
System.out.println("checkdigit(" + idWithoutCheckdigit + ") = " + useAGoodNameForThisVar);
}
}
Main methods in java look like this (having a main method makes a class the main class).
public static void main(String[] args)
{
//code...
}
Perhaps then you want to then call your method
public static void main(String[] args)
{
// print the results of your method
System.out.println(checkdigit("This is the string i'm giving to my method."));
}
public static void main(String[] args){
for(String each : args){
System.out.println(CheckDigit.checkdigit(each));
}
}
Like this:
public class CheckDigit {
public static void main(String[] args) {
if (args.length > 0) {
for (String arg : args) {
System.out.println(CheckDigit.checkdigit(arg));
}
} else {
System.out.println("Please give some values on the command line");
}
}
public static int checkdigit(String idWithoutCheckdigit) {
String validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVYWXZ_";
idWithoutCheckdigit = idWithoutCheckdigit.trim().toUpperCase();
int sum = 0;
for (int i = 0; i < idWithoutCheckdigit.length(); i++) {
char ch = idWithoutCheckdigit.charAt(idWithoutCheckdigit.length() - i - 1);
if (validChars.indexOf(ch) == -1)
throw new RuntimeException("\"" + ch + "\" is an invalid character");
int digit = ch - 48;
int weight;
if (i % 2 == 0) {
weight = (2 * digit) - (digit / 5) * 9;
} else {
weight = digit;
}
sum += weight;
}
sum = Math.abs(sum) + 10;
return (10 - (sum % 10)) % 10;
}
}

Categories

Resources