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();
}
}
}
Related
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();
}
}
I'm making a simple program in java .. So that as I give input:
2 2 4 5
And output will be:
2 2 4 5
Whatever I give input it prints the same output.
But before it must ask to input the number of elements first.
EDITED MY QUESTION
Okay, so I tried this
package com.logical01;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args){
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter your number elements: ");
int n_Elements=in.nextInt();
System.out.println("Enter your number now: ");
for(int i=0; i<=n_Elements; i++){
array[i]=in.nextInt();
}
int i = 0;
System.out.println(array[i]);
}
}
Output
Enter your number elements:
5
Enter your number now:
6
2
1
3
5
6
and it prints..
6
Move this line:
System.out.println(array[i]);
into the for loop just above it.
The reason this program compiles at all is because you have declared int i; at the top of the loop.
If instead you moved the declaration inside the declaration of the for loop, then it wouldn't compile when you try and do the wrong thing.
for(int i=0; i<=n_Elements; i++) {
This is an example of defensive coding, which protects you against mistakes that might be made elsewhere.
This is what you want :
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args){
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter your number elements: ");
int n_Elements=in.nextInt();
System.out.println("Enter your number now: ");
for(int i=0; i<n_Elements; i++){
array[i]=in.nextInt();
}
for(int i = 0; i<n_Elements; i++){ //you need to loop to get all the values in an array
System.out.print(array[i]);
}
}
just think about your last line.
What is the value of i?
What is array[0];
What is array[1];
..
What are you printing really - and what do you want to print?
after initializing your array (int[] array = new int[100]), every entry is 0.
try this for debugging and understanding:
public static void main(String[] args) {
int[] array = new int[100];
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter your number elements: ");
int n_Elements = in.nextInt();
System.out.println("Enter your number now: ");
for (i = 0; i < n_Elements; i++) {
array[i] = in.nextInt();
System.out.println("input: array[" + i + "]= " + array[i]);
}
System.out.println("printing: i=" + i + " and array[" + i + "]="
+ array[i]);
}
Like c++ we can use this.
a[5];
copy(istream_iterator<int>(cin),istream_iterator<int>(),a);
Is there some simple way to get array from input in Java?
You can use the simple way like it
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
}
//print the array
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
How about simply using System.console().readLine("Array (use , as separator)? ").split(",")? Then convert it to an int[] array (there are tons of util libraries to do that).
Really having issues with this program I'm making. I've searched this site and a few others, although have yet to find a solution. It may look like I'm just soliciting help but I truly am stuck. I am to make a program that reads in 5 numbers from the user and average those numbers. My extent of knowledge of Java is the Scanner class and for loops, yet haven't used while loops yet. Here is the very poorly written code:
public class Average5
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
num = sc.nextInt();
}
I honestly have no clue what to do. More or less self taught.
public class Average5 {
public static void main(String args[]) {
int numlenngth = 5;
double total = 0;
Scanner sc = new Scanner(System.in);
for (int num1 = 0; num1 < numlenngth; num1++) {
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : " + (total / numlenngth));
}
}
output >>
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 2
Average : 1.2
For calculating exact average, you need to take double(sum) instead of int and add(sum) everytime with the user value.
public class Average5
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to enter for calculating average: ");
int totalCount = sc.nextInt();
double sum=0;
for(int i= 0; i<totalCount; i++)
{
System.out.print("Please enter a number: ");
sum += sc.nextDouble();
}
System.out.println("Average of number is"+(sum/totalCount));
}
This is almost the same as the others posted, but it is limited to entering only 5 numbers and it takes care of possibly resulting floating number in the final division:
import java.util.Scanner;
public class Average5 {
private static final int TOTAL = 5;
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.format("You have to enter %d numbers now.\n", TOTAL);
for (int cnt = 1; cnt <= TOTAL; cnt++) {
System.out.format("Please enter number %d of %d: ", cnt, TOTAL);
sum += scanner.nextInt();
}
System.out.format("The average is %f.\n", sum / TOTAL);
scanner.close();
}
}
Here you can use the array to store the numbers:
public class Average5 {
private static final int MAX = 5;
public static void main(String[] args) {
int[] numbers = new int[MAX];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < MAX; i++) {
System.out.println("Please type the number");
numbers[i] = sc.nextInt();
}
float average = getAverage(numbers);
System.out.println("The average of the five numbers: " + average);
}
public static float getAverage(int[] arg0) {
int sum = 0;
float Ret = 0.0f;
if(arg0 != null) {
for(int i = 0; i < MAX; i++) {
sum += arg0[i];
Ret = sum / MAX;
}
return Ret;
}
}
This is not the only way to slove this problem.
int num = 0;
float total = 0f;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : "+(total/num));
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));
}