I'm a freshman at uni and we have to make an assignment where we have to find the second smallest number in a line of integers. Now I THINK I got it but I can't get the result to print. Can anyone figure out why this is?
package SecondSmallest;
import java.util.Scanner;
import java.io.PrintStream;
public class SecondSmallest {
public static void secondSmallestLoop() {
Scanner in = new Scanner(System.in);
PrintStream out = new PrintStream(System.out);
out.printf("Please enter a series of at least 2 integers: ");
int smallest = in.nextInt();
int secondSmallest = in.nextInt();
while (in.hasNextInt()) {
int next = in.nextInt();
if (next < smallest) {
secondSmallest = smallest;
smallest = next;
}
else if (next < secondSmallest) {
secondSmallest = next;
}
}
out.print("The second smallest number is: " + secondSmallest);
}
public static void main(String[] args) {
SecondSmallest.secondSmallestLoop();
}
}
In my opinion, it is better to have a condition to stop your scanner. So I would suggest to use a do-while instead. You also should use System.out.println, because it's ready to print in your console. You don't have to instantiate a PrintStream everytime. And by the way, your code is working, but it would be interesting to consider the thoughts we gave to you.
Your problem is not defined stop point for the while loop.
in.hasNextInt() mean: If you input an integer, it will be continue. To stop it, you can input a character that isn't an integer.
Hope to helpful
Related
I just wanted to say first that I'm a beginner so I apologize for my (really) horrible code.
I'm creating a program where you input an int and print out the square root using a do while loop. And when you input "0" the program will stop.
How do you stop it?
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
do {
System.out.println("Please enter an integer.");
int sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot==0);
System.out.println("Closing...");
InputNum.close();
}
}
You need to test if the value entered was 0 (I would test less than or equal to zero, because the square root of a negative number is imaginary). If so, break the loop. Like,
int sqroot = InputNum.nextInt();
if (sqroot <= 0) {
break;
}
try this
public static void main(String[] args) {
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
int sqroot = 0;
do {
System.out.println("Please enter an integer.");
sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot != 0);
System.out.println("Closing...");
InputNum.close();
}
I just initialize sqroot outside of your while and change == to !=
This academic exercise may demand use of a do/while loop, but if you're not constrained to using it, a for loop would also work:
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
System.out.println("Please enter an integer.");
for(int sqroot = InputNum.nextInt(); sqroot > 0; sqroot = InputNum.nextInt()) {
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
}
System.out.println("Closing...");
InputNum.close();
}
Your program as presented in the question has an intrinsic flaw: you ask for input and then immediately try and do something with it (calc the square root) without determining if it is suitable to use.
Switching to a for loop is one way this can be overcome, because it encourages a program flow of "ask for input", "check if input is acceptable", "use input", "repeat"
If you're constrained to using a do/while loop then you still need to follow this flow, which Elliott Frish addresses in his answer, recommending you add in the "check if input is acceptable" part as a dual purpose test of whether the input is <= 0.. Such values are not acceptable for a square root op, and you also want to end the program when you encounter them, so the test can be used to achieve both goals
Side trivia, for loops can be used pretty much exclusively:
for(;;) //same as while(true)
for(;test;) //same as while(test)
for(bool do = true; do; do = test) //same as do..while(test)
..though using while or do is probably more readable than using a for loop for the same job
Note, your while(sqroot==0) is a bug.. you don't want to continue looping while the user entered 0, you want to continue looping while they DIDN'T enter a 0...
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().
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.
I am writing a program that arranges the elements in the array with the max being at the very end then would decrease in size as they move backwards in an array. I could just arrange them with smallest being first and so forth but I want to see if I could do the other way around. Below is my code.It does not work beyond the first iteration. Could anyone help me.
import java.util.Scanner;//Importing scanner class.
import java.util.Arrays;//Importing the array class.
{
public static void main(String[] args)
{
double [] numbers= {5,3,6,4,1};
double currentMax;
int currentMaxIndex;
int i,j,k;
// Scanner input = new Scanner(System.in);//Creating a scanner.
//The below lines are used to ask the user to enter 10 numbers.
/* for (k = 0;k<numbers.length;k++)
{
System.out.print("Enter number " + k +" : ");
numbers[k]=input.nextDouble();
}//end of for loop.
*/
for(i=numbers.length-1;i>1;i--)
{
currentMax=numbers[i];
currentMaxIndex=i;
for(j=numbers.length-2;j>0;j--)
{
if(currentMax<numbers[j])
{currentMax=numbers[j];
currentMaxIndex=j;
}
}
if(currentMaxIndex!=i)
{
numbers[currentMaxIndex]=numbers[i];
numbers[i]=currentMax;
}
}
System.out.print("The sorted new array is:\n");
for(i=0;i<numbers.length;i++)
{
System.out.print(numbers[i]+" ");
}
}
}
Although it doesn't directly answer your question, it does offer a reasonable alternative approach.
Refactor your code as follows:
Step 1: Delete all your code
Step 2: Type this instead:
Arrays.sort(numbers);
Obviously there are better ways to sort, but I think this should fix your code:
The outer loop should be checking for i >= 1 and the inner loop for j >= 0.
I am a beginner in Java and had a question regarding an assignment I was doing.
I am trying to read a sequence of integer inputs and print out the largest and the smallest number. Though I already wrote the code, but the problem is that when I run it, it doesn't print the largest nor the smallest number. The code seems right even though its not! Any help would be appreciated.
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integers: ");
int largest = in.nextInt();
int smallest = largest;
while (in.hasNextInt()) {
int input = in.nextInt();
if (input > largest) {
largest = input;
} else if (input < smallest) {
smallest = input;
}
System.out.println();
}
System.out.println(largest);
System.out.println(smallest);
}
}
To Stop Waiting for an input :
Enter A character as input : in.hasNextInt() return False
Your code will not stop accepting numbers until it get something other than a number.
Like a alphabetical character. Enter an alphabetical character or keep something as a terminator.
Like enter -99 to quit or something.
Reading the code I would say that you expect the user to enter a set of numbers separated by space (the default separator chosen by the Scanner)
The scanner will loop endless parsing the input.
Now you need to decide a condition to exit and make your code safer.
When I say make your vode safer I mean put a try catch around your code in case the user doesn't write a number. Moreover you should close the scanner in a finally.
If you write something like the code below, the cycle is broken whenever u write a letter. E.g 1 2 4 6 A will print 2 and 6. Take it as a suggestion to work out a bit. Actually. you need to still protect the first nextInt, which, as it is, could throw exception if you don't start with a number and ideally decide an exit character handling the other exceptions. But these are implementation details. The code below will work provided that you start with a number and finish with a character different from a number
import java.util.Scanner;
public class Practise {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integers: ");
int largest = in.nextInt();
int smallest = largest;
try {
while (in.hasNextInt()||in.hasNext()) {
int input = in.nextInt();
if (input > largest) {
largest = input;
} else if (input < smallest) {
smallest = input;
}
System.out.println("Computing "+input);
}
System.out.println(largest);
System.out.println(smallest);
} catch (Exception ex) {
System.out.print("Exception caught: " + ex);
} finally {
in.close();
}
}
}