import java.util.Scanner;
public class Max {
public int findMax() {
/* Type your code here. */
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();
int largestInt = 0;
while (userInput > 0) {
if (userInput > largestInt) {
largestInt = userInput;
}
}
return largestInt;
}
public static void main(String[] args) {
Max test = new Max();
System.out.println(test.findMax());
}
}
This is being tested on Zybooks, and everything I have tried has resulted in the program timing out. I can't figure out why! I think my while loop is very logical, what am I missing?
1:Compare output
0 / 1
Program timed out
Output differs. See highlights below.
Input
2 77 17 4 -1
Your output
Expected output
77
If userInput is greater than largestInt, assign userInt value to largestValue until userInt is negative, and return largestInt.
Your loop condition is based on userInput, which doesn't change inside the loop.
Related
I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);
I had this code where after reading the first three lines of input, it would just terminate the program and would not let me enter the next line. Here's the code:
import java.util.Arrays;
import java.util.Scanner;
public class cycle {
public static void main(String[] arg)
{
System.out.println("Put in numbers");
Scanner in=new Scanner(System.in);
int indicator=Integer.parseInt(in.nextLine());
if(indicator==1)
{
mission1();
}
else if(indicator==2)
{
mission2();
}
in.close();
}
static void mission1()
{
Scanner miss1=new Scanner(System.in);
int citizens=Integer.valueOf(miss1.nextLine());
String lines=miss1.nextLine();
lines=lines.replaceAll("\\s", "");
int length=lines.length();
String lines2=miss1.nextLine();
lines2=lines.replaceAll("\\s", "");
int length2=lines.length();
while(citizens!=length||citizens!=length2)
{
System.out.println("Citizens number do not match, try again" );
miss1=new Scanner(System.in);
citizens=Integer.valueOf(miss1.nextLine());
lines=miss1.nextLine();
lines=lines.replaceAll("\\s", "");
length=lines.length();
lines2=miss1.nextLine();
lines2=lines.replaceAll("\\s", "");
length2=lines.length();
miss1.close();
if(citizens!=length||citizens!=length2)
{
throw new IndexOutOfBoundsException("Numebr of citizens do not match. Please enter numbers again");
}
else if(citizens==length&&citizens==length2)
{
String[] strs=lines.trim().split("\\s");
length=lines.length();
int[] dspeed = new int[length];
for(int i=0; i<length;i++)
{
dspeed[i]=Integer.parseInt(strs[i]);
}
String[] strs2=lines2.trim().split("\\s+");
int[] pspeed = new int[length2];
for(int i=0; i<length2;i++)
{
pspeed[i]=Integer.parseInt(strs2[i]);
}
Arrays.sort(dspeed);
break;
}
}
}
static void mission2()
{
}
}
For example, with an input like this:
Put in numbers
1
3
1 3 5
1 3 5
It would just terminate the program and it is ok, but with an input like this:
Put in numbers
1
3
1 3
1 3
Citizens number does not match, try again
1
3
1 3 5
The program would terminate before I can't put in the fourth line.
As a test I put in
for(int n=0;n<length;n+=1)
{
System.out.println(dspeed[n]);
}
in between Arrays.sort(dspeed[n]) and break, and the result is like this
Put in numbers
1
3
1 3
1 3
Citizens number do not match, try again
1
3
1 3 5
3
It makes no sense since it is giving me an output of 3 while not letting me enter the second line. So it is like part of the code is being skipped. Why is this happening and how do I fix this?
Edit: For mission1 it suppose to get a number(let's say x), and then get x numbers of different numbers from the next line. Then, it should put those numbers in an array and sort them
As of writing my answer I realized what the actual cause of your error is; look at this piece of code:
lines=miss1.nextLine();
lines=lines.replaceAll("\\s", "");
length=lines.length();
lines2=miss1.nextLine();
/*Should be lines2!*/
lines2=lines.replaceAll("\\s", "");
/*Should be lines2!*/
length2=lines.length();
You're using linesfor all your variables. Changing lines to lines2 for the lines2 = ... and length2 variables fixed the issue that you posted. I also replaced
if (citizens != length || citizens != length2) {
/*If you decide to keep this, it should not be a "IndexOutOfBoundsException
(since no index was out of bounds) but should perhaps be a "IllegalArgumentException"
since you supplied it illegal arguments.*/
throw new IndexOutOfBoundsException("Numebr of citizens do not match. Please enter numbers again");
} else if (citizens == length && citizens == length2) { ... }
with
if (citizens == length && citizens == length2) { ... }
Since otherwise this would cause the program to crash if you gave it an invalid input twice in a row.
This part of the answer should be considered code-review and is here to (try to) help improve your code structure. Actual answer is above.
This is the entire class code. This seems to have resolved your error and I've also re-structured some of the code and added comments explaining what I edited and why I restructured it. Please leave a comment if anything is unclear or if it didn't actually resolve your error. Please note that the imports are left out of this answer for clarity.
public class Cycle {
/* Important! We can re-use the same scanner for all inputs. */
final Scanner in;
public Cycle() {
in = new Scanner(System.in);
run();
in.close();
}
private void run() {
System.out.println("Input mission number.");
final int indicator = Integer.parseInt(in.nextLine());
if (indicator == 1) {
mission1();
} else if (indicator == 2) {
// etc
}
}
private void mission1() {
while (true) {
System.out.println("Input number of citizens.");
final int citizens = Integer.valueOf(in.nextLine());
/* We don't edit these two first inputs just yet since we
* have to use the un-edited inputs later in our if-else
* statement. */
System.out.println("Input first number(s).");
final String inputOne = in.nextLine();
System.out.println("Input second number(s).");
final String inputTwo = in.nextLine();
final String lines = inputOne.replaceAll("\\s", "");
final int length = lines.length();
final String lines2 = inputTwo.replaceAll("\\s", "");
final int length2 = lines2.length();
if (citizens != length || citizens != length2) {
/* If the number of citizens doesn't match it just
* continues the while-loop and does it all over
* again. */
System.out.println("Citizens number do not match, try again");
} else {
/* Here we use the unedited inputs from before - which
* is why we didn't edit them. */
final int[] dspeed = createArrayFromInput(inputOne);
final int[] pspeed = createArrayFromInput(inputTwo);
break;
}
}
}
/* We shouldn't have duplicated code - use a method instead. */
private int[] createArrayFromInput(final String input) {
final String[] strs = input.trim().split("\\s+");
/* The arrays should be the same size so use 'strs.length' as
* length */
final int[] speed = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
speed[i] = Integer.parseInt(strs[i]);
}
Arrays.sort(speed);
return speed;
}
public static void main(final String[] arg) {
/*We should use a class instance instead of static methods and variables.*/
new Cycle();
}
}
In the method getHighestValue, why is fVI returning 0 every time? How do I get it to set it to the first valid input? I want to end up comparing it to each input that is entered to find the highest value.
public static void main(String[] args) {
int numCount;
int numScores = 0;
int values;
int fVS; //fVS = First Valid Score
Scanner input = new Scanner(System.in);
System.out.println("Enter test scores between 50 and 109");
numScores = getCount(input);
fVS = getHighestValue(input);
if (numScores == 0) {
System.out.println("No scores read");
} else {
System.out.println(numScores + " " + fVS);
}
}// ends main
//Counts the number of inputs
public static int getCount(Scanner input) {
int values;
int numberOfScores = 0;
while (input.hasNextInt()) {
values = input.nextInt();
if (values > 49 && values < 110) {
numberOfScores++;
}
} // ends while loop that scans for next int and counts each score input
return numberOfScores;
}// ends getCount
//Finds the highest value
public static int getHighestValue(Scanner input) {
int fVI = 0;
int value;
int numberOfScores = 0;
while (input.hasNextInt()) {
value = input.nextInt();
if (value > 49 && value < 110) {
fVI = value;
numberOfScores++;
}
}
return fVI;
}// ends getHighestValue
You have one scanner which getCount() will read integers from until there are no more left. Then getHighestValue() will also read integers from that scanner until there are none left.
But, and here's the rub, getCount() has already exhausted the scanner so there can be none left for getHighestValue().
Your best bet is to probably read them into a collection of some description so they're available to both functions.
So have a new function that reads the scanner once and populates and returns (for example) a Vector, then pass that vector to the two functions for processing.
I am trying to only accept integers between the values of 1 and 3 using a while loop and nested if statement in Java.
Anything outside of this range, produces an error message
The program should only accept integers between 1 and 3, any strings of text or decimal values should also produce the same error message and loop back to the original print statement (enter a number: )
The code below runs without any compiler errors although the statement || (a < 1 || a > 3)) will always produce the error message, regardless of the value.
If I was to delete this statement, the program will run and only accept integers of any value, (error message appearing when a string or decimal value is entered)
Could anyone help range this program, only accepting values of between 1 and 3, thanks.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
while (true) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext() || (a < 1 || a > 3)) {
System.out.println("Oops! ");
input.nextLine();
}
else {
a = input.nextInt();
break;
}
}
input.close();
System.out.println("a = " + a);
}
}
Make sure to be careful of the order of expressions. If one of the 3 statements you wrote happens to be true then the code in the if curly braces will execute. You likely want something like this
if (!input.hasNextInt() || !input.hasNext()){
if ((a > 1 || a < 3)){
YourCode
}
}
The biggest issue is that you need to remember that initially your integer "a" is set to "0". This always catches your first if condition meaning that a is never set!
You are not updating the value of a, so it's 0 all the time.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
boolean loop = true;
while (loop) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext()) {
System.out.println("Oops! ");
input.nextLine();
} else {
a = input.nextInt();
if (a <= 3 && a >= 1)
loop = false;
else {
System.out.println("Oops! ");
input.nextLine();
}
}
}
input.close();
System.out.println("a = " + a);
}
}
EDIT:
I want to get input from stdin in the for of
3
10 20 30
the first number is the amount of numbers in the second line. Here's what I got, but it is stuck in the while loop... so I believe. I ran in debug mode and the array is not getting assign any values...
import java.util.*;
public class Tester {
public static void main (String[] args)
{
int testNum;
int[] testCases;
Scanner in = new Scanner(System.in);
System.out.println("Enter test number");
testNum = in.nextInt();
testCases = new int[testNum];
int i = 0;
while(in.hasNextInt()) {
testCases[i] = in.nextInt();
i++;
}
for(Integer t : testCases) {
if(t != null)
System.out.println(t.toString());
}
}
}
It has to do with the condition.
in.hasNextInt()
It lets you keep looping and then after three iterations 'i' value equals to 4 and testCases[4] throws ArrayIndexOutOfBoundException.
The Solution to do this could be
for (int i = 0; i < testNum; i++) {
*//do something*
}
Update your while to read only desired numbers as below:
while(i < testNum && in.hasNextInt()) {
The additional condition && i < testNum added in while will stop reading the numbers once your have read the numbers equivalent to your array size, otherwise it will go indefininte and you will get ArrayIndexOutOfBoundException when number array testCases is full i.e. you are done reading with testNum numbers.