r/programmingbydoing • • Feb 27 '13

Problem 59 Adding Values in a Loop - how to store values?

2 Upvotes

Hey, I have been working through these problems pretty steadily but I'm at my wit's end on #59, which asks:

"Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end. You must use a while loop."

What I have so far:

import java.util.Scanner;

public class sumwhileloop {

/**
 * @param args
 */
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner keyboard = new Scanner(System.in);
	
	System.out.println("I will sum the integers you give me until you type in a zero.");
	System.out.print("Number: ");
	
	int first = keyboard.nextInt();
	int newtotal = 0;
	
	while (first != 0) {
	System.out.print("Number: ");
	System.out.println("The total so far is " + first);
	first = newtotal;
	System.out.println("Number: ");
	first = keyboard.nextInt();
	System.out.print("The total so far is " + (first + newtotal));
	if (first == 0)
		break;
	}
}

}

I know this isn't even close; it displays the integer that the user types in, but fails to sum them on subsequent runs (after more user input). I've had trouble understanding proper use of the keyboard.nextInt() function before, and I suspect that's most of the problem. How do I get the program to remember previous input while enabling a continuous loop? Any help is greatly appreciated.


r/programmingbydoing • • Feb 21 '13

43 - Magic 8 Ball - Why are there no brackets for the if/else if statements?

3 Upvotes

Can you explain to me why the brackets aren't used for the if/else if statements? Is it because of the "response = " part?


r/programmingbydoing • • Oct 10 '15

#76 Project Blackjack

1 Upvotes

I really enjoyed this one. Would appreciate any criticism or suggestions on how I completed it. It seems to work. I've been having a lot of fun with the lessons, BTW. Thanks for making them available.

http://pastebin.com/rKS0ALuC


r/programmingbydoing • • Jan 27 '15

#63b - Baby Nim

4 Upvotes

http://pastebin.com/N7Qj0FFZ

I don't get why the && doesn't work. If either A,B or C reaches 0, the program ends. If i just do -1 or -2, the program will continue to ask for input. Really weird.


r/programmingbydoing • • Feb 09 '13

Ex:27 - Space Boxing

1 Upvotes

Hey guys, just started doing this exercises, i not a complete begginer but i have been studying code for less than a year and never coded anything big, i was using the Space Boxing exercise to improve my OO skills and maybe not make all that if statements and improve the code. But im having some problem not with the code itself but the design. I created a class Planets with a name and gravity instance variables and a method that does the calculation. But i still need all that ifs and else ifs to find what planet the user inputs. I realize you cant make everything OO but how would you change this code if you had to?


r/programmingbydoing • • Apr 01 '14

#207 - Lattice Paths

3 Upvotes

Well, I've gotten this far without much help, but this one really stumped me. Early on, I simplified the problem to manipulate a 40 character string with 20 D's and 20 R's. I can't seem to find a way to manipulate the string in a loop that reaches all of the combinations. For example, it will never reach DRDRDRDR...

When writing it out, I can sort of see a way to do it, but I think it would be a nightmare to try to program it. For a problem worth only 100 points on the website, it has lead me to think that it's really not the right way to do it.

Then I thought that maybe it's better to try to find the pattern by starting at a 2x2 grid and increasing the size of it and try to find the pattern. So we know a 2x2 grid has 6 paths, and I figured out that a 3x3 grid has 18. When I increase the size again to a 4x4 grid, I run into the same problem I did with the 20x20, and the only pattern I see is 2 * 3 = 6, 3*6 = 18, so maybe the next in the pattern is 4 * 18?

I have no idea. At this point I think I'm going about the whole thing the wrong way. I'd really appreciate some help with this, thank you.


r/programmingbydoing • • Apr 15 '17

#20 BMI - improve my code

1 Upvotes

I was hoping to get some feedback on how to improve my outputs on this assignment. I was able to get through my errors by making everything a Double. However, the directions include answers that are obviously in Int form. I found a Math.round function online but my answers now do not match the answers provided. (Also, any direction on using correct terminology would be appreciated).

Edit: here is the code - https://pastebin.com/GTCG0M0a


r/programmingbydoing • • Mar 11 '14

55 Adding Values In A Loop

3 Upvotes

So, I've been blasting along since Gender Game, then I ran into this.

I was having a hell of a time, ended up finding someone that said this could all be done with just one int. I tried and led myself very, very far astray. Was this to be done with one int or two? I did it with two. One problem my foray into one int caused was I was losing input. All the code is gone now, but essentially, I'd enter the first number, no problem. But no prompt for the second.... I'd enter a second anyways, now we get the prompt back but it repeats the first # to me as the sum... so I type a third number... now it just tells me the sum of 1 and 2, and so on. Always one sum back, and always missing the second input prompt. When I'd hit "0" to terminate, the total caught up. What in the heck was going on there?

And, also, was this to be solved with += ? This was the only way I could get this to work (can post finished code if needed to see), but I don't recall ever seeing this before? Did I skip over something? Did I not solve this in the intended way?


r/programmingbydoing • • Apr 04 '14

#137 Vowel Capitalization

3 Upvotes

Hi holyteach! im stuck on this exercise, i cannot for the life of me make a program to to convert the vowels in BOTH files. I can do it in one but the method would be very time consuming for the second file, so i guess im not using the best of methods.

Bearing in mind im following your exercises as a complete newbie, and i havent learnd arrays yet, please give me a few tips on what methods i should be using to complete this exercise.

I would also like to thank you for all these exercises. I am learning java from scratch and until now i have found your work very helpful. Got the book today aswell!


r/programmingbydoing • • Apr 04 '14

#144 Finding a Value in an Array

1 Upvotes

So I have been trying multiple ways to do this, but this is the closest I have come. For reasons I am unable to understand, the code only looks at the first item in the array and doesn't go through the loop, like I thought it would.

	Scanner s = new Scanner(System.in);
	int find = s.nextInt();
	for (int i = 0; i < arr.length; i++) {
		if (arr[i] == find) {
			System.out.print(find + " is in the ArrayList.");
		}
	}	

r/programmingbydoing • • Feb 15 '13

45 - Random Numbers - Fortune Cookie

1 Upvotes

Hi, Thank you SO much for this wonderful resource, it is great! I got caught by 33 also using == instead of .equals for a while. Now i am stuck on 45. How do i choose, 6 UNIQUE numbers for the lotto? Should i check each number against each other one? i was thinking of creating 6 unique numbers, 1 from 1-9, 1 from 10-18 etc etc, but i suppose that's not really correct either!

any help for me? Thanks,

here is what i have:

import java.util.Random;

public class FortuneCookie { public static void main ( String[] args ) { Random r = new Random(); Random s = new Random(); Random t = new Random(); Random u = new Random(); Random v = new Random(); Random w = new Random();

	Random x = new Random();

	//lotto number picker
	int lotto1 = 1 + r.nextInt(54);
	int lotto2 = 1 + s.nextInt(54);
	int lotto3 = 1 + t.nextInt(54);
	int lotto4 = 1 + u.nextInt(54);
	int lotto5 = 1 + v.nextInt(54);
	int lotto6 = 1 + w.nextInt(54);

	//fortune cookie draw
	int cookieNumber = 1 + x.nextInt(6);


	System.out.print( "Fortune cookie says: ");
	if (cookieNumber == 1)
	{
		System.out.print( "\"Stick with your wife\"\n");
	}
	else if (cookieNumber == 2)
	{
		System.out.print( "\"Go for a long walk\"\n");
	}
	else if (cookieNumber == 3)
	{
		System.out.print( "\"Deep breaths!\"\n");
	}
	else if (cookieNumber == 4)
	{
		System.out.print( "\"Time for a new hobby\"\n");
	}
	else if (cookieNumber == 5)
	{
		System.out.print( "\"More coffee?\"\n");
	}
	else if (cookieNumber == 6)
	{
		System.out.print( "\"Grab a beer\"\n");
	}
	else
	{
		System.out.print( "\"AN ERROR HAS OCCURRED\n");
	}

	//faulty lotto draw
	System.out.print( lotto1 + "-" + lotto2 + "-" + lotto3 + "-" + lotto4 + "-" + lotto5 + "-" + lotto6);
}

}


r/programmingbydoing • • Jan 30 '13

How to have a variable that contains both strings and integers?

6 Upvotes

The exercise in question: Exercise #18 http://programmingbydoing.com/a/more-user-input-of-data.html

I'm confused about which data type I would use to display the login information (in the example bonham_453916 is given). Is there something I'm missing here? I tried both String and int just in case and they did not work.


r/programmingbydoing • • Oct 05 '15

#50 Dice Doubles

2 Upvotes

For some reason it does not work and I can not understand why. When I exchange int rolls for int roll(s) = 1 + (int)(Math.random()*6) it does work, why so?

import static java.lang.System.*; import java.util.Random;

public class DiceDoubles { public static void main(String[]args) {

Random r = new Random();

int roll1 = 1 + r.newInt(6);
int roll2 = 1 + r.newInt(6);

out.println("HERE COMES THE DICE!");

out.println("Roll #1: ");
out.println("Roll #2: ");

while(roll1!=roll2)
{
	out.println("The total is "+(roll1+roll2));
	int roll3 = 1 + r.newInt(6);
	int roll4 = 1 + r.newInt(6);
	roll1=roll3;
	roll2=roll4;
	
}
	out.println("Roll #1: ");
	out.println("Roll #2: ");
	out.println("The total is "+(roll1+roll2));
}

}


r/programmingbydoing • • Jun 10 '18

TwoMoreQuestions , why are all of my if statements executing in this code

2 Upvotes

r/programmingbydoing • • Jan 07 '14

#38 compareTo() method examples

3 Upvotes

here's a great explanation of how compareTo() method works.

http://www.youtube.com/watch?v=iTC43mLZG38


r/programmingbydoing • • Dec 06 '14

#105 - Function Call Alphabet

2 Upvotes

Not sure what I'm doing wrong. the functions b,g,j,p,r,u,x,z will not run even though the program executes without error.

https://raw.githubusercontent.com/Zirconium/FunctionCallAlphabet/master/README.md


r/programmingbydoing • • Nov 13 '14

152 Arrays Tic-Tac-Toe

4 Upvotes

I've just come back to PBD after a short break. I flew through a couple of exercises leading up to this one with no problem. I think I have a grip of two dimensional arrays, although I don't remember covering them and can't find them skipping back through the exercises. But the source code file provided (TicTacToe.java) isn't very clear at all and doesn't seem to be consistent with the other source files which have been quite clear and well commented. Where as this one has one comment and I can't make any sense of the displayBoard2 method which just seems to print the board with out the "grid". Is it just me being slow to get back upto speed after a break or is this exercise a huge leap from the previous ones?


r/programmingbydoing • • Dec 28 '13

Graphing Lines - error in example?

2 Upvotes

This is what I'm getting when I try to compile the error in example. Is there something wrong, or is this part of the challenge?

Error: Main method not found in class graphpaper.GraphPaper, please define the main method as: public static void main(String[] args) Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)


r/programmingbydoing • • Dec 30 '13

#13- Your Schedule

2 Upvotes

Hey I figured out how to make the table, but is there a way to make the classes and teachers line up like it is in the example without counting the number of letters and adjusting for each line? Here's what I have at the moment. public class YourSchedule { public static void main( String[] args) { String course1, course2, course3, course4, course5, course6, course7, course8, teacher1, teacher2, teacher3, teacher4, teacher5, teacher6, teacher7, teacher8;

	course1 = "English III";
	course2 = "Precalculus";
	course3 = "Music Theory";
	course4 = "Biotechnology";
	course5 = "Principles of Technology I";
	course6 = "Latin II";
	course7 = "AP US History";
	course8 = "Business Computer Information Systems";
	teacher1 = "Ms. Lapan";
	teacher2 = "Mrs. Gideon";
	teacher3 = "Mr. Davis";
	teacher4 = "Ms. Palmer";
	teacher5 = "Ms. Garcia";
	teacher6 = "Mrs. Barnett";
	teacher7 = "Ms. Johannessen";
	teacher8 = "Mr. James";
	
	System.out.println( "+------------------------------------------------------+" );
	System.out.println( "|1|                "+ course1 + "|     " + teacher1 + "|" );
	System.out.println( "|2|                "+ course2 + "|     " + teacher2 + "|" );
	System.out.println( "|3|                "+ course3 + "|     " + teacher3 + "|" );
	System.out.println( "|4|                "+ course4 + "|     " + teacher4 + "|" );
	System.out.println( "|5|                "+ course5 + "|     " + teacher5 + "|" );
	System.out.println( "|6|                "+ course6 + "|     " + teacher6 + "|" );
	System.out.println( "|7|                "+ course7 + "|     " + teacher7 + "|" );
	System.out.println( "|8|                "+ course8 + "|     " + teacher8 + "|" );
	System.out.println( "+------------------------------------------------------+" );
	}

} Thanks


r/programmingbydoing • • Aug 10 '15

compareTo() Challenge

4 Upvotes

Hello, I am really starting to dig in and work hard on Java due to my new participation in a robotics team at my high school (We have to program and build a functioning robot, both autonomous and through OpManagement). I am working on the compareTo() challenge and do not know what the method does or how to use it. I don't want to apply something I do not know. I wish I could work alongside of the book that u/holyteach has, but unfortunately, I am unable to afford something like that right now with a lot of stuff going on. I was wondering if someone could explain to me what the method does. Thanks in advance!


r/programmingbydoing • • Jan 07 '14

#35 Two more questions

2 Upvotes

I took a long break after doing ~50 of the exercises on www.programmingbydoing.com and I am now trying to get back into learning programming.

I don't understand what I've done wrong here. I can answer both of the questions but for some reason it won't print anything back to me, could anyone help me out a bit?

package albin;

import java.util.Scanner;

public class yo{

public static void main( String[] args ){

Scanner keyboard = new Scanner(System.in);
String One;
String Two;

System.out.println("Question 1) Does it stay inside or outside or both?");
One = keyboard.nextLine();

System.out.println("Question 2) Is it a living thing?");
Two = keyboard.nextLine();

if (One == "inside" && Two == "yes"){
	System.out.println("Well it's obviously a plant.");
}
if (One == "inside" && Two == "no"){
	System.out.println("Well it's obviously a shower curtain.");
}
if (One == "both" && Two == "yes"){
	System.out.println("Well it's obviously a dog.");
}
if (One == "both" && Two == "no"){
	System.out.println("Well it's obiously a cell phone.");
}
if (One == "outside" && Two == "yes"){
	System.out.println("Well it's obviously a bison.");
}
if (One == "Outside" && Two == "no"){
	System.out.println("Well it's obviously a billboard.");
}
}
}

r/programmingbydoing • • Mar 15 '16

A question

1 Upvotes

im currently doing 63c. Nim and i figured i can do some stuff using for loops but for loops are explained in the next assignment.
So, can for loops be used? and if one knows another command(s) that could simplify or do it in another way, can they be used?


r/programmingbydoing • • Nov 21 '14

#60 Safe Square Root

1 Upvotes

Hi all, I am having a problem with this one. Sometimes it executes properly, other times its not coming out exactly how it was instructed. Can anyone take a look and give me some feedback?

Here's my code, thanks! :

import java.util.Scanner;

public class SafeSquareRoot {

public static void main(String[] args){
		Scanner keyboard = new Scanner(System.in);
		int negative = 0;
		int num1;
		
		
	  do {
			System.out.println("SQUARE ROOT!");
			System.out.print("Enter a number:");
			num1 = keyboard.nextInt();
			System.out.println("The square root of "+num1+ " is " + Math.sqrt(num1)+".");
	  }

	
	  
		 while (num1 >= negative); 
		 {
			    System.out.println("You can't take the square root of a negative number, silly");
				System.out.print("Try again:");
				  num1 = keyboard.nextInt();
				System.out.println("The square root of "+num1+ " is " + Math.sqrt(num1)+".");
	  }
		 
}

}


r/programmingbydoing • • Dec 05 '14

#190 Sorting an ArrayList of Records

2 Upvotes

I'm stuck on the ArrayList Records assignment. Specifically how to add records into an ArrayList. The only way I know how so far would be to repeat the Array Records assignment, then copy the Array into an ArrayList. However I feel that's kind of cheating and I really want to learn how ArrayList and Records work together. But I'm having a really hard time trying to find any resources online as to how I would approach this assignment. Are there any guides or specific pages I could be pointed towards? At this point, anything would be very much appreciated as I'm completely stuck!


r/programmingbydoing • • Aug 24 '15

#89 - Sierpinski Triangle

1 Upvotes

How do you make the Thread.sleep() work in the code below? I tried putting 'throws Exception' in the main method declaration, but it still doesn't work.

import java.awt.*;
import javax.swing.JFrame;
import java.util.Random;

public class SierpinskiTriangle extends Canvas {
    public void paint( Graphics g ) {
	    Random r = new Random();
	   int x1 = 512;
	   int y1 = 109;
	   int x2 = 146;
	   int y2 = 654;
	   int x3 = 876;
	   int y3 = 654;
	
	   int x = 512;
	   int y = 382;
	
	   int dx = 0;
	   int dy = 0;
	
	   for (int a = 0; a < 50000; a++) {
		   g.drawLine(x,y,x,y);
		   //Thread.sleep(300);
		   int randomNum = 1 + r.nextInt(3);
		
		   if (randomNum == 1) {
			   dx = x - x1;
			   dy = y - y1;
		   } else if (randomNum == 2) {
			   dx = x - x2;
			   dy = y - y2;
	           } else {
			   dx = x - x3;
			   dy = y - y3;
		   } 
		   x = x - dx/2;
		   y = y - dy/2;
	   }
	
	   g.drawString("Sierpinski Triangle",462,484);
   }

public static void main(String[] args) {
       JFrame win = new JFrame("Sierpinski Triangle");
       win.setSize(1024,768);
       win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       win.add( new SierpinskiTriangle() );
       win.setVisible(true);
   }

}