Hey I don't understand why this code is wrong I'm pretty sure I did everything right logic wise. I think its the case sensitive am I right?
import java.util.Scanner;
public class Letgoshop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter item: ");
String name = input.nextline();
System.out.println("Enter Price: ");
double price = input.nextdouble();
System.out.println("Enter Quantity: ");
int m = input.nextint();
System.out.print("You owe $" + m*price + " for " + m + " " + name.toUpperCase() +"(S)");
}
}
You're misspelling the Scanner method names, they should be:
System.out.println("Enter item: ");
String name = input.nextLine();
System.out.println("Enter Price: ");
double price = input.nextDouble();
System.out.println("Enter Quantity: ");
int m = input.nextInt();
Try to correct these methods names of Scanner class:
input.nextline();
...
input.nextdouble();
...
input.nextint();
With writing them with the right name because java is case sensitive:
input.nextLine();
...
input.nextDouble();
...
input.nextInt();
Java is case sensitive, you misspelling the method.
nextline() --> nextLine()
nextdouble() -> nextDouble()
import java.util.Scanner;
public class Letgoshop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter item: ");
String name = input.nextLine();
System.out.println("Enter Price: ");
double price = input.nextDouble();
System.out.println("Enter Quantity: ");
int m = input.nextInt();
System.out.print("You owe $" + m * price + " for " + m + " " + name.toUpperCase() + "(S)");
}
}
Related
import java.util.Scanner;
public class MadLibs {
public static void main(String[] args) {
String name, place, college, profession, animal, petName;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
name = keyboard.nextLine();
System.out.print("Enter a number: ");
number = keyboard.nextInt();
System.out.print("Enter a place: ");
place = keyboard.nextLine();
System.out.print("Enter a college: ");
college = keyboard.nextLine();
System.out.print("Enter a profession: ");
profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
petName = keyboard.nextLine();
keyboard.close();
}
}
console results
Can't figure out why "enter a college" and "enter a place" are printing on the same line and not acting as separate inputs.
Try below snippet it will definitely work :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
String name = keyboard.nextLine();
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
System.out.print("Enter a place: ");
keyboard.next();
String place = keyboard.nextLine();
System.out.print("Enter a college: ");
keyboard.next();
String college = keyboard.nextLine();
System.out.print("Enter a profession: ");
String profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
String animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
String petName = keyboard.nextLine();
}
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.
enter code here
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String name, place, college, profession, animal, petName;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
name = keyboard.nextLine();
System.out.print("Enter a number: ");
number = keyboard.nextInt();
System.out.print("Enter a place: ");
place = keyboard.nextLine();
keyboard.nextLine(); //brings to next line
System.out.print("Enter a college: ");
college = keyboard.nextLine();
System.out.print("Enter a profession: ");
profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
petName = keyboard.nextLine();
keyboard.close();
}
}
Read all lines from console and store in A collection. in this context how to use scanner's methods. The number of lines user may enter is unknown.
try this:
Scanner reader = new Scanner(System.in);
List<String> a = new ArrayList<>();
while (reader.hasNextLine()) {
String s = reader.nextLine();
if (s.equals("!q")) {
break;
}
a.add(s);
}
you can try this:
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
and output will be like:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}
This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}
Below is the code I have so far, it is a calculator for my computer science class. The problem I am having is that on the second run of the program the System.out.print("Would you like to perform a calculation? (y/n) "); runs twice instead of once. I have already turned in the project, but I would like to know why it does this and how, in my future programs, I can fix it. I'll post the rest of the code below.
I appreciate all of your help, I credit the "A" that I got on it to all of you. Thanks!
/**
* A calculator with multiple functions.
* #author ()
* #version (version 2.1)
*/
import java.io.*;
import java.util.Scanner;
public class Calc
{
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
String cont = "", funct = "";
double fnum = 0, snum = 0, answer = 0;
while(true)
{
System.out.print("Would you like to perform a calculation? (y/n) ");
cont = reader.nextLine();
if (cont.equalsIgnoreCase("y"))
{
System.out.println("What function would you like to do?");
System.out.println("+?");
System.out.println("-?");
System.out.println("*?");
System.out.println("/?");
funct = reader.nextLine();
if (funct.equals("+"))
{
System.out.println("Simple addition calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum + snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("*"))
{
System.out.println("Simple multiplication calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum * snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
}
else if (cont.equalsIgnoreCase("n"))
{
break;
}
}
}
}
In all of your function conditions inside the loop, you are using reader.nextDouble(). This will only read the number (e.g "8") input not the new line (the enter) which is entered by the user after the number.
Following code for the minus(-) function will not print "Would you like to perform a calculation? (y/n) " twice as the new line is already read. Here reader.nextLine() is used instead of reader.nextDouble(). reader.nextLine() will read the whole line not only the number.
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = Double.parseDouble( reader.nextLine());
System.out.println("Enter second num: ");
snum = Double.parseDouble( reader.nextLine());
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
You need to consume the newline character after you call nextDouble() and before the next nextLine() to prevent nextLine() consume the newline character. Otherwise funct = reader.nextLine(); will take the new line character as input and not wait for any more user input, which results in the repeat.
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble(); // consume the new line character
reader.nextLine();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
Try adding this reader.nextLine(); before the while loop ends, as mentioned below. This will clear the screen buffer.
else if (cont.equalsIgnoreCase("n"))
{
break;
}
reader.nextLine();
}
Hope this helps,
Basically what is happening is when you are using the reader.nextLine() method, there is still a newline character left in the buffer, which is picked up when calling nextLine(). So it's making an extra run with the newline character. If you run your program with newline as the input even for the first time, it will loop without doing anything. So, you just need to clear out the buffer before going into your while loop.
I have a problem with some code. When I try to break my loop using "quit" it wont stop. If I begin with typing quit, it breaks as intended but the second time the loop runs and I type quit it's not breaking. What is the problem?
public static void interactionLoop() {
input = new Scanner(System.in);
String ssn = null;
String message = null;
int accountNr;
double amount;
while(true) {
for(Customers aCustomer : Customers.getCustomerList()) {
System.out.println(aCustomer.getName() + ", " + aCustomer.getSsn());
}
System.out.println("Choose a customer by using SSN.");
System.out.print(">> ");
ssn = input.nextLine();
if(ssn.equals("quit")) {
break;
}
Customers theChosenCustomer = Customers.getCustomerBasedOnSSN(ssn);
ArrayList<Accounts> accList = theChosenCustomer.getAccountList();
for(Accounts anAccount : accList) {
if(anAccount instanceof Savings) {
System.out.print("(Savings, " + anAccount.getAccountNr() + ")" + "\n");
}
if(anAccount instanceof Loans) {
System.out.print("(Loans, " + anAccount.getAccountNr() + ")" + "\n");
}
}
System.out.print("Enter the account that you want to work with using the account number:\n>> ");
accountNr = input.nextInt();
Accounts chosenAccount = theChosenCustomer.getSpecificAccount(accountNr);
System.out.println("Account balance: "+chosenAccount.getBalance());
for(Transaction t : chosenAccount.getTransaction()) {
System.out.println(t.getDateAndTime().getTime() +", " + t.getComment() +": " + t.getAmount());
}
System.out.println("\n");
System.out.print("Please enter the amount of money you wish you withdraw or deposit: ");
while(input.hasNext()) {
amount = input.nextDouble();
input.nextLine();
if(chosenAccount.isValid(amount)){
System.out.print("Please enter a comment: ");
message = input.nextLine();
Calendar transdatetime = Calendar.getInstance();
chosenAccount.makeTransaction(new Transaction(transdatetime,message,amount));
System.out.println("");
interactionLoop();
}
}
}
accountNr = input.nextInt();
From 2nd time onwards Scanner scans Integer from the Std InpuStream but then the newline remains which is taken by
ssn = input.nextLine();
due to which your program does not quit. Same goes for double. Better use
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
then use reader.readLine() and parse it into your desired data type. Eg. Integer.parseInt(reader.readLine())