So I'm trying to read all the input from one line, using scanner, then take the values and find the second largest. I would use an array BUT I am not allowed. You are supposed to enter 10 integers, hit enter and evaluate them.
Something like this:
10 20 30 40 50 60 70 80 90 100 ENTER
Second highest number is: 90
I can't manage to solve it at all. It should be easy but I have no idea.
public class SecondLargest {
public static void main(String[] args) {
{
int largest = 0;
int secondLargest = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter integers: ");
int numbers = sc.nextInt();
largest = numbers;
while (sc.hasNextInt()) {
if (numbers > largest) {
secondLargest = largest;
largest = numbers;
} else if (numbers > secondLargest) {
secondLargest = numbers;
}
}
System.out.println("Second largest number is: " + secondLargest);
sc.close();
}
}
Start with assigning the first scanned integer to largest and secondLargest variables and then process the remaining nine integers in a loop as follows:
num = sc.nextInt();
if (num > largest) {
secondLargest = largest;
largest = num;
}
Demo:
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 integers separated by single spaces: ");
// Scan the first integer and assign it to largest and secondLargest
int num = sc.nextInt();
int largest = num;
int secondLargest = largest;
// Input 9 more integers
for (int i = 1; i < 10; i++) {
num = sc.nextInt();
if (num > largest) {
secondLargest = largest;
largest = num;
}
}
System.out.println("The second largest number is: " + secondLargest);
}
}
A sample run:
Enter 10 integers separated by single spaces: 10 23 4 12 80 45 78 90 105 7
The second largest number is: 90
Note: This is just a sample program assuming that the input is in the correct format. I leave it to you to work on how to deal with the wrong input. It will be a good exercise for you.
/*
**In this code I've used BufferedReader class which is faster than Scanner
Class as well as have large buffer of 8KB while Scanner has only 1KB.**
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Second_Highest {
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] s=br.readLine().split(" ");
int a[]=new int[10];
int max=Integer.parseInt(s[0]);
for(int i=0;i<10;i++)
{
a[i]=Integer.parseInt(s[i]);
if(a[i]>max)
{
max=a[i];
}
}
int secondmax=Integer.parseInt(s[0]);
for(int i=0;i<10;i++)
{
if(a[i]>secondmax && a[i]<max)
{
secondmax=a[i];
}
}
System.out.print(secondmax);
}
}
To read single line input, You can do this simply by eating the (\n) which is new line in Java.
Input : 1 2 3
\\Create the object of Scanner Class
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
// this will eat the new line and move forward for other inputs.
sc.nextLine()
To read in a loop or to store at 2D array.
Input :
1 2 3
3 4 5
6 7 8
//... do the above declaration of array
for ( int i = 0; i < n; i++){
for( int j = 0; j < m; j++){
arr[i][j] = sc.nextInt()
}
sc.nextLine(); // you need to eat the \n here.
}
This will work perfectly.
Now you should be able to get the input easily in a single line.
Below snippet can be used to take multiple Integer Input on same line.
Scanner sc= new Scanner(System.in); // Declare and Initialize Scanner
while(sc.hasNext()) // While the input has data execute
System.out.println(sc.nextInt()); // nextInt() method is used to take Integer data
For Multiple String input on same line separated by white space or a comma,
we can use the following snippet
Scanner sc = new Scanner(System.in).useDelimiter("[,\\s+]");
import java.util.*;
public class m1{
public static void main(String args[]){
Scannerscan = new Scanner(System.in);
Stringnum = scan.nextLine();
String[] strs = num.split("\\s+");
int[] arrs = new int[strs.length];
for(inti=0;i<strs.length;i++)
{
String stringnum = strs[i];
arrs[i] = Integer.parseInt(stringnum);
if(arrs[i]%2==0){
System.out.print(" ");
}
else{
System.out.print(arrs[i]);
}
}
scan.close();
}
}
Related
here is the question:
Write an application that reads five numbers between 1 and 30. For
each number that’s read, your program should display the same number of adjacent asterisks. For
example, if your program reads the number 7, it should display *******. Display the bars of asterisks
after you read all five numbers.
here is my code:
package Assignment.Q034;
import java.util.Scanner;
public class Q034_trial
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int num;
num = 1-30;
for (int i = 0; i < 5; i++)// system asks for no more than 5 numbers
{
System.out.printf("Enter a number: ");
num = input.nextInt();
}
for (int j = 0; j < num; j++)
{
System.out.printf("*");
}
System.out.println();
}
}
program IDe used: Apache Netbeans IDE 12.4
the code does not sure any error but when I run and debug it, the output shows like this:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
*****
but the output I need is:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
*
**
***
****
*****
I am new to java programming. please help me t find the solution.
You can try to break them down individually and try to incorporate an approach like this or use these ideas for your project:
import java.util.Scanner;
public class Array {
public static void main(String[] args){
Array asteriskGenerator = new Array();
int nb[]=new int[5];
Scanner input = new Scanner (System.in);
for(int i=0;i<5;i++)
{
System.out.print("Please, Enter a number between 1 - 30 ");
nb[i]=input.nextInt();
}
input.close();
asteriskGenerator.asteriskGenerator(nb);
}
void asteriskGenerator(int nb[])
{
for(int i = 0; i < nb.length; i++)
{
for(int j=1;j<=nb[i];j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
I hope this helps in what you are trying to accomplish!
You need to read in five integers, and then when you are done, do something with them. This means you need some way to store all five integers.
The obvious solution is to store them in an array.
public class Q034_trial
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int[] nums = new int[5];
for (int i = 0; i < 5; i++)
{
System.out.printf("Enter a number: ");
int num = input.nextInt();
nums[i] = num;
}
}
}
Having done that you merely need to iterate over each number in the array to print the correct number of asterisks.
public class Q034_trial
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int[] nums = new int[5];
for (int i = 0; i < 5; i++)
{
System.out.printf("Enter a number: ");
int num = input.nextInt();
nums[i] = num;
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < nums[i]; j++)
System.out.printf("*");
System.out.println();
}
}
}
I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]
does anyone know how to set a user input for an array, I cant find the command anywhere. my array 'grades' have 20 locations. im not so sure about 'grades.length' function but I think it prompts 20 times. BUT I added a while statement to override BUT ITS TOTALLY IGNORING THE FOR STATEMENT. if I could set user input for array I could get rid of the while statement...
program has to accept grade for number of students the user inputs btw..
import java.util.Scanner;
public class gradesaverage {
public static void main(String[] args) {
int [] grades = new int [20];
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
for ( i = 1; i <= grades.length; ++i)
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
while(i <= numStudents );
}
}
Not sure what you mean, but assuming all input is correct,
int [] grades = new int [numStudents ];
Should work if you move this line after declaration and assignment of numStudents. There is no problem in java with variable length arrays.
Also note - your iterator i starts from 1, while in java arrays start from 0.
public static void main(String[] args) {
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
int [] grades = new int [numStudents]; //the size we wanted
for ( i = 0; i < grades.length; ++i) //starting from 0, not 1.
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
//print the array - for checking out everyting is ok
System.out.println(Arrays.toString(grades));
}
import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
output:
Please enter a value:
789
7
8
9
How do I reverse the output? For example, when I enter the number 123, it would display 321 with each digit on a new line.
If the user is inputting values in base 10, you could instead use the modulo operator along with integer division to grab the rightmost values successively in a while loop as so:
import java.util.Scanner;
public class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int quotient = value;
int remainder = 0;
while(quotient != 0){
remainder = quotient%10;
quotient = quotient/10;
System.out.print(remainder);
}
}
}
This might be a better method that attempting to convert the int to a string and then looping through the string character by character.
Loop you printing for loop in the reverse direction:
import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = digit.length()-1; i >= 0; i--) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Edit: No reason to reverse the string itself, ie. using a Stringbuilder like the other answers say. This just adds to the runtime.
import java.util.*;
public class Francis {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Simply reverse the string before looping through it
digit = new StringBuilder(digit).reverse().toString();