Calling a method that displays the output pattern only - java

I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}

You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.

Related

Knapsack Solution using Recursion and Array

I would like to know the best possible way to modify this code. Instead of adding the integers to an array in the code itself, I would like the user to input the different weights and the capacity via keyboard.
Now I am currently having compiling errors when inserting the data. I believe the problem lies within the for loop.
import java.util.*;
public class NN01276494 {
public static ArrayList <Double> sack = new ArrayList <Double> ();
public static void main(String [] args){
Scanner in = new Scanner (System.in);
int i =0;
for(i = 0; i<sack.length; i++){
System.out.println("Enter Capacity");
sack.size(in.nextDouble());
}
while (in.hasNextDouble()){
System.out.print("Enter weights");
sack.add(in.nextDouble());
i++;
}
}
public static Boolean knapsackproblem(double targetWeight, int index)
{
Boolean complete = false;
if(index == sack.size()) return false;
if(sack.get(index) == targetWeight)
{
System.out.print("Answer: " + sack.get(index) + " ");
complete = true;
}; //DONE
if(sack.get(index) < targetWeight)
{
complete = knapsackproblem(targetWeight-sack.get(index), index+1);
if(complete) System.out.print(sack.get(index) + " ");
for(int i = index+1; i < sack.size(); i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i);
}
}
if(sack.get(index) > targetWeight) complete =
knapsackproblem(targetWeight, index+1);
return complete;
}
}
The most common way to accept user input in java is the Scanner class. This allows your users to input into the console, and your program to use their input. Here is the javadoc that details scanners in detail, but here's all you need to do to accept integer inputs from your users:
First, import the scanner dictionary so you can use it.
import java.util.Scanner;
This will give you access to the Scanner library. To construct the scanner, you need to specify an input stream in the declaration. To make the console this input stream, declare it like so:
Scanner nameOfScanner = new Scanner(System.in);
Now, to get the integers for the array, use the method .nextInt() as many times as you want. Make sure to ask the user separately for each input, and if you want the user to be able to control the size of the array, you can also ask the user for that. Just in case you don't know, you can declare an array to have a certain size, but not specify what is going to be in each location until later like so:
int[] nameOfArray = new int[sizeOfArray];
On a separate note, I noticed that you had a semicolon after the closing bracket of your if statement in the middle of the knapsackproblem() method. I don't know if that's a typo in your question or actually in your code, but it really shouldn't be there.
I hope this helps, and good luck coding!
I've modified your code so user can input the array via an ArrayList :-using ArrayList user can input data without regard to length just enter as many values as you want then at the end type any letter for ex:[Out] then your method should start working :).
import java.util.*;
public class knapsack {
public static void main(String [] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter Capacity");
int y = in.nextInt();
double [] sack = new double [y];
System.out.println("enter values");
for (int i =0;i<y;i++){
sack[i]=in.nextDouble();
}
}
public static Boolean knapsackproblem(double targetWeight, int index ,
double [] sack)
{
Boolean complete = false;
if(index == sack.length) return false;
if(sack[index] == targetWeight)
{
System.out.print("Answer: " + sack[index] + " ");
complete = true;
}; //DONE
if(sack[index] < targetWeight)
{
complete = knapsackproblem(targetWeight-sack[index], index+1,sack);
//keep going
if(complete) System.out.print(sack[index] + " ");
for(int i = index+1; i < sack.length; i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i,sack);
}
}
if(sack[index] > targetWeight) complete = knapsackproblem(targetWeight,
index+1,sack);
return complete;
}
}
Hope it helps.Also I've fixed your recursion since you wrote knapsack( instead of knapsackproblem(.ArrayList comes from java,util package which also includes the Scanner class I just got them all using * ArrayList is a class that has its own methods like .size() and .add().

Methods for Functions

Note: Desire to move this to Code Review with a clearer structure for answer and my modified code which was very similar to the answer besides calcmin method.
I'm trying to break this code up into multiple methods and I was successful with the first bit but the other two I can't seem to figure out.
With the second method I was trying to make it so it would ask the user for an integer and continually prompts them until a proper integer is entered.
With the third method I was trying to make it so that it takes three integer parameters and returns the minimum value of those parameters.
I'd really appreciate the help on this. I've looked through examples in my book and can't seem to get it.
My code:
import java.util.Scanner;
public class MinOfThreeInts
{
public static void intro ()
{
System.out.println("This program determines the minimum of three ints");
System.out.println("It gracefully reports errors when erroneous data is entered ");
System.out.println("For example, if you type in 'abc' when this program asked for an int");
System.out.println("the program will report the error & ask for another int");
System.out.println("Try giving it bad input ! \n\n");
}
public static void readInt (int value1, int value2, int value3)
{
System.out.print(" Please enter an integer value ");
Scanner console = new Scanner(System.in);
String input = console.nextLine();
Boolean goodInt;
int parsedValue = 0;
goodInt = false;
while (!goodInt)
{
try
{
parsedValue = Integer.parseInt(input);
goodInt = true;
}
catch(NumberFormatException ex)
{
System.out.print(" Invalid input, please enter Int ");
input = console.nextLine();
}
}
value1 = parsedValue;
// Get the second integer
System.out.print(" Please enter an integer value ");
input = console.nextLine();
goodInt = false;
while (!goodInt)
{
try
{
parsedValue = Integer.parseInt(input);
goodInt = true;
}
catch(NumberFormatException ex)
{
System.out.print(" Invalid input, please enter Int ");
input = console.nextLine();
}
}
value2 = parsedValue;
// Get the third integer
System.out.print(" Please enter an integer value ");
input = console.nextLine();
goodInt = false;
while (!goodInt)
{
try
{
parsedValue = Integer.parseInt(input);
goodInt = true;
}
catch(NumberFormatException ex)
{
System.out.print(" Invalid input, please enter Int ");
input = console.nextLine();
}
}
value3 = parsedValue;
}
public static void calcMin (min)
{
int min = value1;
if (value2 < min)
{
min = value2;
}
if (value3 < min)
{
min = value3;
}
// Now report the results
System.out.println(" The minimum value of the three ints is " + min);
}
public static void main(String[] args)
{
value1 = readInt(console);
value2 = readInt(console);
value3 = readInt(console);
min = calcMin(value1,value2,value3);
}
}
You have a couple of issues. I refactored your code and added comments, I stayed close to your code in order to give you insights on where you can improve.
First, the code:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MinOfThreeInts {
//the main method, things start here
public static void main(String[] args) {
//initialize a new scanner that the application will use
Scanner console = new Scanner(System.in);
//print the intro
intro();
//read the values one by one and save them in a variable
int value1 = readInt(console);
int value2 = readInt(console);
int value3 = readInt(console);
//calculate the minimum and save it in the min variable
int min = calcMin(Arrays.asList(value1,value2,value3));
// Now report the results
System.out.println(" The minimum value of the three ints is " + min);
}
/**
* Reads an integer from the given console
*/
public static int readInt(Scanner console) {
System.out.print(" Please enter an integer value ");
//read the input
int parsedValue = 0;
boolean goodInt = false;
//as long as we don't find a valid number
while (!goodInt)
{
try
{
//read the input
String input = console.nextLine();
//try to parse the value
parsedValue = Integer.parseInt(input);
//set goodInt to true so that the while loop will end
goodInt = true;
}
catch(NumberFormatException ex)
{
//if the provivded value was not an integer, print a message and return to the start of the while loop
System.out.print(" Invalid input, please enter Int ");
}
}
return parsedValue;
}
/**
* calculates the minimum of a list of values
*/
public static int calcMin (List<Integer> values) {
//find the minimum and return the value
return Collections.min(values);
}
/**
* prints an intro message
*/
public static void intro () {
System.out.println("This program determines the minimum of three ints");
System.out.println("It gracefully reports errors when erroneous data is entered ");
System.out.println("For example, if you type in 'abc' when this program asked for an int");
System.out.println("the program will report the error & ask for another int");
System.out.println("Try giving it bad input ! \n\n");
}
}
Now, on what you can do to improve:
compile the code does not compile, always take care your code compiles and then slightly edit it until it compiles again
scope your code has multiple declared integers, the problem was that the values were not visible in other methods, if you declare a variable, say int value1 in some method, another method will not be able to see it. If you have another int value1 in that other method, it will only be visible in that specific method and it will actually be another variable
arguments vs return types methods take arguments and return something. The arguments are the input of the method and the returned value is the result of the method. Take for example your method: public static void readInt (int value1, int value2, int value3). This is a method that should read an integer value from the console. However, this method signature says it takes 3 integers as parameter. These integers would be passed by value, since they are primitive types, so you can not pass them, then fill them and then return them. There is also no return type, so the method is not returning something. Since the integer parameters value1, value2 and value3 are only visible in the method scope, you will loose your data. Compare with the new signature: public static int readInt(Scanner console). This method takes a console to read from as a parameter and returns an integer, the number that has been read. This method encapsulates the retry.

Using nextLine() and nextInt() together in my context always gets an error

I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.

Calling Methods with Arguments

Write the following methods:
13. A method named loadScores that will be passed the size of an array, prompt the user to enter the appropriate number of floating point grades, then return the loaded array.
I wrote the method, but the problem comes when I try to call it. Here's what I have:
public class ArrayHandout {
public static void main(String[] args) {
int size = loadScores(size);
double[] scoresArray = loadScores(size);
} // end main
public static double[] loadScores(int size) {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
} // end loadScores
} // end class
I have changed a few things in an attempt to correct some errors I was having when I wrote the original code, and unfortunately don't even remember what those changes were or if they fixed the problems since I can't get it to compile now. I do know that the problem I was having when I could get the original to compile was that it was only printing the first number in the array rather than printing the entire array. Like I said, I don't know if that problem has been corrected since now when I try to compile I receive the following error message:
1 error found:
File: C:\Users\HiTechRedneck\Desktop\Fall 2013\PlayingwithJava\ArrayHandout.java [line: 6]
Error: incompatible types
required: int
found: double[]
I know that size needs to be declared in main because previously I was getting the "cannot find variable size" error, but I think the fact that I'm trying to declare int size as loadScores(size) is throwing it off since the variable I'm declaring is also an argument in the method.
Any help would be greatly appreciated.
Your line int size = loadScores(size) is incorrect. loadScores has a return type of double[], so you need to assign that return value as such.
Just delete that one line and everything should work as expected.
int size = loadScores(size); is throwing an error because loadScores returns an array of type double.
Since the task just wants a code snippet you could probably give size an arbitrary value and pass that in. Or you could get rid of size in main and just pass a number in:
public static void main(String[] args) {
double[] scoresArray = loadScores(5);
}
Edit: Also worth noting that the print statement after the for loop will throw an ArrayIndexOutOfBoundsException since i is now greater than the length of the array. If you want to print the contents of the scoresArray you'll need another loop to traverse through each element.
Second edit: If you're prompting the user for a size you should run your prompt for that in the main method and then pass that to loadScores().
You don't need size at all before you call the function as you read it in the function
your declaration could be :
public static double[] loadScores()
and call
loadScores()
in main. Example:
public class ArrayHandout {
public static void main(String[] args) {
double[] scoresArray = loadScores();
//do whatever you want here or change declaration of
//the function to void and do not return anything
}
public static double[] loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
}
}
if you don't use the returned array it would be better to do it like this:
public class ArrayHandout {
public static void main(String[] args) {
loadScores();
}
public static void loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
}
}
(When a method doesn't return anything you have to specify it by using the void keyword in its signature)-You also need validation but I was only answering to the specific problem -without validation your program will still fail if incompatible values are given.

integer value read from System.in is not the value typed

I am a newbie to Java, and as an exercise wanted to WAP a simple program to print required no. of '*' characters according to the user. But somehow, the output of this code always remains similar:
package stars;
public class Stars {
public static void main(String[] args) {
int no_stars=0;
try {
System.out.print("Enter the number of stars:");
no_stars = (int)System.in.read();
} catch ( Exception e) {
System.out.println("Error! Invalid argument!");
System.out.println();
}
printstars(no_stars);
}
public static void printstars(int n){
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}
}
If I replace '*' with i, I can see that it loops upto 50/52/54, even though i run the loop no_stars times.
What seems to be the problem here?
You need to parse the number received from System.in.read() or alternatively read it as an integer, currently you just cast it, so if you enter 5, it passes 0x35 times (which is the value of the character '5')
You can do, for example:
Scanner scan = new Scanner( System.in );
printstars( scan.nextInt() );
Because you are reading ASCII code of the character from input here:
no_stars = (int)System.in.read();
It should be
no_stars = Integer.parseInt(Console.readLine());
There are two mistakes in your code.
First
System.in.read()
Is reading a byte, not a integer, so, it is parsing the integer and getting the first byte of it.
Second
for (i = 0; i <= n; i++) {
will print always one star more than requested.
So, it should be changed to
for (i = 0; i < n; i++) {
Suggestion: You could use Scanner to read your integer, for example
Scanner scanner = new Scanner(System.in);
no_stars = scanner.nextInt();
no_stars = (int)System.in.read();
This is using the ASCII value of whatever character the user enters. Try this instead:
no_stars = System.in.read() - '0';
Or, remove the no_stars variable all together,
printstars(System.in.read() - '0');
Also, in your for-loop, the condition should be i < n, in order to perform the correct number of iterations. And there's no need to declare i outside of the loop, you can just do for (int i = 0; i < n; i++).
Here is the corrected program for you: (the main problem was this line //no_stars = (int)System.in.read();)
public static void main(String[] args) {
int no_stars=0;
try{
System.out.print("Enter the number of stars:");
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();
no_stars = Integer.parseInt(name);
//no_stars = (int)System.in.read();
}
catch ( Exception e) {
System.out.println("Error! Invalid argument!");
System.out.println();
}
printstars(no_stars);
}
public static void printstars(int n)
{System.out.println(n);
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}

Categories

Resources