Ok i'm going to show my code and my input and output, Its very strange the value of my array seems to change from one line to the next.
import java.io.*;
class chefAndNewRecipe
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new FileReader("/home/jer/Documents/chef.txt"));
int testCases = Integer.parseInt(r.readLine());
int numGuesses =0 ;
for (int i=0; i<testCases; i++)
{
int ingredients = Integer.parseInt(r.readLine());
String quantity = r.readLine();
String arr[] = quantity.split(" ");
int[] numIngredients = new int[arr.length];
for (int j =0; j< ingredients; j++)
{
String temp = arr[i];
numIngredients[i] = Integer.parseInt(temp);
System.out.println("This is numIngredients index: " + j + " and value " +numIngredients[i]);//print array location and value
}
System.out.println("numIngredients[0]:" + numIngredients[0]); // should be 2 and is
System.out.println("numIngredients[1]:" + numIngredients[1]); // should be 2 and is 0??
for (int k = 0; k< numIngredients.length; k++)
{
if (numIngredients[k] <2)
{
System.out.println("Value of numIngredients[k]: " + numIngredients[k]);// print value of numIngredients
System.out.println("-1");
}
else
{
numGuesses += numIngredients[k];
}
}
System.out.println(numGuesses);
}
}
}
my input is:
2
2
2 2
1
6
And my output is:
This is numIngredients index: 0 and value 2
This is numIngredients index: 1 and value 2
numIngredients[0]:2
numIngredients[1]:0
Value of numIngredients[k]: 0
-1
2
ingredients: 1
The value of numIngredients[1] changes from 2 to 0 from one line to the next, I can't understand whats going on.
Using long variable names is useful even for loop variables - you are seem to be using i instead of j:
for (int j = 0; j < arr.length; j++) // <== possibly arr.length is what you need.
{
String temp = arr[j]; // <=== was i, same next line
numIngredients[j] = Integer.parseInt(temp);
System.out.println(
"This is numIngredients index: " + j + //<== j this line
" and value " + numIngredients[j]); // <== again, was using [i]
}
Using currentIngredient instead of j possibly could help with finding an error.
Related
It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.
I have a little problem that i need help with.
For this assignment (Lesson 12 HW9) name NumberFormatException,I had to do the following below
"Calculator.java, is a simple command-line calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands. Your program should display a message that informs the user of the wrong operand before exiting (see the figure shown below)."
c:\exercise>java Exercise12_01 "4 + 5"
4 + 5 = 9
c:\exercise>java Exercise12_01 "4 - 5"
4 - 5 = -1
c:\exercise>java Exercise12_01 "4x - 5"
Wrong Input: 4x
SO all the math parts of the coding is finished, correct, and works, the only part I cant seem to figure out is:
" display a message that informs the user of the wrong operand before exiting" Wrong Input: 4x. I need to know what I can do to show not only the error message, but the error input as well. the part where it show the error message to the user is at the end of the code at
catch(InputMismatchException ex)
{
System.out.println("Bad input, please correct your operard.");
} //need to add the input error as well
here the full code, thank you
import java.util.*;
public class FillZerosOnes {
public static void main(String[] args) {
Scanner Read = new Scanner(System.in);
Random randNum = new Random();
int n;
int rowCount, columnCount;
int maxrowCount, maxcolumnCount;
ArrayList<Integer> Rows = new ArrayList(),Columns = new ArrayList();
int[][] matrix;
System.out.println("Enter the array size n: ");
n = Read.nextInt();
matrix = new int[n][n];
System.out.println("The random array size : ");
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrix[i][j] = randNum.nextInt(2);//choose the number above 1 for the number you want to be less then
//if I want 0 & 1, out 2
System.out.print(matrix[i][j]);
}
System.out.println();
}
columnCount = 0;
maxrowCount= 0;
maxcolumnCount =0;
for (int i = 0; i < n; i++)
{
rowCount =0;
for (int j = 0; j < n; j++)
{
if (matrix[i][j] ==1 )
{
rowCount++;
}
}
if (rowCount > maxrowCount )
{
maxrowCount = rowCount;
Rows.removeAll(Rows); // or Rows = new Arraylist();
Rows.add(i);
}
else if (rowCount == maxrowCount)
{
Rows.add(i);
}
}
//copy and paste
for (int j = 0; j < n; j++)
{
columnCount =0;
for (int i = 0; i < n; i++)
{
if (matrix[i][j] ==1 )
{
columnCount++;
}
}
if (columnCount > maxcolumnCount )
{
maxcolumnCount = columnCount;
Columns.removeAll(Columns); // or Rows = new Arraylist();
Columns.add(j);
}
else if (columnCount == maxcolumnCount)
{
Columns.add(j);
}
} //end paste
System.out.print("Largest row indices: ");
for (int i = 0; i < Rows.size(); i++)
{
System.out.print(Rows.get(i));
}
System.out.printf("\nLargest column indices: ");
for (int i = 0; i < Columns.size(); i++)
{
System.out.print(Columns.get(i));
}
}
}
System.out.println("text to show"+variable);
I usually log the stack trace on exception:
System.out.println("Bad input, please correct your operand." + ex.getMessage());
But you can also print out your variables in a similar manner:
System.out.println("Bad input, please correct your operands: " + n + ", " + v);
I am trying to write a collection of for-loops that produce the following series of numbers below. I am trying to accommodate my loops to print each series on the same line, with spaces between each term. I am new to java and got really confused on how exactly I can accomplish it. On the right side are the digits I am increasing the counting by.
1. 4 5 6 7 8 9 10 (+1)
2. 6 5 4 3 2 1 (-1)
3. 2 4 6 8 10 12 14 16 (+2)
4. 19 17 15 13 11 9 7 5 (-2)
5. 7 15 23 31 39 (+8)
6. 2 4 8 16 32 64 (*2)
Here is the code the way I tried to accomplish it. I got the first row to work but I'm wondering weather there's an easy way I can create the rest of them without re-duplicating the program.
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run()
{
{
for(int row = 1; row < 2; row++)
{
print(" " + row + ". ");
for (int col = 4; col < 11; col++)
{
print(row*col + " ");
} //col values
println( );
} //row values
}
}
}
I am new to java and right now going over for-loops and trying to accomplish this in for-loop. If someone could help me out, I would really appreciate it.
Thank you!
Edit:
Here is what happens when I increase the number of rows.
Edit:
Here is the solution of what I had tried accomplishing. Thanks to everyone who helped me.
import acm.program.*;
public class ppLoop extends ConsoleProgram
{
public void run()
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
print(i + ". "); // print row number 1
for (int j = 4; j < 11; j++) // loop for row 1
{
print(j + " ");
}
println( );
print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
print(j + " ");
}
println();
print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
print(j + " ");
}
println();
print((i + 3) + ". ");
for (int j = 19; j > 4; j = j - 2) // loop for row 4
{
print(j + " ");
}
println();
print((i + 4) + ". ");
for (int j = 7; j < 40; j = j + 8) // loop for row 5
{
print(j + " ");
}
println();
print((i + 5) + ". ");
for (int j = 2; j < 65; j = j * 2) // loop for row 6
{
print(j + " ");
}
println();
}
} //close outer loop
} //close public run
} //close console program
You can perform this program with a series of nested loops. I have done the first three rows. I took out your package and used a main method. Also, your indentation was very confusing. Since your increment changes each line, I don't know of a way to make it any shorter than this using for loops.
public class ppLoop{
public static void main(String[] args)
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
System.out.print(i + ". "); // print row number
// you can use the same variable for each inner loop
for (int j = 4; j < 11; j++) // loop for row 1
{
System.out.print(j + " ");
}
System.out.println( );
System.out.print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
System.out.print(j + " ");
}
System.out.println();
System.out.print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
System.out.print(j + " ");
}
}
}
}
}
You could create a method that takes:
1. A start number
2. What math operation to perform (add, subtract, or multiply)
3. What number to increment/decrement or multiply by
4. An end number
It would look similar to this:
public void formattedFor(int startNum, String operation, int num, int endNum) {
if (operation.equals("add")) {
for (int i = startNum; i < endNum; i += num) {
System.out.print(i + " ");
}
}
if (operation.equals("sub")) {
for (int i = startNum; i > endNum; i -= num) {
System.out.print(i + " ");
}
}
else if (operation.equals("mult")) {
for (int i = startNum; i < endNum; i *= num) {
System.out.print(i + " ");
}
}
System.out.println( );
}
If I'm understanding the problem, you want to print six series that each start with a different number and increment/decrement that number by some value. Since I see no relationship between the initial value and the increment/decrement, you're going to have to write six separate for loops.
If you're absolutely averse to this, you can store your initial values, your increments/decrements, and your final values in an array and iterate through them using a for loop, an if statement (to deal with the multiplication) and a while loop. The array would look like this:
int[][] values = new int[][] {
{4, 6, 2, 19, 7, 2},
{1, -1, 2, -2, 8, 2},
{10, 1, 16, 5, 39, 64}
};
I could write up the source based on this, but it's not what you asked for.
I strongly suspect that, if this is a homework assignment and you've modified the problem, there's something you've failed to understand about the problem itself. If this is meant to have an simple solution that uses for loops, there should probably be some logic that binds the rows together, unless you're allowed to use arrays/while loops/for loops/objects and methods.
On another note, you should format your code differently. It's somewhat difficult to read right now. In general, indent things that happen inside loops, classes, or functions. For example:
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run() {
for(int row = 1; row < 2; row++) {
print(" " + row + ". ");
for (int col = 4; col < 11; col++) {
print(row*col + " ");
} //col values
println( );
} //row values
}
}
I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]
I have to solve the following problem: Given an array of integers and given an integer value, list all possible numbers form the array that sums up to the given value.
Example:
Input: array = {1, 2, 2, 3, 4, 5}, int N = 5
Output: {1, 2, 2}, {1, 4}, {5} {2, 3}.
here is my code till now, can anybody help me?
import java.util.Scanner;
public class sumarray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int[] array = new int[3];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] + array[j] == 5) {
System.out.println("{" + array[i] + "," + array[j] + "}");
}
}
}
}
}
This is a common Dynamic Programming problem called Subset Sum.
You can do this like so if you only want to print (note that you have {2, 3} twice because there are two 2s):
public class Main {
public static void main(String[] args){
int[] arr = {1, 2, 2, 3, 4, 5};
subsetSum(arr, 5);
}
private static void subsetSum(int[] arr, int sum) {
subsetSum(arr, 0, sum, "");
}
private static String lineSep = System.getProperty("line.separator");
private static void subsetSum(int[] arr, int i, int sum, String aggregated) {
if (sum == 0){
System.out.println("Success with:" + aggregated);
System.out.println("And done.");
System.out.println();
return;
}
if (arr.length <= i){
// failed (uncomment following lines to see why)
// System.out.println("Failed with:" + aggregated);
// System.out.println();
return;
}
int current = arr[i];
subsetSum(arr, i+1, sum, aggregated + lineSep + "not " + current);
subsetSum(arr, i+1, sum - current, aggregated + lineSep + current);
return;
}
}
This uses the fact that String is immutable (so a new string is created for every frame), and does forward aggregation of selected numbers. I've added some text to make it descriptive so you see what's going on.
Output:
not 1
not 2
not 2
not 3
not 4
5
And done.
not 1
not 2
2
3
And done.
not 1
2
not 2
3
And done.
1
not 2
not 2
not 3
4
And done.
1
2
2
And done.
This is problem called Subset Sum.
and this my code and i know not professional but it is solution for this specific problem
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[6];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
int N=5; //N= the given value
int a1=0; // for use to sure not duplicate answer in this case is {2,3}
int a2=0; // for use to sure not duplicate answer
// and we put in a1 and a2 numbers if we add together dose not equal N which is here equal(5)
for (int i = 0; i < array.length; i++) {
if (array[i]==N)
System.out.println("{" + array[i] +"}");
for (int j = i+1; j < array.length; j++) {
for (int f = j+1; f < array.length; f++){
if(array[j]+array[i] == 5 ){
if(a1!=array[i] && a2!=array[j]){ // make sure dose not same number that is done.
System.out.println("{" + array[i] + ","+ array[j] + "}");
a1=array[i];
a2=array[j];}}
else if(array[i] + array[j]+array[f] == 5){
System.out.println("{" + array[i] + "," + array[j] + ","+ array[f] + "}");}
}}}}
the output is :
{1,2,2} {1,4} {2,3} {5}
i hope this help you :)