I need help. I want to ask the user if he wants to try again, but something seems to be wrong with my code, because it's not working.
public class TotoAzul
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n1, n2, sum;
String answer;
do {
System.out.println("Enter number 1: ");
n1 = keyboard.nextInt();
System.out.println("Enter number 2: ");
n2 = keyboard.nextInt();
sum = n1 + n2;
System.out.println("Number 1\t" + "Number 2\t" + "Sum");
System.out.println("__________________________________");
System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
keyboard.nextLine();
}
while(answer.equalsIgnoreCase("YES"));
}
}
When I run it, it stores the user's answer, yet the program doesn't repeat. How can I fix this?
Move the keyboard.nextLine(); after n2 = keyboard.nextInt(); to accept and ignore the dangling newline character in the inputstream left behind by call to nextInt().
When I run it, it stores the user's answer - Try printing what it has stored in the answer field then you will see the problem.
Scanner keyboard = new Scanner(System.in);
int n1, n2, sum;
String answer = "Yes";
while (answer.equals("Yes"))
{
System.out.println("Enter number 1: ");
n1 = keyboard.nextInt();
System.out.println("Enter number 2: ");
n2 = keyboard.nextInt();
sum = n1 + n2;
System.out.println("Number 1\t" + "Number 2\t" + "Sum");
System.out.println("__________________________________");
System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
keyboard.nextLine();
}
Change the position of keyboard.nextLine();.
keyboard.nextLine();
answer = keyboard.nextLine();
In your code answer is getting next line(i.e. enter), which comes into picture when you take value of n2 and press enter.
You can test your code by executing below code
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
System.out.println("Answer : " + answer);
System.out.println(keyboard.nextLine());
Related
I am very new to Java. So I've created a script to receive input of a score, and then give a mark as output based on this score. My issue is I want the code to repeat to allow for entry of multiple scores, but I can't get it to work.
Edit: I have tried using the methods in the answers but I can't get it right. would it be possible for someone to do implement the loop into my code for me?
Here's my code:
import java.util.Scanner;
public class week4
{
public static void main(String[] args)
{
{
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
}
}
First, let's refactor the main logic into another method called calcGrade():
public void calcGrade() {
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
If we invoke this method, it will load a new student name & score from System.in, calculate the grade then print it.
Okay, the next part will be the loop.
There are 3 types of loop in Java, for/while/do-while.
You can use "for" when you know exactly what times you want to loop.
E.g. You know there is only 10 students in your class, then you can write such codes:
for (int i = 0; i < 10; i++) {
calcGrade();
}
If you don't know the times, but you know there is an exact condition to end the loop, you can use while or do-while. The difference between while and do-while is while can do the condition check first then do the inner logic, and do-while always do the inner logic for once time then check the condition.
E.g. You want to continue the loop when you acquire a String "YES" from the System.in.
System.out.println("Please input the first student info, YES or NO?");
Scanner inText = new Scanner(System.in);
while ("YES".equals(inText.nextLine()) {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
}
Also, you can use the do-while, if you know there are at least one people in the class.
Scanner inText = new Scanner(System.in);
do {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
} while ("YES".equals(inText.nextLine());
Hopes it's clear for you ;)
Easiest wway I can think of is to create a class called student and have variables for name, subjects, scores etc. Have setters and getters if you want or just have a constructor which takes in those inputs. Next have a method like computeGrade(). Creates instances of this student class every time you want some thing.
puclic class Student{
public String mName;
public String mSub1;
.
public int m_scoreSub1;
.
.
public computeScore(int m_score){
* your logic goes here ( the if else one)
}
}
Now just instantiate the class !!!
I'm trying to make a simple calculator console app. The answer stays 0 no matter what I do. Can anyone tell me what is wrong if anything is wrong without giving me a direct answer.
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
System.out.print("Please enter first number: ");
firstNum = input.nextInt();
System.out.print("Please enter second number: ");
secondNum = input.nextInt();
System.out.println("What type of operation would you like to perform?");
System.out.println("add, multiply, subtract or divide.");
input.nextLine();
userChoice = input.nextLine();
if (userChoice.equals("add"))
System.out.print("The answer is " + addition);
else if (userChoice.equals("multiply"))
System.out.print("The answer is " + multiplication);
else if (userChoice.equals("subtract"))
System.out.print("The answer is " + subtraction);
else if (userChoice.equals("divide"))
System.out.print("The answer is " + division);
division = firstNum / secondNum;
addition = firstNum + secondNum;
subtraction = firstNum - secondNum;
multiplication = firstNum * secondNum;
}
}
As others have already said, the calculation needs to be done before the output.
I suggest some more improvements:
Use proper variable naming. For example, addition is an operation but the variable holds the result of this operation which is usually called sum. So use these names for your variables. Actually, you don't need four different variables, see below.
Declare your variables where you need them, not at the beginning of the function.
In your code, the four possible calculations are always performed, not only the one selected by the user.
The second part of your code (after the input) could look like this:
int result = 0;
if (userChoice.equals("add")) {
result = firstNum + secondNum;
}
else if (userChoice.equals("subtract")) {
result = firstNum - secondNum;
}
else if (userChoice.equals("multiply")) {
result = firstNum * secondNum;
}
else if (userChoice.equals("divide")) {
// maybe check if secondNum is not zero
result = firstNum / secondNum;
}
else {
System.out.print("Invalid input " + userChoice);
return;
}
System.out.print("The answer is " + result);
I'm creating a program which prints a summary of the situation after interactive input has ended (ctrl - d). So it prints a summary of the average age and percentage of children who have received vaccines after interactive input.
However, I'm always receiving the No Line Found error whenever I press ctrl-d at Name:. My compiler tells me the error is at name = sc.nextLine(); within the while loop but I don't know what is causing the error exactly.
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
You do not correctly implement an exit condition for your loop if you ask me.
Try something like this:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
This way you can quit entering new persons without having to enter a strange command that might lead to an error. Furthermore, a do-while loop helps you to reduce your code, because you don't have to use the same code twice, i.e., everything between Scanner sc = new Scanner(System.in); and while(sc.hasNextLine()) in your example.
How can I print the sum of the 2nd to the last digit of each integer on java?
(so, 8 would be printed since 1 + 3 + 4 is 8 , and 35 would be printed since 3453 + 65324 + 354) in the following Program: * without using if statements *
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10;
System.out.print((num1/10) % 10 + " + " + (num2/10) % 10 + " + " + (num3/10) % 10 + " = " + sumSecToLast);
}//main
}//Pr6
Once you've scanned all the integers:
//In main method:
int secLast1 = Pr6.getSecLastDigit(num1);
int secLast2 = Pr6.getSecLastDigit(num2);
int secLast3 = Pr6.getSecLastDigit(num3);
int sum = secLast1 + secLast2 + secLast3;
System.out.println(secLast1 + " + " + secLast2 + " + " + secLast3 + " = " + sum);
You also want to create the additional method:
private static int getSecLastDigit(int num) {
return (num / 10) % 10;
}
Here is how I would do it. Depending on your definition of an if statement this might not work for you (spoiler).
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int total = 0;
String num1, num2, num3;
System.out.print("Please write an integer: ");
num1 = scan.nextLine(); // rather than taking an integer this takes a String because it is easier to extract a single element.
... // get the other numbers
for (int i = 1; i < num1.length(); i++){
total += Character.getNumericValue(num1.charAt(i)); // adds each number to the total
}
... // do this for the other Strings (or use another loop for with a String[])
System.out.println(total);
}//main
}//Pr6
To make this more concise I would highly recommend using a String[] rather than 3 different variables. Also I am assuming a for loop doesn't count as an if statement. However I realize that because of the boolean check they may be considered too similar for your current situation. I hope this helps! :)
Sorry for inconvenience. My question was misunderstood. I meant that I want to write a code to find the sum of the 2nd to the last digit of a three different integers. For ex: if the user entered 15, 34, and 941, which in this case the 2nd to the last digit will be 1, 3, and 4. Therefore, the subtotal of them will be 1+3+4 = 8.
I found out the answer and I wanted to share it with everyone, and also I would like to thank all of those who tried to help.
thank you..
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = ((num1/10) % 10) + ((num2/10) % 10) + ((num3/10) % 10);
System.out.println("The subtotal of the 2nd to the last digit = " + sumSecToLast);
System.out.println();
}//main
}//Pr6
I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}