Scanner skips input in a for loop [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
So I have this code:
public class Subjects {
String name;
int period;
char grade;
public void period()
{
System.out.println("I have " + this.name + " during period " + this.period + ".");
}
public void study()
{
if (this.grade == 'B')
{
System.out.println("I study for " + this.name + ", so I get a B!");
}
else if (this.grade == 'A')
{
System.out.println("I study for " + this.name + ", so I get an A!");
}
else
{
System.out.println("I don't study for " + this.name + ", so I get a " + this.grade +". :(");
}
}
}
And this test class:
import java.util.Scanner;
public class SubjectsTest {
public static void main (String [] args)
{
Scanner kboard = new Scanner(System.in);
Subjects[] classes;
System.out.print ("How many classes do you have? ");
int x = kboard.nextInt();
int y;
classes = new Subjects[x];
for (int b = 0; b < x; b++)
{
classes[b] = new Subjects();
}
for (int a = 0; a < x; a++)
{
y = a + 1;
System.out.println("Period " + y );
System.out.println ("Enter the subject name: ");
classes[a].name = kboard.nextLine();
System.out.println ("Enter your class period: ");
classes[a].period = kboard.nextInt();
System.out.println ("Enter your grade in the class: ");
classes[a].grade = kboard.next().charAt(0);
}
for (int i = 0; i < x; i++)
{
classes[i].period();
classes[i].study();
}
}
}
What should happen is the user puts in the number of classes they have (e.g. 8) and then puts in the name, period and their grade for each one. Then at the end, it prints 2 statements for each class.
However, when I run the program (in Eclipse), after it asks How many classes do you have? and the user answers, the system prints out the next two questions without waiting for an answer to the first. My error message looks like this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at SubjectsTest.main(SubjectsTest.java:27)
Why does it do this? How can I fix it? I'm new to Java, so any help would be much appreciated!

You should put a kboard.nextLine(); after your kboard.nextInt(); call that gets the number of classes.
This will read in the rest of the kboard.nextInt(); line and allow reading in your subject name to work properly. Currently, your kboard.nextLine(); to read in the subject name is reading in the remainder of your input for the number of classes. So when you're trying to read in the subject, it's actually waiting for the int for period and giving you that exception.
EDIT: Sorry for all the edits, the accepted answer for this question might make a little more sense: Using scanner.nextLine()

Related

Hi I'm beginner in java and started coding recently here's my program it showing an error of ArryIndexOutOfBound [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
// It's program of cars and it's colours
import java.util.Scanner;
class Details
{
String name;
String colour;
public Details( String name, String colour)
{
this.name=name;
this.colour=colour;
}
}
public class Car {
public static void main(String[] args) {
int i, num;
Scanner sc=new Scanner(System.in);
System.out.println("enter the size");
num=sc.nextInt();
Details cars[]=new Details[num];
System.out.println("enter name and colour");
for( i=0;i<cars.length;i++);
{
cars[i].name=sc.next();
cars[i].colour=sc.next();
System.out.println("name : "+cars[i].name+" \n colour :"+cars[i].colour);
}
sc.close();
}
}
You've left extra semicolon on the line with a declaration of for loop.
This is a valid syntax and if you break the code into logical blocks you'll get the following:
for (i = 0; i < cars.length; i++);
{
cars[i].name = sc.next();
cars[i].colour = sc.next();
System.out.println("name : " + cars[i].name + " \n colour :" + cars[i].colour);
}
Here, you have for loop which does nothing until i is equal to 2. This loop is followed by a block, which performs some code with i already being equal to 2!

Method not being called properly?! Calorie App [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner (System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake,BMR);
//this is what you actually ate
actualCalories(actualIntake,BMR);
//gym with protein
gym (30,40,50,100, actualIntake);
}
//testing method
testingMeth(actualIntake);
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR){
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0 ){
calorieDifference = Math.abs (BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0){
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories (int actualIntake, int BMR ) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR ) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR ) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin." );
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym (int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50 ) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50 ) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth (int actualIntake) {
System.out.println(actualIntake);
}
}
//Take calories in then calculate BMR and compare, return value
So I am currently learning java, just learning and making random calorie deficit and BMR program. I created a new method called:
public static int testingMeth(actualIntake) {
System.out.println(actualIntake);
}
The issue is when i try to call the method after the gym method, it creates an error.
gym (30,40,50,100, actualIntake);
}
testingMeth(actualIntake);
If i was to delete the gym method from the main method, all my other methods has errors. I do not necessarily need a solution for this program but rather why am i receiving these errors? Just want to learn and improve! Thanks.
In other words, I can call the testingMeth before the Gym method and it works fine, but why not after the gym method? and if i get rid of the gym method, multiple errors occur amongst the other methods within the program?
If you see below code, i am able to run both method in any sequence and it's working fine as well.
You need to go through with basics of method declaration and method call.
It will help you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner(System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake, BMR);
//this is what you actually ate
testingMeth(actualIntake);
actualCalories(actualIntake, BMR);
//gym with protein
gym(30, 40, 50, 100, actualIntake);
}
//testing method
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR) {
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0) {
calorieDifference = Math.abs(BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0) {
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories(int actualIntake, int BMR) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin.");
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym(int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth(int actualIntake) {
System.out.println(actualIntake);
}
}
You need to understand for every opening braces of class/method/switch-case/or condition must have closing braces.
In your case you are try to call some method after closing braces of class, so those elements are not part of your class and that's why it's throwing an error.

Java skips the while statement and goes straight to the end [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
This is my first semester doing computer programming and our professor totally bailed on us mid class. But I managed to nearly complete the classwork but for some reason my while statement is getting skipped.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
//this is where it skips from here*********
while (response == "y")
{
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
if (response =="y")
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
}
}
while (response == "n");
//to here*********************************************
System.out.println("Final Tally");
System.out.println("Polly received:\t " + totalPolly + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + totalErnest + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
Strings effectively point to values in Java, and aren't values themselves. Try using
while (response.equals("y"))
instead of
while (response == "y")
In the former case you're telling the runtime to actually compare the values. The latter case is telling the runtime to compare the pointers, which may not actually match.

Using a scanner input to define the number of scanner inputs required

I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.

Not getting the correct output from this if statement in for loop? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm making a vocabulary practice program using arrays (I know, not Lists, but I need array practice). However, everything goes well until the program evaluates if the typed answer (when the program quizzes the user) is the actual definition. I always get the answer wrong, and I don't know why. Here's the whole program:
import java.util.Scanner;
public class organ {
public Scanner input = new Scanner(System.in);
public String language;
public int temp;
public static void main(String[] args){
organ organObject = new organ();
organObject.greeting();
organObject.ending();
}
public void greeting(){
System.out.println("Hello! Do you want to practice vocabulary in English or Spanish?");
//Need to fix this grammar.
System.out.println("!Hola! ?Quieres practicar el vocabulario en ingles o espanol?");
language = input.nextLine();
checkLanguage(language);
}
public void checkLanguage(String answer){
if (language.equals("English") || language.equals("ingles")){
englishTree();
}
else{
spanishTree();
}
}
public void englishTree(){
System.out.println("How many words do you want to practice using?");
int temp = input.nextInt();
String[] wordStorage = new String[temp];
String[] meaningStorage = new String[temp];
String answer;
for(int counter = 0; counter < wordStorage.length; counter++){
System.out.println("What is word number " + (1 + counter) + "?");
wordStorage[counter] = input.next();
System.out.println("What is def number " + (1 + counter) + "?");
meaningStorage[counter] = input.next();
}
if (wordStorage.length > 10) {
System.out.println("Stop. Now.");
}
System.out.println("Alright, let's get to the good stuff.");
for(int counter = 0; counter < wordStorage.length; counter++){
System.out.println("What is the meaning of " + wordStorage[counter] + "?");
answer = input.next();
if (answer == meaningStorage[counter]){
System.out.println("Correct!");
}
if (answer != meaningStorage[counter]){
System.out.println("Wrong. The answer is " + meaningStorage[counter] + ".");
}
}
}
public void spanishTree(){
System.out.println("Espere.");
}
public void ending(){
System.out.println("This is the ending of the program for now. Bye!");
}
}
The problem is under "Alright, let's get to the good stuff."
You're using == to compare Strings. Use .equals()
str1.equals(str2) instead of str1 == str2.

Categories

Resources