This is my first week of coding and I am unsure of why when I go to ask "Do you enjoy life", it forces me to type the answer on the next line.
import java.util.Scanner;
public class messing {
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter Your Name: ");
String name = keyboardInput.nextLine();
System.out.print("How old are you: ");
int age = keyboardInput.nextInt();
System.out.println(name + " you are " + age + "?" + " Do you enjoy life: " );
String enjoy = keyboardInput.next();
System.out.print(enjoy + "?");
}
}
This is because the line of code that displays the question (line 13) uses the System.out.println() function, which, in addition to the text displayed, appends a newline character. This sends any further text onto the next line in the console. Replacing the function with the System.out.print() function removes this behavior.
That's because you're using System.out.println when asking the user if they enjoy life.
Simply change the function to System.out.print like the rest so you can input your answer in the same line.
System.out.print(name + " you are " + age + "?" + " Do you enjoy life: " );
Related
I'm tryng to write a Flashcard game. I'm using a LinkedHashMap to store cards (word, definition) defined by the user. When the user tries to add a duplicated term or definition, ask again until the user inputs a unique one. Once cardDefinition and cardName are correct they are stored in Map using flashcard.put(cardName, cardDefinition).
Then I ask all card's definitions in the order of addition. If the definition is wrong for the current term but it is correct for another, output the original term.
Code:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, String> flashcards = new LinkedHashMap<>();
// Choose number of cards
System.out.println("Input the number of cards:");
int numberOfCards = Integer.parseInt(scanner.nextLine());
while (flashcards.size() < numberOfCards) {
for (int i = 0; i < numberOfCards; i++) {
System.out.println("The card # " + (i + 1) + ":");
String cardName = scanner.nextLine();
if (flashcards.containsKey(cardName)) {
System.out.println("The card \"" + cardName + "\" already exists. Try again");
cardName = scanner.nextLine();
} else {
System.out.println("The definition of the card #" + (i + 1) + ":");
String cardDefinition = scanner.nextLine();
if (flashcards.containsKey(cardDefinition)) {
System.out.println("The card \"" + cardDefinition + "\" already exists. Try again");
cardDefinition = scanner.nextLine();
}
flashcards.put(cardName, cardDefinition);
}
}
}
System.out.println(flashcards);
System.out.println(flashcards.size());
for (var entry : flashcards.entrySet()) {
System.out.println("Print the definition of " + entry.getKey());
String input = scanner.nextLine();
if (input.equals(entry.getValue())) {
System.out.println("Correct answer.");
} else {
if (flashcards.containsValue(input)) {
System.out.println("Wrong answer. The correct one is \"" + flashcards.get(input) + "\", you've just " +
"written the definition of \"" + entry.getKey() + "\"");
}
}
}
}
}
Desired output example:
Input the number of cards:
> 2
The card #1:
> a brother of one's parent
The definition of the card #1:
> uncle
The card #2:
> a part of the body where the foot and the leg meet
The definition of the card #2:
> ankle
Print the definition of "a brother of one's parent":
> ankle
Wrong answer. The correct one is "uncle", you've just written the definition of "a part of the body where the foot and the leg meet".
Print the definition of "a part of the body where the foot and the leg meet":
> ???
Wrong answer. The correct one is "ankle".
Actual output:
Input the number of cards:
2
The card # 1:
blue
The definition of the card #1:
red
The card # 2:
white
The definition of the card #2:
black
{blue=red, white=black}
2
Print the definition of blue
red
Correct answer.
Print the definition of white
red
Wrong answer. The correct one is "null", you've just written the definition of "white
I believe I'm not far from the correct code (I hope). I would like some help, please.
Hi and welcome to stackoverflow.
Wouldn't it be better to put the 'definition' as the key and the 'description' as the value? That way it is easier to get the description from the definition. you could do flashcards.get("ankle") and get a part of the body where the foot and the leg meet
Your println at the bottom looks wrong. I guess it should be:
System.out.println("Wrong answer. The correct one is \"" + entry.getValue() + "\", you've just " + "written the definition of \"" + alternate.getKey() + "\"");
where you get the alternate from this:
if (flashcards.containsValue(input)) {
Entry<String, String> alternate = null;
for (var alt : flashcards.entrySet()) {
if (alt.getValue().equals(input)) {
alternate = alt;
break;
}
}
System.out.println(
"Wrong answer. The correct one is \"" + entry.getValue() + "\", you've just " +
"written the definition of \"" + alternate.getKey() + "\""
);
}
I am stuck in the U of Helsinki Java MOOC:
Create a program that can be used to add two integers together. In the beginning, the user is asked to give two integers that are to be summed. The program then prints the formula that describes the addition of the numbers.
Example output:
Give the first number:
5
Give the second number:
4
5 + 4 = 9
I am trying to get the system to print " "first" + "second" is "result". For some reason I am stumped on this otherwise easy question. My code is always throwing an error. What am I doing wrong in the last line?
import java.util.Scanner;
public class AdditionFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// write your program here
System.out.println("Give the first number: ");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Give the second number: ");
int second = Integer.valueOf(scanner.nextLine());
//System.out.println("first" " + " Integer.valueOf(first) + Integer.valueOf(second));
System.out.println(first + " + " + second " = " + (first + second));
}
The code you provided does not compile
Change to
System.out.println(first + " + " + second + " = " + (first + second));
So I have a loop that runs which takes input from the user via a scanner and System.in. The scanner is just called s. I use s.nextInt to get an int for my switch, where I have a lot of cases, so the user has some choices. Now in one of those cases, I use another scanner, and when I close it and the function terminates (which takes me back to my while loop) I want to take a new int from the user, to choose the next thing they want to do. This time around it throws an NoSuchElementException. I used the "I'm before" and "I'm after" and the userrequest = s.nextInt is where I get the error. Any ideas? My function is way too long to post, but it doesn't really do anything that should interfere, except open a new scanner, but I have other functions which does that, but doesn't break it.
while (on) {
System.out.println("What may I do for you today? ");
System.out.println("I'm before");
int userrequest = s.nextInt();
System.out.println("I'm after");
switch (userrequest) {
case 1:
System.out.println("");........
EDIT: Okay, I edited out some non important stuff from the function. This is the function it runs, before returning to my while loop:
public static void buysystem(Connection con, Scanner sysbuy) {
System.out.println("What system do you want to buy?");
String sysreq = sysbuy.next().toUpperCase();
try {
Statement st = con.createStatement();
String query = "SQL";
ResultSet rs = st.executeQuery(query);
rs.next();
String nome = rs.getString("noob");
int price = rs.getInt("cpuprice") + rs.getInt("ramprice") + rs.getInt("mainboardprice") + rs.getInt("casesprice") + rs.getInt("gfxprice");
System.out.println("How many systems do you want to buy?");
int sysamount = sysbuy.nextInt();
//NEED TO MAKE CHECK AMOUNT FUNCTION
int realprice;
if (sysamount>10){
realprice = (price*130/100)-((price*130/100*120/100)-(price*130/100));
System.out.println("You want to buy " + sysamount + " of the system: " + sysreq + " for the price of " + realprice + "?");
System.out.println("Yes/No?");
String yesno = sysbuy.next();
if (yesno.toUpperCase().equals("YES")){
System.out.println("You just bought " + sysamount + " of the system " + sysreq + " for the price of " + realprice);
//UPDATE DB
}
}
else{
realprice = (price*130/100)-((price*130/100*(sysamount*2+100-2)/100)-(price*130/100));
System.out.println("You want to buy " + sysamount + " of the system: " + sysreq + " for the price of " + realprice + "?");
System.out.println("Yes/No?");
String yesno = sysbuy.next();
if (yesno.toUpperCase().equals("YES")){
System.out.println("You just bought " + sysamount + " of the system " + sysreq + " for the price of " + realprice);
//UPDATE DB
}
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Print me");
}
I get this error now:
You just bought 1 of the system SERVER1 for the price of 7540
Print me
What may I do for you today?
I'm before
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at DBtest.requestHandler(DBtest.java:43)
at DBtest.main(DBtest.java:24)
Do not create multiple Scanners, instead use one scanner and use it inside your function or pass it to it if it is out of scope.
You created multiple Scanners, which you should not do, but also closed the second scanner. When you closed that scanner you closed the input stream which both scanners are using (the System's inputstream). This is what caused your crash.
I get this error; bad operand types for binary operator '-'
All other operations work...when I leave out the subtraction via comments like // and /* */; can someone help?
This is the code by the way; the exception is on the subtraction line.
public class Calculator {
/*
*use 'javac Calculator.java' to compile;
*use 'jar cvf Calculator.jar Calculator.class' for jar;
*use 'java Calculator' to run;
*/
public static void main(String []args) {
String NewName
Scanner user_input = new Scanner( System.in );
System.out.println("Type your name please.");
NewName = user_input.next();
System.out.println("");
System.out.println("Hello " + NewName + ".");
System.out.println("I am Hunter's java calculator program.");
System.out.println("");
//mathematical input
String operator;
float cal1, cal2;
System.out.println("Type a Number...");
cal1 = user_input.nextFloat();
System.out.println("");
System.out.println("Type another Number...");
cal2 = user_input.nextFloat();
System.out.println("");
Scanner opt = new Scanner(System.in);
System.out.println("Enter an operator");
operator = opt.next();
//operation decisions
if (operator.equals("+")){
System.out.println("The answer is " + cal1+cal2 + ".");
}
if (operator.equals("-")){
System.out.println("The answer is " + cal1-cal2 + ".");
}
if (operator.equals("/")){
System.out.println("The answer is " + cal1/cal2 + ".");
}
if (operator.equals("*")){
System.out.println("The answer is " + cal1*cal2 + ".");
}
}
}
You need parenthesis:
System.out.println("The answer is " + (cal1-cal2) + ".");
Otherwise what you have is treated as
System.out.println(("The answer is " + cal1) - (cal2 + "."));
which is invalid since you can't subtract strings.
Why don't you have an error with the other operators? Well, * and / have higher precedences, so those are working as expected. +, on the other hand, is overloaded to concatenate strings:
System.out.println("The answer is " + cal1+cal2 + "."); // concatenates, doesn't add
For example, if call1 is 1 and call2 is 2, the result will be:
The answer is 12.
which isn't what you want. Again, this can be solved with parenthesis.
I have this assignment in school, where I have to import a scanner and write a method. What am I doing wrong?
public static void main(String[] args)
{
applicationDate();
}
public static void applicationDate()
{
Scanner input = new Scanner(System.in);
System.out.println("On what day of the month you applied?");
int day = input.nextInt();
System.out.println("What is the name of the month in wich you applied?");
String month = input.nextLine();
System.out.println("During wich year you applied?");
int year = input.nextInt();
System.out.print("Your application date is" + month + " ", + year + "!");
}
It comes with this error when I compile the thing,
EX20.java:27: cannot find symbol
print only takes one String argument - move the comma inside the String
System.out.print("Your application date is" + month + " ," + year + "!");
^
Remove comma and add it in between double quotes like below.
System.out.print("Your application date is" + month + " ,"+ year + "!");
First add import java.util.Scanner; to your file.
As this line is missing you must be getting error as
error: cannot find symbol
Scanner input = new Scanner(System.in);
^
then
Remove extra comma from the last print statement.
System.out.print("Your application date is" + month + " ,"+ year + "!");