简体   繁体   中英

Read in positive numbers from the user until they enter a negative number. Print out the largest positive number that was read. Java

So like, I'm new to Java and whatnot and for the most part, it's been pretty alright. However, I'm kind of stumped with this one problem. So basically I have to write a program in a conditional loop where it reads user input: You enter positive numbers until you enter a negative number, where the program then prints out the largest positive number in that.

I'm building this off of another program where the program read in positive numbers until you entered a negative one in which the program would then print out the sum.

I don't really know what to do past this, can anyone help?

Here's my code

import java.util.Scanner;

class Main {

  public static void main(String[] args) {

    int counter=0;
    Scanner sc=new Scanner(System.in);
    
    int number=sc.nextInt();
    
    while(number>=0){
      counter=counter+number;
      number=sc.nextInt();
    }
    System.out.println(counter);
    
  }
}

the quickest way to request user input off the bat, just like that, is the prompt function.. welcome to javascript :}

 var n=0; var arr=[]; while(n!=-1){ var m=parseInt(prompt("Enter a number\\nEnter value -1 to end entries")); //parseInt attempts to turn the data input into a number and prompt returns what the user inputs if(!isNaN(m)){//i'm asking if m is a number if(m!=-1){arr.push(m);}//this ensures that when -1 is inputted, it isn't a part of the values sorted through n=m; } } alert(arr.sort().reverse()); //sort sorts from highest to lowest, reversing such would do the exact opposite

You were close ...

Create a variable to hold the largest value, then on each loop iteration check if the number entered is greater than the largest value. If so, update it.

import java.util.Scanner;
  
class Main {

        public static void main(String[] args) {

                int largest=0;
                Scanner sc=new Scanner(System.in);

                int number=sc.nextInt();
                while(number>=0){
                        if (number > largest) {
                                largest = number;
                        }
                        number=sc.nextInt();
                }
                System.out.println(largest);
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM