I'm having an issue that I've been working on most of the day. I want to get the user name, then return it twice, but can't seem to get the variable right. Here is my code.
import java.util.Random;
import java.util.ArrayList;
import java.util.Scanner;
public class mlab
{
// instance variables - this instance will get reader's name
private Scanner reader;//name from user
private Random random;//construct a Responder, declare a field type of Random
private ArrayList<String> name;//construct a responder, declare a field type ArrayList
/**
* Constructor for objects of class Calculator
* Create a responder.
* Create the Random and ArrayList object.
* Create the Scanner input object.
*/
public mlab()
{
reader = new Scanner(System.in);
random = new Random();
name = new ArrayList<String>();
}
private String getInput()
{
String user = reader.nextLine();
return user;
}
/**
*Begin the program. This will print a welcome message
*and enter into a dialog with the user, until the user ends
*the dialog.
*
* @param y a sample parameter for a method
* @return A String typed by user.
*/
public void start()
{
printWelcome();
}
/**
* Print a welcome message to the screen
*/
private void printWelcome()
{
System.out.println("Welcome to the 5th Grade Math lab");
System.out.println("What is your name?");
The code below gets the user name and returns it fine, but see a few lines down
System.out.println("Hello, " + reader.nextLine() + ". Today you can practice Addition, Subtraction, or Multiplication.");
System.out.println("Type A for Addition, S for Subtraction, or M for Multiplication.");
String inputLine = reader.nextLine();
if(inputLine.equalsIgnoreCase("A")){
printA();
}
if(inputLine.equalsIgnoreCase("S")){
printS();
}
if(inputLine.equalsIgnoreCase("M")){
printM();
}
}
private void printA()
{
random = new Random();
int num1;
int num2;
int Index = random.nextInt();
System.out.println("You have chosen to work on Addition today. The computer will now");
System.out.println("randomly select two numbers for you.");
System.out.println("The first number is: ");
System.out.println(num1 = random.nextInt(100) + 1);
System.out.println("The second number is: ");
System.out.println(num2 = random.nextInt(100) + 1);
System.out.println("Enter your answer for " + num1 + " + " + num2);
int guess = reader.nextInt();
if(guess == num1 + num2) {
//Here after Great Job, I want to output the username again and can't figure out how.
System.out.println("Great Job, ! Your answer is CORRECT! " + num1 + " + "+ num2 + " = " + (num1 + num2) + "!");
}
else {
System.out.println("Sorry, your answer is INCORRECT! " + num1 + " + " + num2 + " = " + (num1 + num2) + ".");
}
//some code omitted here
}
Can anyone help? Please!
Thank you.