For loop advances two numbers instead of one - java

When i put in the first input it prints the second and the third at the same time. Console:
Please enter the grade for course 1
A
Please enter the grade for course 2
Please enter the grade for course 3
Code:
import java.io.IOException;
public class MyGradeLoops {
public static void main(String[] args) throws IOException{
int grade;
for (int i=1; i<6; i++) {
System.out.println("Please enter the grade for course " + i);
grade = System.in.read();
}
System.out.println("Thank your for submitting your grades");
}
}

System.in.read(); will read the next byte from the user input. When you type a number and press Enter, it would count for at least three bytes (with the two additional bytes corresponding to \r and \n new line characters).
You can simply use a Scanner instance and read the integer using Scanner#nextInt().
Scanner in = new Scanner(System.in);
for (int i = 1; i < 6; i++) {
System.out.println("Please enter the grade for course " + i);
grade = in.nextInt();
}
If System.in.read() is a requirement and the grade is input as a string, here's a (sort of hacky) way to do it:
for (int i = 1; i < 6; i++) {
String grade = "";
System.out.println("Please enter the grade for course " + i);
char c;
while((c = (char) System.in.read()) != '\n') {
grade += c;
}
System.out.println(grade);
}

Related

Need help ending a program with a do while loop

I am creating a wordle project, where the word is set to "tyler". The user's guess is saved as a string, as is the wordle word, "tyler". Both the strings are saved as characters in an array, then the program checks whether each character in the arrays match.
My code is here:
// Nelson's work
import java.util.Scanner;
class FinalProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Nelson's work
int counter = 0;
do {
String word = "tyler";
System.out.println("Press enter to begin");
// Saves userInput as a string
String userInput = input.nextLine();
while (userInput.length() != 5) {
System.out.println("Enter a 5 letter word: ");
userInput = input.nextLine();
counter++;
}
// End of Nelson's work
// Tyler's work
// Creates an array of length equal to string length
char[] ch = new char[userInput.length()];
// For loop to put characters into array
for (int i = 0; i < userInput.length(); i++) {
ch[i] = userInput.charAt(i);
}
// 'For each' loop to print each element of the array
for (char c : ch) {
System.out.println(c);
}
// Creates an array of the size of the wordle word
char[] wordle = new char[word.length()];
System.out.println(" ");
// Characters of string wordle word which is 'tyler' are in an array
for (int i = 0; i < word.length(); i++) {
wordle[i] = word.charAt(i);
// System.out.println(wordle[i]);
if (wordle[i] == ch[i]) {
System.out.println("Letter " + ch[i] + " is correct");
} else {
System.out.println("Letter " + ch[i] + " is not correct");
}
}
System.out.println(" ");
} while (counter <= 5);
System.out.println("You lost!");
// End of Tyler's work
}
}
I am trying to make a do while loop that reprompts the user for a word, giving the user 5 tries, and the program would end if A) the user has had all 5 tries, or B) the user gets the word right. Please help with the loop, or if there is additional code I should try.
I tried to put the variables inside the dowhile loop, but one of the variables is from a scanner (it is user input), but I need that inside the do while loop so it reprompts the user while the counter is less than or equal to 5.

Output is not showing for second array in Java

I'm a beginner in Java programming and I created a program that accepts 10 numbers as input from users and prints them. The first section is using for loop and the second section is using while loop. The first section works properly and the second section isn't displaying output. Could anybody help me?
import java.util.Scanner;
public class ArrayOfTenElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numArray1[] = new int [10];
int numArray2[] = new int [10];
int i;
//First Section
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
for(i=0;i<10;i++) {
numArray1[i] = scanner.nextInt();
}
System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
System.out.print(numArray1[i] + " ");
}
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
System.out.println("The entered numbers are: ");
while(j<10) {
System.out.print(numArray2[j] + " ");
j++;
}
scanner.close();
}
}
You are not resetting variable j back to 0 after the 1st loop. so the 2nd loop starts with a value of 10 for j, and hence, while loop is not executed.
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
// add this
j = 0;
System.out.println("The entered numbers are: ");
while(j<10) {
System.out.print(numArray2[j] + " ");
j++;
}
When you use last for loop j value is 10 in the beginning of that loop
as you declare j out of the scope.So you should declare new variable
and replace while loop from it.The other thing is you should use for
loop to showing array2.Normally we use while loops for only when we
not knowing about end time.So we use for loop for this.
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
System.out.print(numArray2[i] + " ");
}

Loop->Array Output

I'm writing a loop to fill an array. I think I have the coding down, but when I run the compiled code through Java, it doesn't come out right in the command prompt.
Here's the code:
import java.util.Scanner;
import java.io.*;
public class Pr42
{
public static void main(String[]args) throws IOException
{
int k,m,g;
String n;
//double g;
Scanner input1=new Scanner(System.in);
String[]Name=new String [5];
double[]Grade=new double[Name.length];
k=0;
while (k<Name.length)
{
m=k+1;
System.out.print("Enter the name of student "+m+": ");
Name[k]=input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student "+m+": ");
Grade[k]=input1.nextInt();
k++;
}
}
}
Here's the output in the command prompt:
Enter the name of student 1:
Please enter the grade of student 1:
Please enter the name of student 2: Please enter the grade of student 2:
The problem is that line regarding the second student.
What did I do wrong in the code to get an output like that?
You need to identify name has input in next line with Name[k] = input1.nextLine();
int k, m, g;
String n;
//double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
m = k + 1;
System.out.print("Enter the name of student " + m + ": ");
Name[k] = input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student " + m + ": ");
Grade[k] = input1.nextDouble();
input1.nextLine();
k++;
}
EDITED: As per mentioned in Tom's comment under this answer when you have Name[k] = input1.nextLine(); instead of input1.nextLine(); program works correctly, but it messed up with value of array.
the nextInt of the Scannerdoes not read the "new line" character.
there are 2 ways to fix it.
1. call input1.nextLine(); after the input1.nextInt(); ignore what you get here, it is just to make it go to the next line.
Grade[k] = input1.nextInt();
input1.nextLine();
2. call input1.nextLine(); for the grade.
the String you get you can cast to int and save in Grade[k].
String str = input1.nextLine();
Grade[k] = Integer.parseInt(str);
This works:
public static void main(String[] args) throws IOException {
int k, m, g;
String n;
// double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
m = k + 1;
System.out.print("Enter the name of student " + m + ": ");
Name[k] = input1.nextLine();
System.out.print("Please enter the grade of student " + m + ": ");
Grade[k] = input1.nextInt();
input1.nextLine();
k++;
}
}
I recommend you to please go through this question, you shall have your doubts clarified. Excerpt from the answer given in that post:
Scanner#nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.
The problem is that: Grade[k] = input1.nextInt(); don't reads the end of line or anything after the number.
Try placing a input1.nextLine(); after Grade[k]=input1.nextInt(); should solve the issue:
while (k<Name.length)
{
m=k+1;
System.out.print("Enter the name of student "+m+": ");
Name[k]=input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student "+m+": ");
Grade[k]=input1.nextInt();
input1.nextLine();
k++;
}

I cant figure out where to put a loop

I have tried a do loop and a while loop. I just can't seem to figure out where to put a loop so once the program has completely run I want it to Question the user "Yes I want to continue" or "No" and it ends. This is a class assignment and I am using eclipse and it correct somethings which really sent me for a loop myself.
Code
import java.util.Scanner;
public class studentgpa {
public static void main(String[] args) {
Scanner consoleInput = extracted();
printGPA(consoleInput);
}
public static void printGPA(Scanner input) {
System.out.println("Enter a student record: ");
String name = extracted().next();
System.out.print("Enter Number of grades you will be entering: ");
int count = extracted().nextInt();
int sum = 0;
System.out.println("Enter Grades: 95 enter 98 enter and so on ");
for (int i = 1; i <= count; i++) {
sum += extracted().nextInt();
}
double average = (double) sum / count;
System.out.println(name + "'s grade is " + average);
}
private static Scanner extracted() {
return new Scanner(System.in);
}
}
You would need to wrap the content inside of main in a do while loop like this and prompt the user asking if they want to continue
do {
Scanner consoleInput = extracted();
printGPA(consoleInput);
System.out.println("Do you want to add another student? (Yes/No)");
String continue = consoleInput.nextLine(); // storing the user's response
} while (continue.equals("Yes"));
Just begin your function printGPA with a String like this
String continueLoop="Yes";
while("Yes".equals(continueLoop)){
///put the code you already have
continueLoop=extracted().next();
}
The code above will loop until you enter something other than "Yes".
If you need to ask the user then you need to add a loop at the begining of printGPA.
String ans="yes";
while(ans.equalsIgnoreCase("Yes")){//checks the user input is yes or no
//your code
System.out.println("Do you want to continue?");
ans=extracted().next();
}
After changes, the pringtGPA should look like this
public static void printGPA(Scanner input)
{
String ans="yes";
while(ans.equalsIgnoreCase("Yes")){
System.out.println("Enter a student record: ");
String name = extracted().next();
System.out.print("Enter Number of grades you will be entering: ");
int count = extracted().nextInt();
int sum = 0;
System.out.println("Enter Grades: 95 enter 98 enter and so on ");
for (int i = 1; i <= count; i++) {
sum += extracted().nextInt();
}
double average = (double) sum / count;
System.out.println(name + "'s grade is " + average);
System.out.println("Do you want to continue?");
ans=extracted().next();
}//end of while loop
}
Hope it helps.Happy Coding!!

How can I limit the amount of strings printed on a single line

I want to be able to enter a string s and an integer n, then print the string s n times. I have done this, but I want there to be only 2 strings per line.
Here is my code so far:
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
System.out.println(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Let's say the string was java and the number was 6. I need it to output:
java java
java java
java java
Use the modulo operator (%) to check if your loop index is evenly divisible by 2.
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=1; j<n+1; j++){
System.out.print(s);
if (j%2==0)
System.out.println("\n");
else
System.out.print(" ");
}
if(n<0){
System.out.println("error: number must be positive");
}
}
EDIT I changed the output to use print() instead of println() and added an empty space so the output is formatted as the example in your question. Also changed the for loop index to be one based so the mod works correctly.
Create a simple counter that counts to two inside your for loop. After it reaches two. Add a return character.
int count = 0;
for(int j=0; j<n; j++){
System.out.print(s);
count++;
if (count == 2) {
System.out.print("\n");
count = 0;
}
}
for(int j=0; j<n/2; j++){
System.out.println(s+" "+s);
}
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
// modified
if(j%2==0 && j!=0){
System.out.println("\n");
}
System.out.print(s); // Should this not be print and not println
System.out.print(" ");
// end of modification
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Try this code
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n/2; j++){
System.out.print(s + " " + s + "\n");
}
if(n%2 == 1){
System.out.print(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}

Categories

Resources