java program for printing the two largest numbers a user inputs - while-loop

Whenever I run my compiled code, it displays the largest number but it doesn't display the second largest number correctly. Here is my code:
package twoLargestNumbers;
import java.util.Scanner;
//find two largest numbers
public class twoLargestNumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int num;
int counter=0;
int largest=0;//largest
int second=0;//second largest
System.out.println("Enter number:");
num=input.nextInt();
while(counter<5){
num=input.nextInt();
if(num>largest){
second=largest;//store largest to second largest
largest=num;//store largest to inputted number
}
else{
if(num>second)
second=num;//store second number to inputed number
}
counter=counter+1;
}
System.out.println("largest number is "+largest);
System.out.println("and second largest number is "+second);
}
}
What am I doing wrong? I reread and read this code and I cannot find out what the error is.

Remove the num=input.nextInt() before the while loop starts.
The initial input is being called and then straight away after the "first" input in the while method is called.
A couple of other tips, usually for a defined length of loop (in this case, 5) you would use a for loop to show your intent a bit more.
Also you can increment counter doing: counter++; or counter += 1;
Assuming the intent of your program is to ask for 5 numbers of input and then display the largest two, that should all help. Hope it did.

Also I don't think this block of code is needed, the second largest is already being stored in the first if statement.
else{
if(num>second)
second=num;//store second number to inputed number
}

Related

How does this duplicate checker loop work?

Hi I hope someone can help. I'm trying to understand the following java program that loops until it finds two integers from the user that are the same:
import java.util.Scanner;
public class whileloop {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int previous, input = in.nextInt();
while(in.hasNextInt()){
previous = input;
input = in.nextInt();
if (input == previous){
System.out.println("Duplicate input found!");
}
}
}
So from my understanding, the program will call the user to provide two integers from .nextInt(), store those values in the variables named "previous" and "input", and then will proceed to the while loop. What I don't understand is what occurs right before the if condition. What is the point of having "previous" equate to "input" and then asking input for another integer? If I remove previous = input and input = in.nextInt() I get an error that says that the variables have not been initialized.... which confuses me since I thought that the variables "previous" and "input" got initialized when the program asked the user for the two integers? Evidently I'm quite confused, and would really appreciate help.

How to repeat main method in java

My question is simple but the answer eludes me. I have looked up and down for this little bit of info and can't find it.
It's simple, I have a program with println text that I want to have repeated just once. what is the line of code to do this in the simplest way.
There are two lines of System.out.println that make up the static void main and I want it to just repeat itself just once so that there is double without me actually typing in a System.out.println() to put a space between the first set and then just typing in an exact copy of the first set of two lines.
Example:
System.out.println("Hello World!");
System.out.println("I am Klinton");
System.out.println()
System.out.println("Hello World!");
System.out.println("I am Klinton");
I want to shrink this to just the first two lines and have the program repeat it once to achieve the same result.
Use a for loop.
for(int i=1; i<=10; i++)
{
System.out.println("Hello World!");
System.out.println("I am Klinton");
System.out.println()
}
This will loop ten times. It starts at one with initializing a new variable i to 1, sets the termination to when I is no longer less than or equal to 10, and the increment to 1, so i will increase by 1 each time the loop runs..

Testing Phone Number using Selenium

I have given a task by my Project Manager and he has asked me to "Test a phone number using selenium". He has asked me to cover all the test cases possible to test a phone number
The test cases are given below:
1. Phone number must contain digits only.
2. Phone number length should be 10.
3. It should not contain alphabets.
4. It should not contain symbols.
5. It should not contain the combination of alphanumerics.
6. Phone number should not start with 0.
Please help me in testing all these test cases in automation.
i conform with the comments above, in agreement; i also don't condone answering questions like this, but something like this is so easy in selenium that it won't take me long to write.
this is all pseudo-code in java.
void testCase1() {
// digits only
setPhoneNumber("+12345a5434")
clickSubmit()
validateErrorMessage("ERROR: Your phone number contains letters")
}
void testCase2() {
// length should be ten
setPhoneNumber("+123456789")
clickSubmit()
validateErrorMessage("ERROR: Phone numbers should be ten-digits long")
}
void testCase3() {
testCase1() // this test case is the exact same as #1
}
void testCase4() {
setPhoneNumber("+|123456t890")
clickSubmit()
validateErrorMessage("ERROR: Your phone number contains invalid characters")
}
void testCase5() {
testCase1()
testCase3()
testCase4()
// already covered in both these cases
}
void testCase6() {
setPhoneNumber("+0123456789")
clickSubmit()
validateErrorMessage("ERROR: your phone number starts with 0")
}
void validTestCase() {
setPhoneNumber("+1234567890")
clickSubmit()
validateErrorMessage(null)
validateElementPresent(".success")
}
mind you this is al pseudo-code. you don't specify which language you are using, nor any html. I don't condone answering this type of question - but your task is so easy that i figured i'd write it out in pseudo-code.

remove objects from arraylist is doing strange things

In the code below, i want the balls to change from ArrayList ballList to another ArrayList oldBalls as soon as their age turns higher than a threshold value.
This code should be very simple but i can't figure out why when the age is same as the threshold (not larger) they disappear and then they come back 2 frames later.
I have checked related questions using iterators for ArrayLists in java but i think there should be a way to do this in processing without java.
Also i cant seem to post any question on the processing forum even though i can sign in, no idea why...
I have reduced the code to the minimum able to reproduce the error.
ArrayList <Ball> ballList;
ArrayList <Ball> oldBalls;
int threshold=4;
PFont font;
void setup(){
size(400,400);
frameRate(0.5);
font=createFont("Georgia", 18);
textFont(font);
textAlign(CENTER, CENTER);
ballList=new ArrayList<Ball>();
oldBalls=new ArrayList<Ball>();
noFill();
strokeWeight(2);
}
void draw(){
background(0);
Ball b=new Ball(new PVector(10, random(height/10,9*height/10)),new PVector(10,0),0);
ballList.add(b);
stroke(0,0,200);
for(int i=0;i<oldBalls.size();i++){
Ball bb=oldBalls.get(i);
bb.update();
bb.render();
text(bb.age,bb.pos.x,bb.pos.y);
}
stroke(200,0,0);
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
}
class Ball{
PVector pos;
PVector vel;
int age;
Ball(PVector _pos, PVector _vel, int _age){
pos=_pos;
vel=_vel;
age=_age;
}
void migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
}
}
void update(){
pos.add(vel);
age+=1;
}
void render(){
ellipse(pos.x,pos.y,24,24);
}
}
Note how balls labelled with age=threshold suddenly disappear...
i guess the problem is here:
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
//add this
if(bb.migrate())
i--;
text(bb.age,bb.pos.x,bb.pos.y);
}
and
boolean migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
//and this
return true;
}
return false;
}
migrate() will remove the object from the ballList and reduce it's size by 1.
What it looks like is happening here is because you're altering the List's whilst iterating through them. Consider this for loop you have here
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
Say ballList has 2 balls in it both age 3, the first loops gets ball[0] and then removes it from the list, i will increment and the loop will immediately exit because ballList.size() is now 1. So it's not the ball which gets to age 4 that vanishes but the subsequent one.

How can I use a value of a variable that is assigned to the variable in a previous if statement?

This is code in Android Studio. I created Buttons start, higher and lower. The goal is to get the button "start" to show a random number guess. This initial random number has to be used when the buttons "higher" or "lower" are being pressed. But if I do it in the way below, it gives me the error that x is not initialized. I know this is because I assigned a value to x in another if-loop but I don't know how to fix it. Can anyone help me?
#Override
public void onClick(View v) {
int x;
int lowBound;
int highBound;
if (v==start) {
x=(int) Math.random()*1000;
myTextView2.append("Random guess is "+String.valueOf(x));
}
if (v==higher) {
lowBound=x;
x= (int) (lowBound+Math.random()*(1000-lowBound));
myTextView2.append(" New guess is "+String.valueOf(x));
}
if (v==lower) {
highBound=x;
x=(int) (highBound-Math.random()*(1000-highBound));
myTextView2.append(" New guess is "+ String.valueOf(x));
}
}
If v is equal to anything other than start, the variable will assigned to lowerBound or upperBound uninitialized.
Unless I'm reading it wrong, this actually shows a flaw in your logic:
Every time onClick is called, x will either be reset if v == start, or will be used uninitiated.
x should declared outside of the method since you need it to "survive" between onClicks.