I'm a beginner programmer Java:
I want to get 10 values from user and put if statement, if some one enters grade value above 100, it may get "Enter right value < 100"
But i don't want to use any array etc.
When i use the following code, it shows the error message but for 1 wrong value, it calculates other 09 values and don't repeat the wrong value, given if statement skips the wrong
int i, number, total=0;
Scanner sc = new Scanner(System.in);
for (i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100);;
{total = total + number;}
}
int number, total=0;
int i = 1;
Scanner sc = new Scanner(System.in);
while (i<=10)
{
System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
i++;
}else{
System.out.println("invalid value");
}
}
This will work, using a while loop
You just had few typo errors in your code also , to make the for loop more simple you don't need to define i at top just define the i when you need to use the for loop . And its avoid overwrite outside of the for loop .
To make using for loop more professional also considering that maybe sometimes you need to use it for arrays its better to always start the loop with i=0 thats the better practice.
After if(condition) don't need to put any ;
int number, total=0;
Scanner sc = new Scanner(System.in);
for (int i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
}
}
Related
The below while loop runs an extra time. I am trying to perform a user input that accepts 10 valid numbers from the user and prints their sum. However, the while loop executes an extra time and asks for the 11th input.
import java.util.Scanner;
class userInput{
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
}
In addition to those great comments, you should probably only increment "i" if you get a VALID input:
while(i <= 10) {
System.out.print("Enter number " + "#" +i + ": ");
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
i++;
}else{
System.out.println("Invalid Input");
sc.next();
}
}
Note that when you have a bad input you need to get rid of it with "sc.next()".
First - make sure you're formatted correctly.
(I've indented your loops, moved your output into the main class, fixed up some curly brackets/loop endings).
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}
else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
Alright - so running the code, I've found there are the correct amount of times asked, but the input prompt is displaying the wrong number with the first input prompt starting on 2, the last one on 11.
The reason for this is the i++ runs before asking for an input, thus it counts up before outputting.
This can easily be fixed by moving said i++ to just underneath the else clause - as follows:
else{
System.out.println("Invalid Input");
}
i++
}
the main problem here is that you're increasing the variable at the start of your while loop. If that's what you're looking for then that's fine, but if you want to stop the loop when it hits 10 you'll need to have it like while(i < 10) if the i++ were at the end of the loop, then you could do while(i <= 10)
Ex:
i = 0;
while(i < 10){
i++;
//code here
}
this will make the code that uses i use the values between 1 and 10. using <= will use the values between 1 and 11.
another example:
i = 0;
while(i < 10){
//code here
i++;
}
this will make the code that uses i use the values between 0 and 9. using <= will use the values between 0 and 10.
another way people do an incremental loop is doing a for loop rather than a while loop
this would look like:
for(int i = 0; i < 10; i++){
//code here
}
this also allows you to create a variable that will only be inside the loop, so rather than making it at the beginning of the method or before the loop, you could make it inside the for loop. This is not good if the variable is used elsewhere though.
How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}
I'm new with java and i have to write a code that asks the user two numbers an interval. Then the user must introduce n numbers and the program must return how many numbers belong to that interval.
I've tried to do this and this is what i have:
import java.util.*;
public class NumsInter {
public static void main(String[] args) {
Scanner sc;
int a,b,nums,count;
sc = new Scanner (System.in);
System.out.print ("Write two numbers a and b(a<=b)(interval): ");
a=sc.nextInt();
b=sc.nextInt();
count=0;
System.out.println("write a number: ");
while(sc.hasNextInt()){
nums=sc.nextInt();
if (a<=nums && nums>=b){
count= count + 1;
} else {
count= count;
}
}
System.out.println(count +" numbers are included in ("+a+","+b+")");
}
}
Example: If the user writes 2 and 6, and then 4,4,3,1 the output should be 3.
As I am a newbie i don't know how can i do this the good way, can someoen help?
PD: How can i break the loop so i can get the output?
Thank You!
Try something like this
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter the numbers you want to test, enter 'stop' to stop");
boolean userInput = true;
while(input.hasNextInt() && userInput){
if(input.hasNext("stop")){userInput = false;}
numbers.add(input.nextInt());
}
Where you have a loop that checks if there is a next int while at the same time checking to see if the user is done or not.
And them something like this to print your answer
for(int i =0; i < numbers.size(); i++){
testNum = numbers.get(i);
if(testNum > lowerLimit && testNum < upperLimit){
count++;
}
}
System.out.println(count + " valid numbers have been entered!");
take an int [] no_between_max&min after take the input from user and store in this array. after that take a for loop and compare the value of array with max and min ant increase the count variable.
int noOfItem=sc.nextInt();
int [] no_between_max_min = new int[noOfItem];
for(int i=0;i<noOfItem;i++){
no_between_max_min[i]=sc.nextInt();
}
for(int i=0;i<no_between_max_min.length;i++){
if(no_between_max_min[i]>=a&&no_between_max_min[i]<=b){
count++;
}
}
I was wondering how to load up an array (with user input) using a while loop. The code below prints a 0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int n = 0;
int[] myArray = new int[10];
System.out.printf("enter a value>>");
while (scan.nextInt() > 0) {
for (i = 0; i > 0; i++) {
myArray[i] = scan.nextInt();
}
System.out.printf("enter a value>>");
}
System.out.printf("array index 2 is %d", myArray[2]);
}
There are multiple things wrong with your code:
First of all
while(scan.nextInt() > 0){
Scanner.nextInt() returns an int from your standard input so you actually have to pick up that value. You are checking here what the user typed but then not using it at all and storing the next thing that the user types by saying:
myArray[i] = scan.nextInt();
You don't really need the outer while loop, just use the for loop, its enough.
However, your for loop is off as well:
for(i = 0; i > 0; i++){
It starts at i equal to 0 and runs while i is greater than 0. This means it will never actually run the code within the loop because 0 is never greater than 0. And if it did run (you started it at some number < 0), you would end up in an infinite loop because your condition i > 0 is always true for positive numbers.
Change the loop to:
for(i = 0; i < 10; i++){
Now, your loop could look like:
for(i = 0; i < 10; i++){ // do this 10 times
System.out.printf("enter a value>>"); // print a statement to the screen
myArray[i] = scan.nextInt(); // read an integer from the user and store it into the array
}
one other way to do it
Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
System.out.println("Enter a value to store in list");
list.add(scan.nextInt());
System.out.println("Enter more value y to continue or enter n to exit");
Scanner s = new Scanner(System.in);
String ans = s.nextLine();
if(ans.equals("n"))
break;
}
System.out.println(list);
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int[] arr=new int[4];
int i;
for(i=0;i<4;i++)
{
System.out.println("Enter the number: ");
arr[i]=input.nextInt();
}
for(i=0;i<4;i++)
{
System.out.println(arr[i]);
}
}
Hope this code helps.
I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.
for example
enter up to 5 numbers : 3 4 5
I'm going to add them in the integer sum and then later divide them by counter
to get the average of these numbers.
However, my loop does not seem to end. What's wrong with my code?
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt());{
counter++;
sum += scan.nextInt();
}
System.out.println(counter);
System.out.println(sum);
You put a ; between while and {, so it loops. Remove it.
Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.
What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:
String input = scan.nextLine();
for(String part : input.split(" "))
sum += Integer.parseInt(part);
Serge Seredenko's answer is also correct, however, but that's another problem.
Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt()){
counter++;
sum += scan.nextInt();
if(counter >=5)
break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();
First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete.
Second, when you use your code, you need CTRL + Z to end up your input. By adding
if(counter >=5)
break;
your input will end up when you input 5 numbers.
If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.
I would suggest you to read line then split by space and iterate over string array. Check out code snippet.
package com.gaurangjadia.code.java;
import java.util.Scanner;
public class SO19204901 {
public static void main(String[] args) {
int counter = 0,
sum = 0;
System.out.println("enter up to 5 numbers");
Scanner scan = new Scanner(System.in);
String strInput = scan.nextLine();
String[] arrayNumbers = strInput.split(" ");
for (int i = 0; i < arrayNumbers.length; i++) {
int n;
try {
n = Integer.parseInt(arrayNumbers[i]);
}
catch (NumberFormatException e) {
n = 0;
}
sum = sum + n;
counter++;
}
System.out.println(sum);
}
}
DataInputStream in = new DataInputStream(System.in);
String[]label = {"quiz #","Total","Average"};
int counter = 0;
int theSum = 0;
System.out.print("Enter up to 5 number : ");
String[]tempNum = in.readLine().trim().split("\\s+");
System.out.println();
while (counter <= tempNum.length)
{
if ( counter == tempNum.length)
{
System.out.printf("%10s %12s\n",label[1],label[2]);
counter = 0;
break;
} else {
System.out.printf("%10s",label[0] + (counter+1) );
}
counter++;
}
while(counter <= tempNum.length)
{
if ( counter == tempNum.length)
{System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
} else
{System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
theSum += Integer.valueOf(tempNum[counter]);
}
counter++;
}